context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use the Utilities SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/utilities-1.31 Unless required by applicable law or agreed to in writing, the Utilities SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; /// <summary> /// Plays tactile effects on a tracked VR controller. /// </summary> public static class OVRHaptics { public readonly static OVRHapticsChannel[] Channels; public readonly static OVRHapticsChannel LeftChannel; public readonly static OVRHapticsChannel RightChannel; private readonly static OVRHapticsOutput[] m_outputs; static OVRHaptics() { Config.Load(); m_outputs = new OVRHapticsOutput[] { new OVRHapticsOutput((uint)OVRPlugin.Controller.LTouch), new OVRHapticsOutput((uint)OVRPlugin.Controller.RTouch), }; Channels = new OVRHapticsChannel[] { LeftChannel = new OVRHapticsChannel(0), RightChannel = new OVRHapticsChannel(1), }; } /// <summary> /// Determines the target format for haptics data on a specific device. /// </summary> public static class Config { public static int SampleRateHz { get; private set; } public static int SampleSizeInBytes { get; private set; } public static int MinimumSafeSamplesQueued { get; private set; } public static int MinimumBufferSamplesCount { get; private set; } public static int OptimalBufferSamplesCount { get; private set; } public static int MaximumBufferSamplesCount { get; private set; } static Config() { Load(); } public static void Load() { OVRPlugin.HapticsDesc desc = OVRPlugin.GetControllerHapticsDesc((uint)OVRPlugin.Controller.RTouch); SampleRateHz = desc.SampleRateHz; SampleSizeInBytes = desc.SampleSizeInBytes; MinimumSafeSamplesQueued = desc.MinimumSafeSamplesQueued; MinimumBufferSamplesCount = desc.MinimumBufferSamplesCount; OptimalBufferSamplesCount = desc.OptimalBufferSamplesCount; MaximumBufferSamplesCount = desc.MaximumBufferSamplesCount; } } /// <summary> /// A track of haptics data that can be mixed or sequenced with another track. /// </summary> public class OVRHapticsChannel { private OVRHapticsOutput m_output; /// <summary> /// Constructs a channel targeting the specified output. /// </summary> public OVRHapticsChannel(uint outputIndex) { m_output = m_outputs[outputIndex]; } /// <summary> /// Cancels any currently-playing clips and immediatly plays the specified clip instead. /// </summary> public void Preempt(OVRHapticsClip clip) { m_output.Preempt(clip); } /// <summary> /// Enqueues the specified clip to play after any currently-playing clips finish. /// </summary> public void Queue(OVRHapticsClip clip) { m_output.Queue(clip); } /// <summary> /// Adds the specified clip to play simultaneously to the currently-playing clip(s). /// </summary> public void Mix(OVRHapticsClip clip) { m_output.Mix(clip); } /// <summary> /// Cancels any currently-playing clips. /// </summary> public void Clear() { m_output.Clear(); } } private class OVRHapticsOutput { private class ClipPlaybackTracker { public int ReadCount { get; set; } public OVRHapticsClip Clip { get; set; } public ClipPlaybackTracker(OVRHapticsClip clip) { Clip = clip; } } private bool m_lowLatencyMode = true; private bool m_paddingEnabled = true; private int m_prevSamplesQueued = 0; private float m_prevSamplesQueuedTime = 0; private int m_numPredictionHits = 0; private int m_numPredictionMisses = 0; private int m_numUnderruns = 0; private List<ClipPlaybackTracker> m_pendingClips = new List<ClipPlaybackTracker>(); private uint m_controller = 0; private OVRNativeBuffer m_nativeBuffer = new OVRNativeBuffer(OVRHaptics.Config.MaximumBufferSamplesCount * OVRHaptics.Config.SampleSizeInBytes); private OVRHapticsClip m_paddingClip = new OVRHapticsClip(); public OVRHapticsOutput(uint controller) { #if UNITY_ANDROID m_paddingEnabled = false; #endif m_controller = controller; } /// <summary> /// The system calls this each frame to update haptics playback. /// </summary> public void Process() { var hapticsState = OVRPlugin.GetControllerHapticsState(m_controller); float elapsedTime = Time.realtimeSinceStartup - m_prevSamplesQueuedTime; if (m_prevSamplesQueued > 0) { int expectedSamples = m_prevSamplesQueued - (int)(elapsedTime * OVRHaptics.Config.SampleRateHz + 0.5f); if (expectedSamples < 0) expectedSamples = 0; if ((hapticsState.SamplesQueued - expectedSamples) == 0) m_numPredictionHits++; else m_numPredictionMisses++; //Debug.Log(hapticsState.SamplesAvailable + "a " + hapticsState.SamplesQueued + "q " + expectedSamples + "e " //+ "Prediction Accuracy: " + m_numPredictionHits / (float)(m_numPredictionMisses + m_numPredictionHits)); if ((expectedSamples > 0) && (hapticsState.SamplesQueued == 0)) { m_numUnderruns++; //Debug.LogError("Samples Underrun (" + m_controller + " #" + m_numUnderruns + ") -" // + " Expected: " + expectedSamples // + " Actual: " + hapticsState.SamplesQueued); } m_prevSamplesQueued = hapticsState.SamplesQueued; m_prevSamplesQueuedTime = Time.realtimeSinceStartup; } int desiredSamplesCount = OVRHaptics.Config.OptimalBufferSamplesCount; if (m_lowLatencyMode) { float sampleRateMs = 1000.0f / (float)OVRHaptics.Config.SampleRateHz; float elapsedMs = elapsedTime * 1000.0f; int samplesNeededPerFrame = (int)Mathf.Ceil(elapsedMs / sampleRateMs); int lowLatencySamplesCount = OVRHaptics.Config.MinimumSafeSamplesQueued + samplesNeededPerFrame; if (lowLatencySamplesCount < desiredSamplesCount) desiredSamplesCount = lowLatencySamplesCount; } if (hapticsState.SamplesQueued > desiredSamplesCount) return; if (desiredSamplesCount > OVRHaptics.Config.MaximumBufferSamplesCount) desiredSamplesCount = OVRHaptics.Config.MaximumBufferSamplesCount; if (desiredSamplesCount > hapticsState.SamplesAvailable) desiredSamplesCount = hapticsState.SamplesAvailable; int acquiredSamplesCount = 0; int clipIndex = 0; while(acquiredSamplesCount < desiredSamplesCount && clipIndex < m_pendingClips.Count) { int numSamplesToCopy = desiredSamplesCount - acquiredSamplesCount; int remainingSamplesInClip = m_pendingClips[clipIndex].Clip.Count - m_pendingClips[clipIndex].ReadCount; if (numSamplesToCopy > remainingSamplesInClip) numSamplesToCopy = remainingSamplesInClip; if (numSamplesToCopy > 0) { int numBytes = numSamplesToCopy * OVRHaptics.Config.SampleSizeInBytes; int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes; int srcOffset = m_pendingClips[clipIndex].ReadCount * OVRHaptics.Config.SampleSizeInBytes; Marshal.Copy(m_pendingClips[clipIndex].Clip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes); m_pendingClips[clipIndex].ReadCount += numSamplesToCopy; acquiredSamplesCount += numSamplesToCopy; } clipIndex++; } for (int i = m_pendingClips.Count - 1; i >= 0 && m_pendingClips.Count > 0; i--) { if (m_pendingClips[i].ReadCount >= m_pendingClips[i].Clip.Count) m_pendingClips.RemoveAt(i); } if (m_paddingEnabled) { int desiredPadding = desiredSamplesCount - (hapticsState.SamplesQueued + acquiredSamplesCount); if (desiredPadding < (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount)) desiredPadding = (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount); if (desiredPadding > hapticsState.SamplesAvailable) desiredPadding = hapticsState.SamplesAvailable; if (desiredPadding > 0) { int numBytes = desiredPadding * OVRHaptics.Config.SampleSizeInBytes; int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes; int srcOffset = 0; Marshal.Copy(m_paddingClip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes); acquiredSamplesCount += desiredPadding; } } if (acquiredSamplesCount > 0) { OVRPlugin.HapticsBuffer hapticsBuffer; hapticsBuffer.Samples = m_nativeBuffer.GetPointer(); hapticsBuffer.SamplesCount = acquiredSamplesCount; OVRPlugin.SetControllerHaptics(m_controller, hapticsBuffer); hapticsState = OVRPlugin.GetControllerHapticsState(m_controller); m_prevSamplesQueued = hapticsState.SamplesQueued; m_prevSamplesQueuedTime = Time.realtimeSinceStartup; } } /// <summary> /// Immediately plays the specified clip without waiting for any currently-playing clip to finish. /// </summary> public void Preempt(OVRHapticsClip clip) { m_pendingClips.Clear(); m_pendingClips.Add(new ClipPlaybackTracker(clip)); } /// <summary> /// Enqueues the specified clip to play after any currently-playing clip finishes. /// </summary> public void Queue(OVRHapticsClip clip) { m_pendingClips.Add(new ClipPlaybackTracker(clip)); } /// <summary> /// Adds the samples from the specified clip to the ones in the currently-playing clip(s). /// </summary> public void Mix(OVRHapticsClip clip) { int numClipsToMix = 0; int numSamplesToMix = 0; int numSamplesRemaining = clip.Count; while (numSamplesRemaining > 0 && numClipsToMix < m_pendingClips.Count) { int numSamplesRemainingInClip = m_pendingClips[numClipsToMix].Clip.Count - m_pendingClips[numClipsToMix].ReadCount; numSamplesRemaining -= numSamplesRemainingInClip; numSamplesToMix += numSamplesRemainingInClip; numClipsToMix++; } if (numSamplesRemaining > 0) { numSamplesToMix += numSamplesRemaining; numSamplesRemaining = 0; } if (numClipsToMix > 0) { OVRHapticsClip mixClip = new OVRHapticsClip(numSamplesToMix); OVRHapticsClip a = clip; int aReadCount = 0; for (int i = 0; i < numClipsToMix; i++) { OVRHapticsClip b = m_pendingClips[i].Clip; for(int bReadCount = m_pendingClips[i].ReadCount; bReadCount < b.Count; bReadCount++) { if (OVRHaptics.Config.SampleSizeInBytes == 1) { byte sample = 0; // TODO support multi-byte samples if ((aReadCount < a.Count) && (bReadCount < b.Count)) { sample = (byte)(Mathf.Clamp(a.Samples[aReadCount] + b.Samples[bReadCount], 0, System.Byte.MaxValue)); // TODO support multi-byte samples aReadCount++; } else if (bReadCount < b.Count) { sample = b.Samples[bReadCount]; // TODO support multi-byte samples } mixClip.WriteSample(sample); // TODO support multi-byte samples } } } while (aReadCount < a.Count) { if (OVRHaptics.Config.SampleSizeInBytes == 1) { mixClip.WriteSample(a.Samples[aReadCount]); // TODO support multi-byte samples } aReadCount++; } m_pendingClips[0] = new ClipPlaybackTracker(mixClip); for (int i = 1; i < numClipsToMix; i++) { m_pendingClips.RemoveAt(1); } } else { m_pendingClips.Add(new ClipPlaybackTracker(clip)); } } public void Clear() { m_pendingClips.Clear(); } } /// <summary> /// The system calls this each frame to update haptics playback. /// </summary> public static void Process() { Config.Load(); for (int i = 0; i < m_outputs.Length; i++) { m_outputs[i].Process(); } } }
using System.Diagnostics; namespace Community.CsharpSqlite { public partial class Sqlite3 { /***** This file contains automatically generated code ****** ** ** The code in this file has been automatically generated by ** ** sqlite/tool/mkkeywordhash.c ** ** The code in this file implements a function that determines whether ** or not a given identifier is really an SQL keyword. The same thing ** might be implemented more directly using a hand-written hash table. ** But by using this automatically generated code, the size of the code ** is substantially reduced. This is important for embedded applications ** on platforms with limited memory. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7 ** ** $Header$ ************************************************************************* */ /* Hash score: 175 */ static int keywordCode( string z, int iOffset, int n ) { /* zText[] encodes 811 bytes of keywords in 541 bytes */ /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */ /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */ /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */ /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */ /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */ /* INITIALLY */ string zText = new string( new char[540] { 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G', #if !SQLITE_OMIT_TRIGGER 'E', #else '\0', #endif 'R', #if !SQLITE_OMIT_FOREIGN_KEY 'E', #else '\0', #endif 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U', 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S', 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C', 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L', 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D', 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E', 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A', 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U', 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W', 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C', 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R', 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M', 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U', 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M', 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T', 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L', 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S', 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L', 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V', 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y', } ); byte[] aHash = { //aHash[127] 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0, 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0, 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67, 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44, 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25, 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0, 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14, 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109, 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0, 29, 0, 82, 59, 60, 0, 20, 57, 0, 52, }; byte[] aNext = { //aNext[121] 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1, 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0, 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0, 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0, 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0, 35, 64, 0, 0, }; byte[] aLen = { //aLen[121] 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6, 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; int[] aOffset = { //aOffset[121] 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527, 531, 536, }; byte[] aCode = { //aCode[121 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, }; int h, i; if ( n < 2 ) return TK_ID; h = ( ( sqlite3UpperToLower[z[iOffset + 0]] ) * 4 ^//(charMap(z[iOffset+0]) * 4) ^ ( sqlite3UpperToLower[z[iOffset + n - 1]] * 3 ) ^ //(charMap(z[iOffset+n - 1]) * 3) ^ n ) % 127; for ( i = ( aHash[h] ) - 1; i >= 0; i = ( aNext[i] ) - 1 ) { if ( aLen[i] == n && 0 == sqlite3StrNICmp( zText.Substring( aOffset[i],n), z.Substring( iOffset, n ), n ) ) { testcase( i == 0 ); /* REINDEX */ testcase( i == 1 ); /* INDEXED */ testcase( i == 2 ); /* INDEX */ testcase( i == 3 ); /* DESC */ testcase( i == 4 ); /* ESCAPE */ testcase( i == 5 ); /* EACH */ testcase( i == 6 ); /* CHECK */ testcase( i == 7 ); /* KEY */ testcase( i == 8 ); /* BEFORE */ testcase( i == 9 ); /* FOREIGN */ testcase( i == 10 ); /* FOR */ testcase( i == 11 ); /* IGNORE */ testcase( i == 12 ); /* REGEXP */ testcase( i == 13 ); /* EXPLAIN */ testcase( i == 14 ); /* INSTEAD */ testcase( i == 15 ); /* ADD */ testcase( i == 16 ); /* DATABASE */ testcase( i == 17 ); /* AS */ testcase( i == 18 ); /* SELECT */ testcase( i == 19 ); /* TABLE */ testcase( i == 20 ); /* LEFT */ testcase( i == 21 ); /* THEN */ testcase( i == 22 ); /* END */ testcase( i == 23 ); /* DEFERRABLE */ testcase( i == 24 ); /* ELSE */ testcase( i == 25 ); /* EXCEPT */ testcase( i == 26 ); /* TRANSACTION */ testcase( i == 27 ); /* ACTION */ testcase( i == 28 ); /* ON */ testcase( i == 29 ); /* NATURAL */ testcase( i == 30 ); /* ALTER */ testcase( i == 31 ); /* RAISE */ testcase( i == 32 ); /* EXCLUSIVE */ testcase( i == 33 ); /* EXISTS */ testcase( i == 34 ); /* SAVEPOINT */ testcase( i == 35 ); /* INTERSECT */ testcase( i == 36 ); /* TRIGGER */ testcase( i == 37 ); /* REFERENCES */ testcase( i == 38 ); /* CONSTRAINT */ testcase( i == 39 ); /* INTO */ testcase( i == 40 ); /* OFFSET */ testcase( i == 41 ); /* OF */ testcase( i == 42 ); /* SET */ testcase( i == 43 ); /* TEMPORARY */ testcase( i == 44 ); /* TEMP */ testcase( i == 45 ); /* OR */ testcase( i == 46 ); /* UNIQUE */ testcase( i == 47 ); /* QUERY */ testcase( i == 48 ); /* ATTACH */ testcase( i == 49 ); /* HAVING */ testcase( i == 50 ); /* GROUP */ testcase( i == 51 ); /* UPDATE */ testcase( i == 52 ); /* BEGIN */ testcase( i == 53 ); /* INNER */ testcase( i == 54 ); /* RELEASE */ testcase( i == 55 ); /* BETWEEN */ testcase( i == 56 ); /* NOTNULL */ testcase( i == 57 ); /* NOT */ testcase( i == 58 ); /* NO */ testcase( i == 59 ); /* NULL */ testcase( i == 60 ); /* LIKE */ testcase( i == 61 ); /* CASCADE */ testcase( i == 62 ); /* ASC */ testcase( i == 63 ); /* DELETE */ testcase( i == 64 ); /* CASE */ testcase( i == 65 ); /* COLLATE */ testcase( i == 66 ); /* CREATE */ testcase( i == 67 ); /* CURRENT_DATE */ testcase( i == 68 ); /* DETACH */ testcase( i == 69 ); /* IMMEDIATE */ testcase( i == 70 ); /* JOIN */ testcase( i == 71 ); /* INSERT */ testcase( i == 72 ); /* MATCH */ testcase( i == 73 ); /* PLAN */ testcase( i == 74 ); /* ANALYZE */ testcase( i == 75 ); /* PRAGMA */ testcase( i == 76 ); /* ABORT */ testcase( i == 77 ); /* VALUES */ testcase( i == 78 ); /* VIRTUAL */ testcase( i == 79 ); /* LIMIT */ testcase( i == 80 ); /* WHEN */ testcase( i == 81 ); /* WHERE */ testcase( i == 82 ); /* RENAME */ testcase( i == 83 ); /* AFTER */ testcase( i == 84 ); /* REPLACE */ testcase( i == 85 ); /* AND */ testcase( i == 86 ); /* DEFAULT */ testcase( i == 87 ); /* AUTOINCREMENT */ testcase( i == 88 ); /* TO */ testcase( i == 89 ); /* IN */ testcase( i == 90 ); /* CAST */ testcase( i == 91 ); /* COLUMN */ testcase( i == 92 ); /* COMMIT */ testcase( i == 93 ); /* CONFLICT */ testcase( i == 94 ); /* CROSS */ testcase( i == 95 ); /* CURRENT_TIMESTAMP */ testcase( i == 96 ); /* CURRENT_TIME */ testcase( i == 97 ); /* PRIMARY */ testcase( i == 98 ); /* DEFERRED */ testcase( i == 99 ); /* DISTINCT */ testcase( i == 100 ); /* IS */ testcase( i == 101 ); /* DROP */ testcase( i == 102 ); /* FAIL */ testcase( i == 103 ); /* FROM */ testcase( i == 104 ); /* FULL */ testcase( i == 105 ); /* GLOB */ testcase( i == 106 ); /* BY */ testcase( i == 107 ); /* IF */ testcase( i == 108 ); /* ISNULL */ testcase( i == 109 ); /* ORDER */ testcase( i == 110 ); /* RESTRICT */ testcase( i == 111 ); /* OUTER */ testcase( i == 112 ); /* RIGHT */ testcase( i == 113 ); /* ROLLBACK */ testcase( i == 114 ); /* ROW */ testcase( i == 115 ); /* UNION */ testcase( i == 116 ); /* USING */ testcase( i == 117 ); /* VACUUM */ testcase( i == 118 ); /* VIEW */ testcase( i == 119 ); /* INITIALLY */ testcase( i == 120 ); /* ALL */ return aCode[i]; } } return TK_ID; } static int sqlite3KeywordCode( string z, int n ) { return keywordCode( z, 0, n ); } public const int SQLITE_N_KEYWORD = 121;//#define SQLITE_N_KEYWORD 121 } }
// 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.Diagnostics.Contracts; using System.Linq.Internal; using System.Runtime.InteropServices; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableArray{T}" />. /// </summary> static class ImmutableArray { /// <summary> /// A two element array useful for throwing exceptions the way LINQ does. /// </summary> internal static readonly byte[] TwoElementArray = new byte[2]; /// <summary> /// Creates an empty ImmutableArray{T}. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <returns>An empty array.</returns> [Pure] public static ImmutableArray<T> Create<T>() { return ImmutableArray<T>.Empty; } /// <summary> /// Creates an ImmutableArray{T} with the specified element as its only member. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item">The element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item) { T[] array = new[] { item }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2) { T[] array = new[] { item1, item2 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3) { T[] array = new[] { item1, item2, item3 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <param name="item4">The third element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4) { T[] array = new[] { item1, item2, item3, item4 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} populated with the contents of the specified sequence. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items) { Requires.NotNull(items, "items"); // As an optimization, if the provided enumerable is actually a // boxed ImmutableArray<T> instance, reuse the underlying array if possible. // Note that this allows for automatic upcasting and downcasting of arrays // where the CLR allows it. var immutableArray = items as IImmutableArray; if (immutableArray != null) { immutableArray.ThrowInvalidOperationIfNotInitialized(); var existingImmutableArray = immutableArray.Array as T[]; if (existingImmutableArray != null || immutableArray.Array == null) { return new ImmutableArray<T>(existingImmutableArray); } } // We don't recognize the source as an array that is safe to use. // So clone the sequence into an array and return an immutable wrapper. int count; if (items.TryGetCount(out count)) { if (count == 0) { // Return a wrapper around the singleton empty array. return Create<T>(); } else { // We know how long the sequence is. Linq's built-in ToArray extension method // isn't as comprehensive in finding the length as we are, so call our own method // to avoid reallocating arrays as the sequence is enumerated. return new ImmutableArray<T>(items.ToArray(count)); } } else { return new ImmutableArray<T>(items.ToArray()); } } /// <summary> /// Creates an empty ImmutableArray{T}. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> Create<T>(params T[] items) { if (items == null) { return Create<T>(); } // We can't trust that the array passed in will never be mutated by the caller. // The caller may have passed in an array explicitly (not relying on compiler params keyword) // and could then change the array after the call, thereby violating the immutable // guarantee provided by this struct. So we always copy the array to ensure it won't ever change. return CreateDefensiveCopy(items); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. A defensive copy is made.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(T[] items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { // Avoid allocating an array. return Create<T>(); } var array = new T[length]; for (int i = 0; i < length; i++) { array[i] = items[start + i]; } return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. /// The selected array segment may be copied into a new array.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length) { Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } var array = new T[length]; Array.Copy(items.array, start, array, 0, length); return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on a slice of an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, "start"); Requires.Range(length >= 0 && start + length <= itemsLength, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i + start]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on a slice of an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, "start"); Requires.Range(length >= 0 && start + length <= itemsLength, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i + start], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct based on the contents /// of an existing instance, allowing a covariant static cast to efficiently reuse the existing array. /// </summary> /// <param name="items">The array to initialize the array with. No copy is made.</param> /// <remarks> /// Covariant upcasts from this method may be reversed by calling the /// <see cref="ImmutableArray&lt;T&gt;.As&lt;TOther&gt;"/> instance method. /// </remarks> [Pure] public static ImmutableArray<T> Create<T, TDerived>(ImmutableArray<TDerived> items) where TDerived : class, T { return new ImmutableArray<T>(items.array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <param name="initialCapacity">The size of the initial array backing the builder.</param> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity) { return new ImmutableArray<T>.Builder(initialCapacity); } /// <summary> /// Enumerates a sequence exactly once and produces an immutable array of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="items">The sequence to enumerate.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items) { if (items is ImmutableArray<TSource>) { return (ImmutableArray<TSource>)items; } return CreateRange(items); } /// <summary> /// Searches an entire one-dimensional sorted System.Array for a specific element, /// using the System.IComparable&lt;T&gt; generic interface implemented by each element /// of the System.Array and by the specified object. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value) { return Array.BinarySearch<T>(array.array, value); } /// <summary> /// Searches an entire one-dimensional sorted System.Array for a value using /// the specified System.Collections.Generic.IComparer&lt;T&gt; generic interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The System.Collections.Generic.IComparer&lt;T&gt; implementation to use when comparing /// elements; or null to use the System.IComparable&lt;T&gt; implementation of each /// element. /// </param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, value, comparer); } /// <summary> /// Searches a range of elements in a one-dimensional sorted System.Array for /// a value, using the System.IComparable&lt;T&gt; generic interface implemented by /// each element of the System.Array and by the specified value. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value) { return Array.BinarySearch<T>(array.array, index, length, value); } /// <summary> /// Searches a range of elements in a one-dimensional sorted System.Array for /// a value, using the specified System.Collections.Generic.IComparer&lt;T&gt; generic /// interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The System.Collections.Generic.IComparer&lt;T&gt; implementation to use when comparing /// elements; or null to use the System.IComparable&lt;T&gt; implementation of each /// element. /// </param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// comparer is null, value does not implement the System.IComparable&lt;T&gt; generic /// interface, and the search encounters an element that does not implement the /// System.IComparable&lt;T&gt; generic interface. /// </exception> /// <exception cref="ArgumentException"> /// index and length do not specify a valid range in array.-or-comparer is null, /// and value is of a type that is not compatible with the elements of array. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// index is less than the lower bound of array. -or- length is less than zero. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, index, length, value, comparer); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to use or copy from. May be null for "default" arrays.</param> internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items) { // Some folks lazily initialize fields containing these structs, so retaining a null vs. empty array status is useful. if (items == null) { return default(ImmutableArray<T>); } if (items.Length == 0) { return ImmutableArray<T>.Empty; // use just a shared empty array, allowing the input array to be potentially GC'd } // defensive copy var tmp = new T[items.Length]; Array.Copy(items, tmp, items.Length); return new ImmutableArray<T>(tmp); } } }
/** * Copyright 2013 * * 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 NinthChevron.Data.Metadata; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; namespace NinthChevron.Data.SqlServer.Metadata { public class SqlServerMetadata : IDatabaseMetadata { public SqlServerMetadata(string connectionString, params string[] schemas) { if (connectionString.ToLower().IndexOf("initial catalog") < 0) throw new ArgumentException("'initial catalog' option missing in connection string"); string schemaClause = string.Empty; if (schemas.Length > 0) schemaClause = " AND columns.table_schema IN (" + string.Join(",", schemas.Select(s => "'" + s + "'")) + ") "; Tables = new List<ITableMetadata>(); Dictionary<string, ITableMetadata> tables = new Dictionary<string, ITableMetadata>(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand cmd = new SqlCommand(@"SELECT DISTINCT columns.table_catalog, CASE WHEN columns.table_schema = 'dbo' THEN '' ELSE columns.table_schema END AS TableSchema, columns.table_name, columns.column_name, columns.data_type, CASE WHEN columns.is_nullable = 'YES' THEN 1 ELSE 0 END AS IsNullable, CASE WHEN EXISTS(SELECT * FROM information_schema.constraint_column_usage usage LEFT JOIN information_schema.table_constraints constraints ON usage.table_catalog = constraints.table_catalog AND usage.table_schema = constraints.table_schema AND usage.table_name = constraints.table_name AND usage.constraint_name = constraints.constraint_name AND constraints.Constraint_type = 'PRIMARY KEY' WHERE columns.table_catalog = usage.table_catalog AND columns.table_schema = usage.table_schema AND columns.table_name = usage.table_name AND columns.column_name = usage.column_name ) THEN 1 ELSE 0 END AS IsPK, COLUMNPROPERTY(object_id(columns.table_schema + '.' + columns.table_name), columns.column_name, 'IsIdentity') AS IsIdentity, columns.ordinal_position FROM information_schema.columns columns INNER JOIN information_schema.tables tables ON columns.table_catalog = tables.table_catalog AND columns.table_schema = tables.table_schema AND columns.table_name = tables.table_name WHERE columns.table_name NOT IN ('dtproperties', 'sysconstraints', 'syssegments', 'sysdiagrams') AND tables.table_type = 'BASE TABLE'" + schemaClause + @"ORDER BY columns.table_catalog, TableSchema, columns.table_name, columns.ordinal_position", connection); using (SqlDataReader reader = cmd.ExecuteReader()) { ITableMetadata currentTable = null; while (reader.Read()) { this.Name = reader.GetString(0); string schema = reader.GetString(1); string tableName = reader.GetString(2); if (currentTable == null || currentTable.Name != tableName || currentTable.Schema != schema) { currentTable = new TableMetadata(this.Name, schema, tableName); Tables.Add(currentTable); tables.Add(schema + "/" + tableName, currentTable); } currentTable.Columns.Add(reader.GetString(3), new ColumnMetadata( this, currentTable, reader.GetString(3), reader.GetString(4), reader.GetInt32(6) == 1 ? true : false, reader.GetInt32(7) == 1 ? true : false, reader.GetInt32(5) == 1 ? true : false )); } } // Found Relation Column cmd = new SqlCommand(@"SELECT usage.table_schema, usage.table_name, usage.column_name, CASE WHEN columns.is_nullable = 'YES' THEN 1 ELSE 0 END AS IsNullable, fkusage.table_schema AS ReferencedTable, fkusage.table_name AS ReferencedTable, fkusage.column_name AS ReferencedColumn FROM information_schema.constraint_column_usage usage INNER JOIN information_schema.table_constraints constraints ON usage.table_catalog = constraints.table_catalog AND usage.table_schema = constraints.table_schema AND usage.table_name = constraints.table_name AND usage.constraint_name = constraints.constraint_name AND constraints.Constraint_type = 'FOREIGN KEY' INNER JOIN information_schema.referential_constraints rconstraint ON rconstraint.constraint_catalog = usage.constraint_catalog AND rconstraint.constraint_schema = usage.constraint_schema AND rconstraint.constraint_name = usage.constraint_name INNER JOIN information_schema.constraint_column_usage fkusage ON rconstraint.unique_constraint_catalog = fkusage.constraint_catalog AND rconstraint.unique_constraint_schema = fkusage.constraint_schema AND rconstraint.unique_constraint_name = fkusage.constraint_name INNER JOIN information_schema.columns columns ON columns.table_catalog = fkusage.table_catalog AND columns.table_schema = fkusage.table_schema AND columns.table_name = fkusage.table_name AND columns.column_name = fkusage.column_name INNER JOIN information_schema.tables tables ON columns.table_catalog = tables.table_catalog AND columns.table_schema = tables.table_schema AND columns.table_name = tables.table_name WHERE columns.table_name NOT IN ('dtproperties', 'sysconstraints', 'syssegments', 'sysdiagrams') AND tables.table_type = 'BASE TABLE'" + schemaClause + @"ORDER BY columns.table_schema, columns.table_name, columns.ordinal_position", connection); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string sourceSchema = reader.GetString(0); string sourceTableName = reader.GetString(1); string sourceColumn = reader.GetString(2); bool isNullable = reader.GetInt32(3) == 1 ? true : false; string foreignSchema = reader.GetString(4); string foreignTableName = reader.GetString(5); string foreignColumn = reader.GetString(6); ITableMetadata table = tables[sourceSchema + "/" + sourceTableName]; ITableMetadata foreignTable = tables[foreignSchema + "/" + foreignTableName]; table.Relations.Add(new RelationColumnMetadata(false, table, sourceColumn, isNullable, foreignTable, foreignColumn)); foreignTable.Relations.Add(new RelationColumnMetadata(true, foreignTable, foreignColumn, isNullable, table, sourceColumn)); } } // Get Procedures cmd = new SqlCommand(@"SELECT routines.routine_schema, routines.routine_name, parameters.parameter_name, parameters.data_type, parameters.parameter_mode, ISNULL(parameters.character_maximum_length, parameters.numeric_precision) FROM information_schema.routines AS routines LEFT JOIN information_schema.parameters AS parameters ON parameters.specific_name = routines.routine_name INNER JOIN sysobjects ON sysobjects.type = 'P' AND sysobjects.category <> 2 AND sysobjects.name = routines.routine_name WHERE routine_type = 'PROCEDURE' ORDER BY routines.routine_name, parameters.ordinal_position", connection); using (SqlDataReader reader = cmd.ExecuteReader()) { List<SqlServerProcedureMetadata> procedures = new List<SqlServerProcedureMetadata>(); SqlServerProcedureMetadata current = null; while (reader.Read()) { string schema = reader.GetString(0); string name = reader.GetString(1); if (current == null || current.Name != name || current.Schema != schema) { current = new SqlServerProcedureMetadata(this, schema, name); procedures.Add(current); } if (!reader.IsDBNull(2)) { int? precision = null; if (!reader.IsDBNull(5)) precision = reader.GetInt32(5); current.Parameters.Add(new ProcedureParameterMetadata(reader.GetString(2), reader.GetString(3), reader.GetString(4), precision)); } } this.Procedures = procedures; } } } public string Name { get; private set; } public List<ITableMetadata> Tables { get; private set; } public IEnumerable<IProcedureMetadata> Procedures { get; private set; } public Type GetType(string dbType, bool isNullable) { switch (dbType) { case "varchar": case "nvarchar": case "char": case "nchar": case "text": case "ntext": return typeof(string); case "datetime": case "smalldatetime": return isNullable ? typeof(DateTime?) : typeof(DateTime); case "int": return isNullable ? typeof(int?) : typeof(int); case "smallint": return isNullable ? typeof(short?) : typeof(short); case "decimal": return isNullable ? typeof(decimal?) : typeof(decimal); case "float": return isNullable ? typeof(double?) : typeof(double); case "real": return isNullable ? typeof(float?) : typeof(float); case "bigint": case "timestamp": return isNullable ? typeof(long?) : typeof(long); case "bit": return isNullable ? typeof(bool?) : typeof(bool); case "tinyint": return isNullable ? typeof(byte?) : typeof(byte); case "uniqueidentifier": return typeof(Guid); case "varbinary": return typeof(byte[]); case "image": default: return typeof(object); } } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using umbraco.cms.presentation.create.controls; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class MemberTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Member_Cannot_Edit_Property() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); //re-get memberType = ServiceContext.MemberTypeService.Get(memberType.Id); foreach (var p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } } [Test] public void Member_Can_Edit_Property() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanEditProperty(prop, true); ServiceContext.MemberTypeService.Save(memberType); //re-get memberType = ServiceContext.MemberTypeService.Get(memberType.Id); foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); } Assert.IsTrue(memberType.MemberCanEditProperty(prop)); } [Test] public void Member_Cannot_View_Property() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); //re-get memberType = ServiceContext.MemberTypeService.Get(memberType.Id); foreach (var p in memberType.PropertyTypes) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } } [Test] public void Member_Can_View_Property() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var prop = memberType.PropertyTypes.First().Alias; memberType.SetMemberCanViewProperty(prop, true); ServiceContext.MemberTypeService.Save(memberType); //re-get memberType = ServiceContext.MemberTypeService.Get(memberType.Id); foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) { Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); } Assert.IsTrue(memberType.MemberCanViewProperty(prop)); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "[email protected]", "pass", "test"); ServiceContext.MemberService.Save(member); var initProps = member.Properties.Count; var initPropTypes = member.PropertyTypes.Count(); //remove a property (NOT ONE OF THE DEFAULTS) var standardProps = Constants.Conventions.Member.GetStandardPropertyTypeStubs(); memberType.RemovePropertyType(memberType.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias); ServiceContext.MemberTypeService.Save(memberType); //re-load it from the db member = ServiceContext.MemberService.GetById(member.Id); Assert.AreEqual(initPropTypes - 1, member.PropertyTypes.Count()); Assert.AreEqual(initProps - 1, member.Properties.Count); } [Test] public void Rebuild_Member_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateSimpleMemberType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateSimpleMemberType("test2", "Test2"); ServiceContext.MemberTypeService.Save(contentType1); ServiceContext.MemberTypeService.Save(contentType2); var contentItems1 = MockedMember.CreateSimpleMember(contentType1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.MemberService.Save(x)); var contentItems2 = MockedMember.CreateSimpleMember(contentType2, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.MemberService.Save(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.MemberTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Member_Xml_On_Property_Removal() { var standardProps = Constants.Conventions.Member.GetStandardPropertyTypeStubs(); var contentType1 = MockedContentTypes.CreateSimpleMemberType("test1", "Test1"); ServiceContext.MemberTypeService.Save(contentType1); var contentItems1 = MockedMember.CreateSimpleMember(contentType1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.MemberService.Save(x)); var alias = contentType1.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property (NOT ONE OF THE DEFAULTS) contentType1.RemovePropertyType(alias); ServiceContext.MemberTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } //[Test] //public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It() //{ // // Arrange // var cs = ServiceContext.MemberService; // var cts = ServiceContext.MemberTypeService; // var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); // var ctBase = new MemberType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; // ctBase.AddPropertyType(new PropertyType(dtdYesNo) // { // Name = "Hide From Navigation", // Alias = Constants.Conventions.Content.NaviHide // } // /*,"Navigation"*/); // cts.Save(ctBase); // var ctHomePage = new MemberType(ctBase) // { // Name = "Home Page", // Alias = "HomePage", // Icon = "settingDomain.gif", // Thumbnail = "folder.png", // AllowedAsRoot = true // }; // ctHomePage.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Some property", Alias = "someProperty" } // /*,"Navigation"*/); // cts.Save(ctHomePage); // // Act // var homeDoc = cs.CreateMember("Test", "[email protected]", "test", "HomePage"); // // Assert // Assert.That(ctBase.HasIdentity, Is.True); // Assert.That(ctHomePage.HasIdentity, Is.True); // Assert.That(homeDoc.HasIdentity, Is.True); // Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); //} //[Test] //public void Can_Create_And_Save_MemberType_Composition() //{ // /* // * Global // * - Components // * - Category // */ // var service = ServiceContext.ContentTypeService; // var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); // service.Save(global); // var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global); // service.Save(components); // var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components); // service.Save(component); // var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global); // service.Save(category); // var success = category.AddContentType(component); // Assert.That(success, Is.False); //} //[Test] //public void Can_Remove_ContentType_Composition_From_ContentType() //{ // //Test for U4-2234 // var cts = ServiceContext.ContentTypeService; // //Arrange // var component = CreateComponent(); // cts.Save(component); // var banner = CreateBannerComponent(component); // cts.Save(banner); // var site = CreateSite(); // cts.Save(site); // var homepage = CreateHomepage(site); // cts.Save(homepage); // //Add banner to homepage // var added = homepage.AddContentType(banner); // cts.Save(homepage); // //Assert composition // var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(added, Is.True); // Assert.That(bannerExists, Is.True); // Assert.That(bannerPropertyExists, Is.True); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); // //Remove banner from homepage // var removed = homepage.RemoveContentType(banner.Alias); // cts.Save(homepage); // //Assert composition // var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); // var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); // Assert.That(removed, Is.True); // Assert.That(bannerStillExists, Is.False); // Assert.That(bannerPropertyStillExists, Is.False); // Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); //} //[Test] //public void Can_Copy_ContentType_By_Performing_Clone() //{ // // Arrange // var service = ServiceContext.ContentTypeService; // var metaContentType = MockedContentTypes.CreateMetaContentType(); // service.Save(metaContentType); // var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); // service.Save(simpleContentType); // var categoryId = simpleContentType.Id; // // Act // var sut = simpleContentType.Clone("newcategory"); // service.Save(sut); // // Assert // Assert.That(sut.HasIdentity, Is.True); // var contentType = service.GetContentType(sut.Id); // var category = service.GetContentType(categoryId); // Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); // Assert.AreEqual(contentType.ParentId, category.ParentId); // Assert.AreEqual(contentType.Level, category.Level); // Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); // Assert.AreNotEqual(contentType.Id, category.Id); // Assert.AreNotEqual(contentType.Key, category.Key); // Assert.AreNotEqual(contentType.Path, category.Path); // Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); // Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); // Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); //} //private ContentType CreateComponent() //{ // var component = new ContentType(-1) // { // Alias = "component", // Name = "Component", // Description = "ContentType used for Component grouping", // Icon = ".sprTreeDoc3", // Thumbnail = "doc.png", // SortOrder = 1, // CreatorId = 0, // Trashed = false // }; // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); // return component; //} //private ContentType CreateBannerComponent(ContentType parent) //{ // var banner = new ContentType(parent) // { // Alias = "banner", // Name = "Banner Component", // Description = "ContentType used for Banner Component", // Icon = ".sprTreeDoc3", // Thumbnail = "doc.png", // SortOrder = 1, // CreatorId = 0, // Trashed = false // }; // var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) // { // Alias = "bannerName", // Name = "Banner Name", // Description = "", // HelpText = "", // Mandatory = false, // SortOrder = 2, // DataTypeDefinitionId = -88 // }; // banner.AddPropertyType(propertyType, "Component"); // return banner; //} //private ContentType CreateSite() //{ // var site = new ContentType(-1) // { // Alias = "site", // Name = "Site", // Description = "ContentType used for Site inheritence", // Icon = ".sprTreeDoc3", // Thumbnail = "doc.png", // SortOrder = 2, // CreatorId = 0, // Trashed = false // }; // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); // return site; //} //private ContentType CreateHomepage(ContentType parent) //{ // var contentType = new ContentType(parent) // { // Alias = "homepage", // Name = "Homepage", // Description = "ContentType used for the Homepage", // Icon = ".sprTreeDoc3", // Thumbnail = "doc.png", // SortOrder = 1, // CreatorId = 0, // Trashed = false // }; // var contentCollection = new PropertyTypeCollection(); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); // contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); // contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); // return contentType; //} //private IEnumerable<IContentType> CreateContentTypeHierarchy() //{ // //create the master type // var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); // masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); // ServiceContext.ContentTypeService.Save(masterContentType); // //add the one we just created // var list = new List<IContentType> { masterContentType }; // for (var i = 0; i < 10; i++) // { // var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, // //make the last entry in the list, this one's parent // list.Last()); // list.Add(contentType); // } // return list; //} } }
#region Copyright (C) 2013 // Project hw.nuget // Copyright (C) 2013 - 2013 Harald Hoyer // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using hw.Debug; using JetBrains.Annotations; namespace hw.Helper { public static class ListExtender { public static bool AddDistinct<T>(this IList<T> a, IEnumerable<T> b, Func<T, T, bool> isEqual) { return InternalAddDistinct(a, b, isEqual); } public static bool AddDistinct<T>(this IList<T> a, IEnumerable<T> b, Func<T, T, T> combine) where T : class { return InternalAddDistinct(a, b, combine); } static bool InternalAddDistinct<T>(ICollection<T> a, IEnumerable<T> b, Func<T, T, bool> isEqual) { var result = false; foreach(var bi in b) if(AddDistinct(a, bi, isEqual)) result = true; return result; } static bool InternalAddDistinct<T>(IList<T> a, IEnumerable<T> b, Func<T, T, T> combine) where T : class { var result = false; foreach(var bi in b) if(AddDistinct(a, bi, combine)) result = true; return result; } static bool AddDistinct<T>(ICollection<T> a, T bi, Func<T, T, bool> isEqual) { if(a.Any(ai => isEqual(ai, bi))) return false; a.Add(bi); return true; } static bool AddDistinct<T>(IList<T> a, T bi, Func<T, T, T> combine) where T : class { for(var i = 0; i < a.Count; i++) { var ab = combine(a[i], bi); if(ab != null) { a[i] = ab; return false; } } a.Add(bi); return true; } public static IEnumerable<IEnumerable<T>> Separate<T>(this IEnumerable<T> x, Func<T, bool> isHead) { var subResult = new List<T>(); foreach(var xx in x) { if(isHead(xx)) if(subResult.Count > 0) { yield return subResult.ToArray(); subResult = new List<T>(); } subResult.Add(xx); } if(subResult.Count > 0) yield return subResult.ToArray(); } [CanBeNull] public static T Aggregate<T>(this IEnumerable<T> x) where T : class, IAggregateable<T> { var xx = x.ToArray(); if(!xx.Any()) return null; var result = xx[0]; for(var i = 1; i < xx.Length; i++) result = result.Aggregate(xx[i]); return result; } public static string Dump<T>(this IEnumerable<T> x) { var xArray = x.ToArray(); return xArray.Aggregate(xArray.Length.ToString(), (a, xx) => a + " " + xx.ToString()); } public static string DumpLines<T>(this IEnumerable<T> x) where T : Dumpable { var i = 0; return x.Aggregate("", (a, xx) => a + "[" + i++ + "] " + xx.Dump() + "\n"); } [Obsolete("use Stringify")] public static string Format<T>(this IEnumerable<T> x, string separator) { return Stringify(x, separator); } public static string Stringify<T>(this IEnumerable<T> x, string separator, bool showNumbers = false) { var result = new StringBuilder(); var i = 0; var isNext = false; foreach(var element in x) { if(isNext) result.Append(separator); if(showNumbers) result.Append("[" + i + "] "); isNext = true; result.Append(element); i++; } return result.ToString(); } public static TimeSpan Sum<T>(this IEnumerable<T> x, Func<T, TimeSpan> selector) { var result = new TimeSpan(); return x.Aggregate(result, (current, element) => current + selector(element)); } /// <summary> /// Returns index list of all elements, that have no other element, with "isInRelation(element, other)" is true /// For example if relation is "element ;&less; other" will return the maximal element /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="isInRelation"></param> /// <returns></returns> public static IEnumerable<int> FrameIndexList<T>(this IEnumerable<T> list, Func<T, T, bool> isInRelation) { var listArray = list.ToArray(); return listArray.Select((item, index) => new Tuple<T, int>(item, index)).Where(element => !listArray.Any(other => isInRelation(element.Item1, other))).Select(element => element.Item2); } /// <summary> /// Returns list of all elements, that have no other element, with "isInRelation(element, other)" is true /// For example if relation is "element ;&less; other" will return the maximal element /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="isInRelation"></param> /// <returns></returns> public static IEnumerable<T> FrameElementList<T>(this IEnumerable<T> list, Func<T, T, bool> isInRelation) { var listArray = list.ToArray(); return listArray.FrameIndexList(isInRelation).Select(index => listArray[index]); } public static IEnumerable<int> MaxIndexList<T>(this IEnumerable<T> list) where T : IComparable<T> { return list.FrameIndexList((a, b) => a.CompareTo(b) < 0); } public static IEnumerable<int> MinIndexList<T>(this IEnumerable<T> list) where T : IComparable<T> { return list.FrameIndexList((a, b) => a.CompareTo(b) > 0); } /// <summary> /// Checks if object starts with given object. /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="x"> The x. </param> /// <param name="y"> The y. </param> /// <returns> </returns> public static bool StartsWith<T>(this IList<T> x, IList<T> y) { if(x.Count < y.Count) return false; return !y.Where((t, i) => !Equals(x[i], t)).Any(); } /// <summary> /// Checks if object starts with given object and is longer. /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="x"> The x. </param> /// <param name="y"> The y. </param> /// <returns> </returns> public static bool StartsWithAndNotEqual<T>(this IList<T> x, IList<T> y) { if(x.Count == y.Count) return false; return x.StartsWith(y); } public static TResult CheckedApply<T, TResult>(this T target, Func<T, TResult> function) where T : class where TResult : class { return target == default(T) ? default(TResult) : function(target); } public static TResult AssertValue<TResult>(this TResult? target) where TResult : struct { Tracer.Assert(target != null); return target.Value; } public static TResult AssertNotNull<TResult>(this TResult target) where TResult : class { Tracer.Assert(target != null); return target; } [NotNull] public static IEnumerable<int> Select(this int count) { for(var i = 0; i < count; i++) yield return i; } [NotNull] public static IEnumerable<long> Select(this long count) { for(long i = 0; i < count; i++) yield return i; } [NotNull] public static IEnumerable<int> Where(Func<int, bool> getValue) { for(var i = 0; getValue(i); i++) yield return i; } [NotNull] public static IEnumerable<T> Select<T>(this int count, Func<int, T> getValue) { for(var i = 0; i < count; i++) yield return getValue(i); } [NotNull] public static IEnumerable<T> Select<T>(this long count, Func<long, T> getValue) { for(long i = 0; i < count; i++) yield return getValue(i); } public static IEnumerable<Tuple<TKey, TLeft, TRight>> Merge<TKey, TLeft, TRight>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> getLeftKey, Func<TRight, TKey> getRightKey) where TLeft : class where TRight : class { var leftCommon = left.Select(l => new Tuple<TKey, TLeft, TRight>(getLeftKey(l), l, null)); var rightCommon = right.Select(r => new Tuple<TKey, TLeft, TRight>(getRightKey(r), null, r)); return leftCommon.Union(rightCommon).GroupBy(t => t.Item1).Select(Merge); } public static Tuple<TKey, TLeft, TRight> Merge<TKey, TLeft, TRight>(IGrouping<TKey, Tuple<TKey, TLeft, TRight>> grouping) where TLeft : class where TRight : class { var list = grouping.ToArray(); switch(list.Length) { case 1: return list[0]; case 2: if(list[0].Item2 == null && list[1].Item3 == null) return new Tuple<TKey, TLeft, TRight>(grouping.Key, list[1].Item2, list[0].Item3); if(list[1].Item2 == null && list[0].Item3 == null) return new Tuple<TKey, TLeft, TRight>(grouping.Key, list[0].Item2, list[1].Item3); break; } throw new DuplicateKeyException(); } public static FunctionCache<TKey, IEnumerable<T>> ToDictionaryEx<TKey, T>(this IEnumerable<T> list, Func<T, TKey> selector) { return new FunctionCache<TKey, IEnumerable<T>>(key => list.Where(item => Equals(selector(item), key))); } public static void AddRange<TKey, TValue>(this IDictionary<TKey, TValue> target, IEnumerable<KeyValuePair<TKey, TValue>> newEntries) { foreach(var item in newEntries.Where(x => !target.ContainsKey(x.Key))) target.Add(item); } } public interface IAggregateable<T> { T Aggregate(T other); } sealed class DuplicateKeyException : Exception {} }
// // System.Web.UI.WebControls.HyperLink.cs // // Authors: // Gaurav Vaish ([email protected]) // Gonzalo Paniagua Javier ([email protected]) // Andreas Nahr ([email protected]) // // (c) 2002 Ximian, Inc. (http://www.ximian.com) // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.Web; using System.Web.UI; using System.ComponentModel; using System.ComponentModel.Design; namespace System.Web.UI.WebControls { [DefaultProperty("Text")] [ControlBuilder(typeof(HyperLinkControlBuilder))] [Designer("System.Web.UI.Design.WebControls.HyperLinkDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))] [DataBindingHandler("System.Web.UI.Design.HyperLinkDataBindingHandler, " + Consts.AssemblySystem_Design)] [ParseChildren(false)] [ToolboxData("<{0}:HyperLink runat=\"server\">HyperLink</{0}:HyperLink>")] public class HyperLink: WebControl { bool textSet; public HyperLink(): base(HtmlTextWriterTag.A) { } #if NET_2_0 [UrlPropertyAttribute] #endif [DefaultValue (""), Bindable (true), WebCategory ("Appearance")] [Editor ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))] [WebSysDescription ("The URL to the image file.")] public virtual string ImageUrl { get { object o = ViewState["ImageUrl"]; if(o!=null) return (string)o; return String.Empty; } set { ViewState["ImageUrl"] = value; } } #if NET_2_0 [UrlPropertyAttribute] #endif [DefaultValue (""), Bindable (true), WebCategory ("Navigation")] [Editor ("System.Web.UI.Design.UrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))] [WebSysDescription ("The URL to navigate to.")] public string NavigateUrl { get { object o = ViewState["NavigateUrl"]; if(o!=null) return (string)o; return String.Empty; } set { ViewState["NavigateUrl"] = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (""), WebCategory ("Navigation")] [TypeConverter (typeof (TargetConverter))] [WebSysDescription ("The target frame in which the navigation target should be opened.")] public string Target { get { object o = ViewState["Target"]; if(o!=null) return (string)o; return String.Empty; } set { ViewState["Target"] = value; } } #if NET_2_0 [Localizable (true)] #endif [DefaultValue (""), Bindable (true), WebCategory ("Appearance")] [PersistenceMode (PersistenceMode.InnerDefaultProperty)] [WebSysDescription ("The text that should be shown on this HyperLink.")] public virtual string Text { get { object o = ViewState ["Text"]; if (o != null) return (string) o; return String.Empty; } set { if (HasControls()) Controls.Clear(); ViewState["Text"] = value; textSet = true; } } #if NET_2_0 [BindableAttribute (true)] [LocalizableAttribute (true)] [DefaultValueAttribute ("")] public string SoftkeyLabel { get { string text = (string)ViewState["SoftkeyLabel"]; if (text!=null) return text; return String.Empty; } set { ViewState["SoftkeyLabel"] = value; } } #endif string InternalText { get { return Text; } set { ViewState["Text"] = value; } } protected override void AddAttributesToRender(HtmlTextWriter writer) { base.AddAttributesToRender(writer); if(NavigateUrl.Length > 0) { string url = ResolveUrl (NavigateUrl); writer.AddAttribute(HtmlTextWriterAttribute.Href, url); } if(Target.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Target, Target); } } protected override void AddParsedSubObject(object obj) { if(HasControls()) { base.AddParsedSubObject(obj); return; } if(obj is LiteralControl) { // This is a hack to workaround the behaviour of the code generator, which // may split a text in several LiteralControls if there's a special character // such as '<' in it. if (textSet) { Text = ((LiteralControl)obj).Text; textSet = false; } else { InternalText += ((LiteralControl)obj).Text; } // return; } if(Text.Length > 0) { base.AddParsedSubObject(new LiteralControl (Text)); Text = String.Empty; } base.AddParsedSubObject (obj); } protected override void LoadViewState(object savedState) { if(savedState != null) { base.LoadViewState(savedState); object o = ViewState["Text"]; if(o!=null) Text = (string)o; } } protected override void RenderContents(HtmlTextWriter writer) { if(ImageUrl.Length > 0) { Image img = new Image(); img.ImageUrl = ResolveUrl(ImageUrl); if(ToolTip.Length > 0) img.ToolTip = ToolTip; if(Text.Length > 0) img.AlternateText = Text; img.RenderControl(writer); return; } if(HasControls()) { base.RenderContents(writer); return; } writer.Write(Text); } } }
/** * Copyright (c) 2013-2014 Microsoft Mobile. All rights reserved. * * Nokia, Nokia Connecting People, Nokia Developer, and HERE are trademarks * and/or registered trademarks of Nokia Corporation. Other product and company * names mentioned herein may be trademarks or trade names of their respective * owners. * * See the license text file delivered with this project for more information. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace RateMyXamlXnaApp { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Provides access to a ContentManager for the application. /// </summary> public ContentManager Content { get; private set; } /// <summary> /// Provides access to a GameTimer that is set up to pump the FrameworkDispatcher. /// </summary> public GameTimer FrameworkDispatcherTimer { get; private set; } /// <summary> /// Provides access to the AppServiceProvider for the application. /// </summary> public AppServiceProvider Services { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard Silverlight initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // XNA initialization InitializeXnaApplication(); // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Disable the application idle detection by setting the UserIdleDetectionMode property of the // application's PhoneApplicationService object to Disabled. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // A navigation has failed; break into the debugger System.Diagnostics.Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } #endregion #region XNA application initialization // Performs initialization of the XNA types required for the application. private void InitializeXnaApplication() { // Create the service provider Services = new AppServiceProvider(); // Add the SharedGraphicsDeviceManager to the Services as the IGraphicsDeviceService for the app foreach (object obj in ApplicationLifetimeObjects) { if (obj is IGraphicsDeviceService) Services.AddService(typeof(IGraphicsDeviceService), obj); } // Create the ContentManager so the application can load precompiled assets Content = new ContentManager(Services, "Content"); // Create a GameTimer to pump the XNA FrameworkDispatcher FrameworkDispatcherTimer = new GameTimer(); FrameworkDispatcherTimer.FrameAction += FrameworkDispatcherFrameAction; FrameworkDispatcherTimer.Start(); } // An event handler that pumps the FrameworkDispatcher each frame. // FrameworkDispatcher is required for a lot of the XNA events and // for certain functionality such as SoundEffect playback. private void FrameworkDispatcherFrameAction(object sender, EventArgs e) { FrameworkDispatcher.Update(); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>AdGroupAudienceView</c> resource.</summary> public sealed partial class AdGroupAudienceViewName : gax::IResourceName, sys::IEquatable<AdGroupAudienceViewName> { /// <summary>The possible contents of <see cref="AdGroupAudienceViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/adGroupAudienceViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="AdGroupAudienceViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AdGroupAudienceViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupAudienceViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupAudienceViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupAudienceViewName"/> with the pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="AdGroupAudienceViewName"/> constructed from the provided ids. /// </returns> public static AdGroupAudienceViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new AdGroupAudienceViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAudienceViewName"/> with pattern /// <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupAudienceViewName"/> if successful.</returns> public static AdGroupAudienceViewName Parse(string adGroupAudienceViewName) => Parse(adGroupAudienceViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AdGroupAudienceViewName"/> if successful.</returns> public static AdGroupAudienceViewName Parse(string adGroupAudienceViewName, bool allowUnparsed) => TryParse(adGroupAudienceViewName, allowUnparsed, out AdGroupAudienceViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAudienceViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAudienceViewName, out AdGroupAudienceViewName result) => TryParse(adGroupAudienceViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAudienceViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAudienceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAudienceViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAudienceViewName, bool allowUnparsed, out AdGroupAudienceViewName result) { gax::GaxPreconditions.CheckNotNull(adGroupAudienceViewName, nameof(adGroupAudienceViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(adGroupAudienceViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupAudienceViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupAudienceViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupAudienceViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/adGroupAudienceViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupAudienceViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AdGroupAudienceViewName); /// <inheritdoc/> public bool Equals(AdGroupAudienceViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupAudienceViewName a, AdGroupAudienceViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupAudienceViewName a, AdGroupAudienceViewName b) => !(a == b); } public partial class AdGroupAudienceView { /// <summary> /// <see cref="AdGroupAudienceViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupAudienceViewName ResourceNameAsAdGroupAudienceViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAudienceViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ namespace Multiverse.Tools.TerrainGenerator { partial class TerrainGenerator { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TerrainGenerator)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loadSeedMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.designateRepositoryMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.createSeedHeightmapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.wireFrameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.displayOceanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.spinCameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resetCameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.launchOnlineHelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.submitABugReToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutTerrainGeneratorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.terrainProperties = new System.Windows.Forms.TabPage(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.generalTerrainButton = new System.Windows.Forms.Button(); this.generalTerrainGroupBox = new System.Windows.Forms.GroupBox(); this.generalTerrainHelpLink = new System.Windows.Forms.LinkLabel(); this.featureSpacingTrackBar = new System.Windows.Forms.TrackBar(); this.featureSpacingValueLabel = new System.Windows.Forms.Label(); this.heightOffsetTrackBar = new System.Windows.Forms.TrackBar(); this.heightOffsetValueLabel = new System.Windows.Forms.Label(); this.heightFloorValueLabel = new System.Windows.Forms.Label(); this.heightFloorTrackBar = new System.Windows.Forms.TrackBar(); this.heightScaleValueLabel = new System.Windows.Forms.Label(); this.heightScaleTrackBar = new System.Windows.Forms.TrackBar(); this.featureSpacingLabel = new System.Windows.Forms.Label(); this.heightFloorLabel = new System.Windows.Forms.Label(); this.heightOffsetLabel = new System.Windows.Forms.Label(); this.heightScaleLabel = new System.Windows.Forms.Label(); this.fractalParamsButton = new System.Windows.Forms.Button(); this.fractalParamsGroupBox = new System.Windows.Forms.GroupBox(); this.fractalParamsHelpLink = new System.Windows.Forms.LinkLabel(); this.seedZUpDown = new System.Windows.Forms.NumericUpDown(); this.seedYUpDown = new System.Windows.Forms.NumericUpDown(); this.seedXUpDown = new System.Windows.Forms.NumericUpDown(); this.fractalOffsetTrackBar = new System.Windows.Forms.TrackBar(); this.fractalOffsetValueLabel = new System.Windows.Forms.Label(); this.iterationsUpDown = new System.Windows.Forms.NumericUpDown(); this.lacunarityTrackBar = new System.Windows.Forms.TrackBar(); this.lacunarityValueLabel = new System.Windows.Forms.Label(); this.hTrackBar = new System.Windows.Forms.TrackBar(); this.hValueLabel = new System.Windows.Forms.Label(); this.fractalOffsetLabel = new System.Windows.Forms.Label(); this.iterationsLabel = new System.Windows.Forms.Label(); this.seedXLabel = new System.Windows.Forms.Label(); this.lacunarityLabel = new System.Windows.Forms.Label(); this.seedYLabel = new System.Windows.Forms.Label(); this.hLabel = new System.Windows.Forms.Label(); this.seedZLabel = new System.Windows.Forms.Label(); this.heightMapParamsButton = new System.Windows.Forms.Button(); this.heightMapGroupBox = new System.Windows.Forms.GroupBox(); this.heightMapParamsHelpLink = new System.Windows.Forms.LinkLabel(); this.useSeedMapCheckBox = new System.Windows.Forms.CheckBox(); this.mapOriginZTextBox = new System.Windows.Forms.TextBox(); this.mapOriginZLabel = new System.Windows.Forms.Label(); this.mapOriginXLabel = new System.Windows.Forms.Label(); this.mapOriginXTextBox = new System.Windows.Forms.TextBox(); this.mpsTextBox = new System.Windows.Forms.TextBox(); this.mpsLabel = new System.Windows.Forms.Label(); this.heightOutsideTextBox = new System.Windows.Forms.TextBox(); this.heightOutsideLabel = new System.Windows.Forms.Label(); this.heightMapEditor = new System.Windows.Forms.TabPage(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.hmeOptionsButton = new System.Windows.Forms.Button(); this.hmeOptionsGroupBox = new System.Windows.Forms.GroupBox(); this.heightMapEditorHelpLink = new System.Windows.Forms.LinkLabel(); this.brushShapeComboBox = new System.Windows.Forms.ComboBox(); this.brushShapeLabel = new System.Windows.Forms.Label(); this.brushTaperUpDown = new System.Windows.Forms.NumericUpDown(); this.brushTaperLabel = new System.Windows.Forms.Label(); this.brushWidthUpDown = new System.Windows.Forms.NumericUpDown(); this.brushWidthLabel = new System.Windows.Forms.Label(); this.heightAdjustSpeedLabel = new System.Windows.Forms.Label(); this.heightAdjustSpeedUpDown = new System.Windows.Forms.NumericUpDown(); this.adjustHeightRadioButton = new System.Windows.Forms.RadioButton(); this.moveCameraRadioButton = new System.Windows.Forms.RadioButton(); this.mouseModeLabel = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.axiomPictureBox = new System.Windows.Forms.PictureBox(); this.launchReleaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.terrainProperties.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.generalTerrainGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.featureSpacingTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.heightOffsetTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.heightFloorTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.heightScaleTrackBar)).BeginInit(); this.fractalParamsGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.seedZUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.seedYUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.seedXUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.fractalOffsetTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.iterationsUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.lacunarityTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.hTrackBar)).BeginInit(); this.heightMapGroupBox.SuspendLayout(); this.heightMapEditor.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); this.hmeOptionsGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.brushTaperUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.brushWidthUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.heightAdjustSpeedUpDown)).BeginInit(); this.statusStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem, this.viewToolStripMenuItem1, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1016, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loadTerrainToolStripMenuItem, this.saveTerrainToolStripMenuItem, this.loadSeedMapToolStripMenuItem, this.designateRepositoryMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // loadTerrainToolStripMenuItem // this.loadTerrainToolStripMenuItem.Name = "loadTerrainToolStripMenuItem"; this.loadTerrainToolStripMenuItem.Size = new System.Drawing.Size(230, 22); this.loadTerrainToolStripMenuItem.Text = "Load &Terrain..."; this.loadTerrainToolStripMenuItem.Click += new System.EventHandler(this.loadTerrainToolStripMenuItem_Click); // // saveTerrainToolStripMenuItem // this.saveTerrainToolStripMenuItem.Name = "saveTerrainToolStripMenuItem"; this.saveTerrainToolStripMenuItem.Size = new System.Drawing.Size(230, 22); this.saveTerrainToolStripMenuItem.Text = "&Save Terrain..."; this.saveTerrainToolStripMenuItem.Click += new System.EventHandler(this.saveTerrainToolStripMenuItem_Click); // // loadSeedMapToolStripMenuItem // this.loadSeedMapToolStripMenuItem.Name = "loadSeedMapToolStripMenuItem"; this.loadSeedMapToolStripMenuItem.Size = new System.Drawing.Size(230, 22); this.loadSeedMapToolStripMenuItem.Text = "Load Seed &Map..."; this.loadSeedMapToolStripMenuItem.Click += new System.EventHandler(this.loadSeedMapToolStripMenuItem_Click); // // designateRepositoryMenuItem // this.designateRepositoryMenuItem.Name = "designateRepositoryMenuItem"; this.designateRepositoryMenuItem.Size = new System.Drawing.Size(230, 22); this.designateRepositoryMenuItem.Text = "&Designate Asset Repository..."; this.designateRepositoryMenuItem.ToolTipText = "Designate the folder containing the asset repository that the Terrain Generator s" + "hould use"; this.designateRepositoryMenuItem.Click += new System.EventHandler(this.designateRepositoryMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(230, 22); this.exitToolStripMenuItem.Text = "&Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.createSeedHeightmapToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.viewToolStripMenuItem.Text = "&Edit"; // // createSeedHeightmapToolStripMenuItem // this.createSeedHeightmapToolStripMenuItem.Name = "createSeedHeightmapToolStripMenuItem"; this.createSeedHeightmapToolStripMenuItem.Size = new System.Drawing.Size(211, 22); this.createSeedHeightmapToolStripMenuItem.Text = "Create &Seed Heightmap..."; this.createSeedHeightmapToolStripMenuItem.Click += new System.EventHandler(this.createSeedHeightmapToolStripMenuItem_Click); // // viewToolStripMenuItem1 // this.viewToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.wireFrameToolStripMenuItem, this.displayOceanToolStripMenuItem, this.spinCameraToolStripMenuItem, this.resetCameraToolStripMenuItem}); this.viewToolStripMenuItem1.Name = "viewToolStripMenuItem1"; this.viewToolStripMenuItem1.Size = new System.Drawing.Size(41, 20); this.viewToolStripMenuItem1.Text = "&View"; this.viewToolStripMenuItem1.DropDownOpening += new System.EventHandler(this.viewToolStripMenuItem1_DropDownOpening); // // wireFrameToolStripMenuItem // this.wireFrameToolStripMenuItem.Name = "wireFrameToolStripMenuItem"; this.wireFrameToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.wireFrameToolStripMenuItem.Text = "&Wire Frame"; this.wireFrameToolStripMenuItem.Click += new System.EventHandler(this.wireFrameToolStripMenuItem_Click); // // displayOceanToolStripMenuItem // this.displayOceanToolStripMenuItem.Enabled = false; this.displayOceanToolStripMenuItem.Name = "displayOceanToolStripMenuItem"; this.displayOceanToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.displayOceanToolStripMenuItem.Text = "&Display Ocean"; this.displayOceanToolStripMenuItem.Click += new System.EventHandler(this.displayOceanToolStripMenuItem_Click); // // spinCameraToolStripMenuItem // this.spinCameraToolStripMenuItem.Name = "spinCameraToolStripMenuItem"; this.spinCameraToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.spinCameraToolStripMenuItem.Text = "&Spin Camera"; this.spinCameraToolStripMenuItem.Click += new System.EventHandler(this.spinCameraToolStripMenuItem_Click); // // resetCameraToolStripMenuItem // this.resetCameraToolStripMenuItem.Name = "resetCameraToolStripMenuItem"; this.resetCameraToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.resetCameraToolStripMenuItem.Text = "&Reset Camera"; this.resetCameraToolStripMenuItem.Click += new System.EventHandler(this.resetCameraToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.launchOnlineHelpToolStripMenuItem, this.launchReleaseNotesToolStripMenuItem, this.submitABugReToolStripMenuItem, this.aboutTerrainGeneratorToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // launchOnlineHelpToolStripMenuItem // this.launchOnlineHelpToolStripMenuItem.Name = "launchOnlineHelpToolStripMenuItem"; this.launchOnlineHelpToolStripMenuItem.Size = new System.Drawing.Size(209, 22); this.launchOnlineHelpToolStripMenuItem.Text = "&Launch Online Help"; this.launchOnlineHelpToolStripMenuItem.Click += new System.EventHandler(this.launchOnlineHelpToolStripMenuItem_Click); // // submitABugReToolStripMenuItem // this.submitABugReToolStripMenuItem.Name = "submitABugReToolStripMenuItem"; this.submitABugReToolStripMenuItem.Size = new System.Drawing.Size(209, 22); this.submitABugReToolStripMenuItem.Text = "&Submit Feedback or a Bug"; this.submitABugReToolStripMenuItem.Click += new System.EventHandler(this.submitABugReToolStripMenuItem_Click); // // aboutTerrainGeneratorToolStripMenuItem // this.aboutTerrainGeneratorToolStripMenuItem.Name = "aboutTerrainGeneratorToolStripMenuItem"; this.aboutTerrainGeneratorToolStripMenuItem.Size = new System.Drawing.Size(209, 22); this.aboutTerrainGeneratorToolStripMenuItem.Text = "&About Terrain Generator"; this.aboutTerrainGeneratorToolStripMenuItem.Click += new System.EventHandler(this.aboutTerrainGeneratorToolStripMenuItem_Click); // // toolStrip1 // this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1016, 39); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(36, 36); this.toolStripButton1.Text = "toolStripButton1"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.tabControl1.Controls.Add(this.terrainProperties); this.tabControl1.Controls.Add(this.heightMapEditor); this.tabControl1.Location = new System.Drawing.Point(3, 67); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(290, 649); this.tabControl1.TabIndex = 4; this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged); // // terrainProperties // this.terrainProperties.Controls.Add(this.flowLayoutPanel1); this.terrainProperties.Location = new System.Drawing.Point(4, 22); this.terrainProperties.Name = "terrainProperties"; this.terrainProperties.Padding = new System.Windows.Forms.Padding(3); this.terrainProperties.Size = new System.Drawing.Size(282, 623); this.terrainProperties.TabIndex = 0; this.terrainProperties.Tag = "terrainProperties"; this.terrainProperties.Text = "Terrain Properties"; this.terrainProperties.UseVisualStyleBackColor = true; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoScroll = true; this.flowLayoutPanel1.Controls.Add(this.generalTerrainButton); this.flowLayoutPanel1.Controls.Add(this.generalTerrainGroupBox); this.flowLayoutPanel1.Controls.Add(this.fractalParamsButton); this.flowLayoutPanel1.Controls.Add(this.fractalParamsGroupBox); this.flowLayoutPanel1.Controls.Add(this.heightMapParamsButton); this.flowLayoutPanel1.Controls.Add(this.heightMapGroupBox); this.flowLayoutPanel1.Location = new System.Drawing.Point(6, 6); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(274, 611); this.flowLayoutPanel1.TabIndex = 0; // // generalTerrainButton // this.generalTerrainButton.Image = global::TerrainGenerator.Properties.Resources.group_up_icon; this.generalTerrainButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.generalTerrainButton.Location = new System.Drawing.Point(3, 3); this.generalTerrainButton.Name = "generalTerrainButton"; this.generalTerrainButton.Size = new System.Drawing.Size(252, 23); this.generalTerrainButton.TabIndex = 5; this.generalTerrainButton.Text = "General Terrain Parameters"; this.generalTerrainButton.UseVisualStyleBackColor = true; this.generalTerrainButton.Click += new System.EventHandler(this.generalTerrainButton_Click); // // generalTerrainGroupBox // this.generalTerrainGroupBox.Controls.Add(this.generalTerrainHelpLink); this.generalTerrainGroupBox.Controls.Add(this.featureSpacingTrackBar); this.generalTerrainGroupBox.Controls.Add(this.featureSpacingValueLabel); this.generalTerrainGroupBox.Controls.Add(this.heightOffsetTrackBar); this.generalTerrainGroupBox.Controls.Add(this.heightOffsetValueLabel); this.generalTerrainGroupBox.Controls.Add(this.heightFloorValueLabel); this.generalTerrainGroupBox.Controls.Add(this.heightFloorTrackBar); this.generalTerrainGroupBox.Controls.Add(this.heightScaleValueLabel); this.generalTerrainGroupBox.Controls.Add(this.heightScaleTrackBar); this.generalTerrainGroupBox.Controls.Add(this.featureSpacingLabel); this.generalTerrainGroupBox.Controls.Add(this.heightFloorLabel); this.generalTerrainGroupBox.Controls.Add(this.heightOffsetLabel); this.generalTerrainGroupBox.Controls.Add(this.heightScaleLabel); this.generalTerrainGroupBox.Location = new System.Drawing.Point(3, 32); this.generalTerrainGroupBox.Name = "generalTerrainGroupBox"; this.generalTerrainGroupBox.Size = new System.Drawing.Size(252, 347); this.generalTerrainGroupBox.TabIndex = 7; this.generalTerrainGroupBox.TabStop = false; // // generalTerrainHelpLink // this.generalTerrainHelpLink.AutoSize = true; this.generalTerrainHelpLink.Location = new System.Drawing.Point(162, 323); this.generalTerrainHelpLink.Name = "generalTerrainHelpLink"; this.generalTerrainHelpLink.Size = new System.Drawing.Size(69, 13); this.generalTerrainHelpLink.TabIndex = 16; this.generalTerrainHelpLink.TabStop = true; this.generalTerrainHelpLink.Text = "What\'s This?"; this.generalTerrainHelpLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.generalTerrainHelpLink_LinkClicked); // // featureSpacingTrackBar // this.featureSpacingTrackBar.Location = new System.Drawing.Point(21, 278); this.featureSpacingTrackBar.Maximum = 1500; this.featureSpacingTrackBar.Minimum = 100; this.featureSpacingTrackBar.Name = "featureSpacingTrackBar"; this.featureSpacingTrackBar.Size = new System.Drawing.Size(210, 42); this.featureSpacingTrackBar.TabIndex = 15; this.featureSpacingTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.toolTip1.SetToolTip(this.featureSpacingTrackBar, "This value is the approximate spacing (in meters) between terrain features such a" + "s hills and mountains."); this.featureSpacingTrackBar.Value = 100; this.featureSpacingTrackBar.Scroll += new System.EventHandler(this.featureSpacingTrackBar_Scroll); // // featureSpacingValueLabel // this.featureSpacingValueLabel.AutoSize = true; this.featureSpacingValueLabel.Location = new System.Drawing.Point(128, 238); this.featureSpacingValueLabel.Name = "featureSpacingValueLabel"; this.featureSpacingValueLabel.Size = new System.Drawing.Size(13, 13); this.featureSpacingValueLabel.TabIndex = 14; this.featureSpacingValueLabel.Text = "0"; this.toolTip1.SetToolTip(this.featureSpacingValueLabel, "This value is the approximate spacing (in meters) between terrain features such a" + "s hills and mountains."); // // heightOffsetTrackBar // this.heightOffsetTrackBar.Location = new System.Drawing.Point(21, 193); this.heightOffsetTrackBar.Maximum = 500; this.heightOffsetTrackBar.Name = "heightOffsetTrackBar"; this.heightOffsetTrackBar.Size = new System.Drawing.Size(210, 42); this.heightOffsetTrackBar.TabIndex = 13; this.heightOffsetTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.toolTip1.SetToolTip(this.heightOffsetTrackBar, "This value is added to the fractal algorithm result before scaling."); this.heightOffsetTrackBar.Value = 250; this.heightOffsetTrackBar.Scroll += new System.EventHandler(this.heightOffsetTrackBar_Scroll); // // heightOffsetValueLabel // this.heightOffsetValueLabel.AutoSize = true; this.heightOffsetValueLabel.Location = new System.Drawing.Point(128, 168); this.heightOffsetValueLabel.Name = "heightOffsetValueLabel"; this.heightOffsetValueLabel.Size = new System.Drawing.Size(13, 13); this.heightOffsetValueLabel.TabIndex = 12; this.heightOffsetValueLabel.Text = "0"; this.toolTip1.SetToolTip(this.heightOffsetValueLabel, "This value is added to the fractal algorithm result before scaling."); // // heightFloorValueLabel // this.heightFloorValueLabel.AutoSize = true; this.heightFloorValueLabel.Location = new System.Drawing.Point(128, 92); this.heightFloorValueLabel.Name = "heightFloorValueLabel"; this.heightFloorValueLabel.Size = new System.Drawing.Size(13, 13); this.heightFloorValueLabel.TabIndex = 11; this.heightFloorValueLabel.Text = "0"; this.toolTip1.SetToolTip(this.heightFloorValueLabel, "This is the minimum height (in meters) of your terrain. Any terrain height compu" + "ted to be below this value will be set to this value."); // // heightFloorTrackBar // this.heightFloorTrackBar.Location = new System.Drawing.Point(21, 123); this.heightFloorTrackBar.Maximum = 500; this.heightFloorTrackBar.Name = "heightFloorTrackBar"; this.heightFloorTrackBar.Size = new System.Drawing.Size(210, 42); this.heightFloorTrackBar.TabIndex = 10; this.heightFloorTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.toolTip1.SetToolTip(this.heightFloorTrackBar, "This is the minimum height (in meters) of your terrain. Any terrain height compu" + "ted to be below this value will be set to this value."); this.heightFloorTrackBar.Scroll += new System.EventHandler(this.heightFloorTrackBar_Scroll); // // heightScaleValueLabel // this.heightScaleValueLabel.AutoSize = true; this.heightScaleValueLabel.Location = new System.Drawing.Point(128, 22); this.heightScaleValueLabel.Name = "heightScaleValueLabel"; this.heightScaleValueLabel.Size = new System.Drawing.Size(13, 13); this.heightScaleValueLabel.TabIndex = 9; this.heightScaleValueLabel.Text = "0"; this.toolTip1.SetToolTip(this.heightScaleValueLabel, "This height (in Meters) is used to scale the terrain height generated by the frac" + "tal algorithm. It is the approximate altitude of mountains."); // // heightScaleTrackBar // this.heightScaleTrackBar.Location = new System.Drawing.Point(21, 47); this.heightScaleTrackBar.Maximum = 500; this.heightScaleTrackBar.Name = "heightScaleTrackBar"; this.heightScaleTrackBar.Size = new System.Drawing.Size(210, 42); this.heightScaleTrackBar.TabIndex = 5; this.heightScaleTrackBar.TickFrequency = 10; this.heightScaleTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.toolTip1.SetToolTip(this.heightScaleTrackBar, "This height (in Meters) is used to scale the terrain height generated by the frac" + "tal algorithm. It is the approximate altitude of mountains."); this.heightScaleTrackBar.Scroll += new System.EventHandler(this.heightScaleTrackBar_Scroll); // // featureSpacingLabel // this.featureSpacingLabel.AutoSize = true; this.featureSpacingLabel.Location = new System.Drawing.Point(18, 238); this.featureSpacingLabel.Name = "featureSpacingLabel"; this.featureSpacingLabel.Size = new System.Drawing.Size(85, 13); this.featureSpacingLabel.TabIndex = 7; this.featureSpacingLabel.Text = "Feature Spacing"; this.toolTip1.SetToolTip(this.featureSpacingLabel, "This value is the approximate spacing (in meters) between terrain features such a" + "s hills and mountains."); // // heightFloorLabel // this.heightFloorLabel.AutoSize = true; this.heightFloorLabel.Location = new System.Drawing.Point(18, 92); this.heightFloorLabel.Name = "heightFloorLabel"; this.heightFloorLabel.Size = new System.Drawing.Size(64, 13); this.heightFloorLabel.TabIndex = 6; this.heightFloorLabel.Text = "Height Floor"; this.toolTip1.SetToolTip(this.heightFloorLabel, "This is the minimum height (in meters) of your terrain. Any terrain height compu" + "ted to be below this value will be set to this value."); // // heightOffsetLabel // this.heightOffsetLabel.AutoSize = true; this.heightOffsetLabel.Location = new System.Drawing.Point(18, 168); this.heightOffsetLabel.Name = "heightOffsetLabel"; this.heightOffsetLabel.Size = new System.Drawing.Size(69, 13); this.heightOffsetLabel.TabIndex = 5; this.heightOffsetLabel.Text = "Height Offset"; this.toolTip1.SetToolTip(this.heightOffsetLabel, "This value is added to the fractal algorithm result before scaling."); // // heightScaleLabel // this.heightScaleLabel.AutoSize = true; this.heightScaleLabel.Location = new System.Drawing.Point(18, 22); this.heightScaleLabel.Name = "heightScaleLabel"; this.heightScaleLabel.Size = new System.Drawing.Size(68, 13); this.heightScaleLabel.TabIndex = 4; this.heightScaleLabel.Text = "Height Scale"; this.toolTip1.SetToolTip(this.heightScaleLabel, "This height (in Meters) is used to scale the terrain height generated by the frac" + "tal algorithm. It is the approximate altitude of mountains."); // // fractalParamsButton // this.fractalParamsButton.Image = global::TerrainGenerator.Properties.Resources.group_down_icon; this.fractalParamsButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.fractalParamsButton.Location = new System.Drawing.Point(3, 385); this.fractalParamsButton.Name = "fractalParamsButton"; this.fractalParamsButton.Size = new System.Drawing.Size(252, 23); this.fractalParamsButton.TabIndex = 4; this.fractalParamsButton.Text = "Fractal Parameters"; this.fractalParamsButton.UseVisualStyleBackColor = true; this.fractalParamsButton.Click += new System.EventHandler(this.fractalParamsButton_Click); // // fractalParamsGroupBox // this.fractalParamsGroupBox.Controls.Add(this.fractalParamsHelpLink); this.fractalParamsGroupBox.Controls.Add(this.seedZUpDown); this.fractalParamsGroupBox.Controls.Add(this.seedYUpDown); this.fractalParamsGroupBox.Controls.Add(this.seedXUpDown); this.fractalParamsGroupBox.Controls.Add(this.fractalOffsetTrackBar); this.fractalParamsGroupBox.Controls.Add(this.fractalOffsetValueLabel); this.fractalParamsGroupBox.Controls.Add(this.iterationsUpDown); this.fractalParamsGroupBox.Controls.Add(this.lacunarityTrackBar); this.fractalParamsGroupBox.Controls.Add(this.lacunarityValueLabel); this.fractalParamsGroupBox.Controls.Add(this.hTrackBar); this.fractalParamsGroupBox.Controls.Add(this.hValueLabel); this.fractalParamsGroupBox.Controls.Add(this.fractalOffsetLabel); this.fractalParamsGroupBox.Controls.Add(this.iterationsLabel); this.fractalParamsGroupBox.Controls.Add(this.seedXLabel); this.fractalParamsGroupBox.Controls.Add(this.lacunarityLabel); this.fractalParamsGroupBox.Controls.Add(this.seedYLabel); this.fractalParamsGroupBox.Controls.Add(this.hLabel); this.fractalParamsGroupBox.Controls.Add(this.seedZLabel); this.fractalParamsGroupBox.Location = new System.Drawing.Point(3, 414); this.fractalParamsGroupBox.Name = "fractalParamsGroupBox"; this.fractalParamsGroupBox.Size = new System.Drawing.Size(252, 366); this.fractalParamsGroupBox.TabIndex = 8; this.fractalParamsGroupBox.TabStop = false; this.fractalParamsGroupBox.Visible = false; // // fractalParamsHelpLink // this.fractalParamsHelpLink.AutoSize = true; this.fractalParamsHelpLink.Location = new System.Drawing.Point(176, 342); this.fractalParamsHelpLink.Name = "fractalParamsHelpLink"; this.fractalParamsHelpLink.Size = new System.Drawing.Size(69, 13); this.fractalParamsHelpLink.TabIndex = 24; this.fractalParamsHelpLink.TabStop = true; this.fractalParamsHelpLink.Text = "What\'s This?"; this.fractalParamsHelpLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.fractalParamsHelpLink_LinkClicked); // // seedZUpDown // this.seedZUpDown.DecimalPlaces = 2; this.seedZUpDown.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.seedZUpDown.Location = new System.Drawing.Point(131, 90); this.seedZUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.seedZUpDown.Minimum = new decimal(new int[] { 10000, 0, 0, -2147483648}); this.seedZUpDown.Name = "seedZUpDown"; this.seedZUpDown.Size = new System.Drawing.Size(100, 20); this.seedZUpDown.TabIndex = 23; this.seedZUpDown.ValueChanged += new System.EventHandler(this.seedZUpDown_ValueChanged); // // seedYUpDown // this.seedYUpDown.DecimalPlaces = 2; this.seedYUpDown.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.seedYUpDown.Location = new System.Drawing.Point(131, 55); this.seedYUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.seedYUpDown.Minimum = new decimal(new int[] { 10000, 0, 0, -2147483648}); this.seedYUpDown.Name = "seedYUpDown"; this.seedYUpDown.Size = new System.Drawing.Size(100, 20); this.seedYUpDown.TabIndex = 22; this.seedYUpDown.ValueChanged += new System.EventHandler(this.seedYUpDown_ValueChanged); // // seedXUpDown // this.seedXUpDown.DecimalPlaces = 2; this.seedXUpDown.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.seedXUpDown.Location = new System.Drawing.Point(131, 21); this.seedXUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.seedXUpDown.Minimum = new decimal(new int[] { 10000, 0, 0, -2147483648}); this.seedXUpDown.Name = "seedXUpDown"; this.seedXUpDown.Size = new System.Drawing.Size(100, 20); this.seedXUpDown.TabIndex = 21; this.seedXUpDown.ValueChanged += new System.EventHandler(this.seedXUpDown_ValueChanged); // // fractalOffsetTrackBar // this.fractalOffsetTrackBar.Location = new System.Drawing.Point(21, 297); this.fractalOffsetTrackBar.Maximum = 1000; this.fractalOffsetTrackBar.Name = "fractalOffsetTrackBar"; this.fractalOffsetTrackBar.Size = new System.Drawing.Size(210, 42); this.fractalOffsetTrackBar.TabIndex = 20; this.fractalOffsetTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.fractalOffsetTrackBar.Scroll += new System.EventHandler(this.fractalOffsetTrackBar_Scroll); // // fractalOffsetValueLabel // this.fractalOffsetValueLabel.AutoSize = true; this.fractalOffsetValueLabel.Location = new System.Drawing.Point(128, 281); this.fractalOffsetValueLabel.Name = "fractalOffsetValueLabel"; this.fractalOffsetValueLabel.Size = new System.Drawing.Size(13, 13); this.fractalOffsetValueLabel.TabIndex = 19; this.fractalOffsetValueLabel.Text = "0"; // // iterationsUpDown // this.iterationsUpDown.Location = new System.Drawing.Point(131, 249); this.iterationsUpDown.Name = "iterationsUpDown"; this.iterationsUpDown.Size = new System.Drawing.Size(100, 20); this.iterationsUpDown.TabIndex = 18; this.iterationsUpDown.ValueChanged += new System.EventHandler(this.iterationsUpDown_ValueChanged); // // lacunarityTrackBar // this.lacunarityTrackBar.Location = new System.Drawing.Point(21, 206); this.lacunarityTrackBar.Maximum = 1000; this.lacunarityTrackBar.Name = "lacunarityTrackBar"; this.lacunarityTrackBar.Size = new System.Drawing.Size(210, 42); this.lacunarityTrackBar.TabIndex = 17; this.lacunarityTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.lacunarityTrackBar.Scroll += new System.EventHandler(this.lacunarityTrackBar_Scroll); // // lacunarityValueLabel // this.lacunarityValueLabel.AutoSize = true; this.lacunarityValueLabel.Location = new System.Drawing.Point(128, 190); this.lacunarityValueLabel.Name = "lacunarityValueLabel"; this.lacunarityValueLabel.Size = new System.Drawing.Size(13, 13); this.lacunarityValueLabel.TabIndex = 16; this.lacunarityValueLabel.Text = "0"; // // hTrackBar // this.hTrackBar.Location = new System.Drawing.Point(21, 145); this.hTrackBar.Maximum = 1000; this.hTrackBar.Name = "hTrackBar"; this.hTrackBar.Size = new System.Drawing.Size(210, 42); this.hTrackBar.TabIndex = 15; this.hTrackBar.TickStyle = System.Windows.Forms.TickStyle.None; this.hTrackBar.Scroll += new System.EventHandler(this.hTrackBar_Scroll); // // hValueLabel // this.hValueLabel.AutoSize = true; this.hValueLabel.Location = new System.Drawing.Point(128, 129); this.hValueLabel.Name = "hValueLabel"; this.hValueLabel.Size = new System.Drawing.Size(13, 13); this.hValueLabel.TabIndex = 14; this.hValueLabel.Text = "0"; // // fractalOffsetLabel // this.fractalOffsetLabel.AutoSize = true; this.fractalOffsetLabel.Location = new System.Drawing.Point(18, 281); this.fractalOffsetLabel.Name = "fractalOffsetLabel"; this.fractalOffsetLabel.Size = new System.Drawing.Size(70, 13); this.fractalOffsetLabel.TabIndex = 13; this.fractalOffsetLabel.Text = "Fractal Offset"; // // iterationsLabel // this.iterationsLabel.AutoSize = true; this.iterationsLabel.Location = new System.Drawing.Point(18, 251); this.iterationsLabel.Name = "iterationsLabel"; this.iterationsLabel.Size = new System.Drawing.Size(50, 13); this.iterationsLabel.TabIndex = 10; this.iterationsLabel.Tag = ""; this.iterationsLabel.Text = "Iterations"; // // seedXLabel // this.seedXLabel.AutoSize = true; this.seedXLabel.Location = new System.Drawing.Point(18, 23); this.seedXLabel.Name = "seedXLabel"; this.seedXLabel.Size = new System.Drawing.Size(42, 13); this.seedXLabel.TabIndex = 0; this.seedXLabel.Text = "Seed X"; // // lacunarityLabel // this.lacunarityLabel.AutoSize = true; this.lacunarityLabel.Location = new System.Drawing.Point(18, 190); this.lacunarityLabel.Name = "lacunarityLabel"; this.lacunarityLabel.Size = new System.Drawing.Size(56, 13); this.lacunarityLabel.TabIndex = 9; this.lacunarityLabel.Text = "Lacunarity"; // // seedYLabel // this.seedYLabel.AutoSize = true; this.seedYLabel.Location = new System.Drawing.Point(18, 57); this.seedYLabel.Name = "seedYLabel"; this.seedYLabel.Size = new System.Drawing.Size(42, 13); this.seedYLabel.TabIndex = 1; this.seedYLabel.Text = "Seed Y"; // // hLabel // this.hLabel.AutoSize = true; this.hLabel.Location = new System.Drawing.Point(18, 129); this.hLabel.Name = "hLabel"; this.hLabel.Size = new System.Drawing.Size(15, 13); this.hLabel.TabIndex = 8; this.hLabel.Text = "H"; // // seedZLabel // this.seedZLabel.AutoSize = true; this.seedZLabel.Location = new System.Drawing.Point(18, 92); this.seedZLabel.Name = "seedZLabel"; this.seedZLabel.Size = new System.Drawing.Size(42, 13); this.seedZLabel.TabIndex = 2; this.seedZLabel.Text = "Seed Z"; // // heightMapParamsButton // this.heightMapParamsButton.Image = global::TerrainGenerator.Properties.Resources.group_down_icon; this.heightMapParamsButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.heightMapParamsButton.Location = new System.Drawing.Point(3, 786); this.heightMapParamsButton.Name = "heightMapParamsButton"; this.heightMapParamsButton.Size = new System.Drawing.Size(252, 23); this.heightMapParamsButton.TabIndex = 9; this.heightMapParamsButton.Text = "Height Map Parameters"; this.heightMapParamsButton.UseVisualStyleBackColor = true; this.heightMapParamsButton.Click += new System.EventHandler(this.heightMapParamsButton_Click); // // heightMapGroupBox // this.heightMapGroupBox.Controls.Add(this.heightMapParamsHelpLink); this.heightMapGroupBox.Controls.Add(this.useSeedMapCheckBox); this.heightMapGroupBox.Controls.Add(this.mapOriginZTextBox); this.heightMapGroupBox.Controls.Add(this.mapOriginZLabel); this.heightMapGroupBox.Controls.Add(this.mapOriginXLabel); this.heightMapGroupBox.Controls.Add(this.mapOriginXTextBox); this.heightMapGroupBox.Controls.Add(this.mpsTextBox); this.heightMapGroupBox.Controls.Add(this.mpsLabel); this.heightMapGroupBox.Controls.Add(this.heightOutsideTextBox); this.heightMapGroupBox.Controls.Add(this.heightOutsideLabel); this.heightMapGroupBox.Location = new System.Drawing.Point(3, 815); this.heightMapGroupBox.Name = "heightMapGroupBox"; this.heightMapGroupBox.Size = new System.Drawing.Size(252, 225); this.heightMapGroupBox.TabIndex = 10; this.heightMapGroupBox.TabStop = false; this.heightMapGroupBox.Visible = false; // // heightMapParamsHelpLink // this.heightMapParamsHelpLink.AutoSize = true; this.heightMapParamsHelpLink.Location = new System.Drawing.Point(176, 198); this.heightMapParamsHelpLink.Name = "heightMapParamsHelpLink"; this.heightMapParamsHelpLink.Size = new System.Drawing.Size(69, 13); this.heightMapParamsHelpLink.TabIndex = 9; this.heightMapParamsHelpLink.TabStop = true; this.heightMapParamsHelpLink.Text = "What\'s This?"; this.heightMapParamsHelpLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.heightMapParamsHelpLink_LinkClicked); // // useSeedMapCheckBox // this.useSeedMapCheckBox.AutoSize = true; this.useSeedMapCheckBox.Enabled = false; this.useSeedMapCheckBox.Location = new System.Drawing.Point(21, 19); this.useSeedMapCheckBox.Name = "useSeedMapCheckBox"; this.useSeedMapCheckBox.Size = new System.Drawing.Size(97, 17); this.useSeedMapCheckBox.TabIndex = 8; this.useSeedMapCheckBox.Text = "Use Seed Map"; this.useSeedMapCheckBox.UseVisualStyleBackColor = true; this.useSeedMapCheckBox.CheckedChanged += new System.EventHandler(this.useSeedMapCheckBox_CheckedChanged); // // mapOriginZTextBox // this.mapOriginZTextBox.Enabled = false; this.mapOriginZTextBox.Location = new System.Drawing.Point(131, 150); this.mapOriginZTextBox.Name = "mapOriginZTextBox"; this.mapOriginZTextBox.Size = new System.Drawing.Size(100, 20); this.mapOriginZTextBox.TabIndex = 7; this.mapOriginZTextBox.Leave += new System.EventHandler(this.mapOriginZTextBox_TextChanged); // // mapOriginZLabel // this.mapOriginZLabel.AutoSize = true; this.mapOriginZLabel.Location = new System.Drawing.Point(18, 153); this.mapOriginZLabel.Name = "mapOriginZLabel"; this.mapOriginZLabel.Size = new System.Drawing.Size(68, 13); this.mapOriginZLabel.TabIndex = 6; this.mapOriginZLabel.Text = "Map Origin Z"; // // mapOriginXLabel // this.mapOriginXLabel.AutoSize = true; this.mapOriginXLabel.Location = new System.Drawing.Point(18, 118); this.mapOriginXLabel.Name = "mapOriginXLabel"; this.mapOriginXLabel.Size = new System.Drawing.Size(68, 13); this.mapOriginXLabel.TabIndex = 5; this.mapOriginXLabel.Text = "Map Origin X"; // // mapOriginXTextBox // this.mapOriginXTextBox.Enabled = false; this.mapOriginXTextBox.Location = new System.Drawing.Point(131, 115); this.mapOriginXTextBox.Name = "mapOriginXTextBox"; this.mapOriginXTextBox.Size = new System.Drawing.Size(100, 20); this.mapOriginXTextBox.TabIndex = 4; this.mapOriginXTextBox.Leave += new System.EventHandler(this.mapOriginXTextBox_TextChanged); // // mpsTextBox // this.mpsTextBox.Enabled = false; this.mpsTextBox.Location = new System.Drawing.Point(131, 80); this.mpsTextBox.Name = "mpsTextBox"; this.mpsTextBox.Size = new System.Drawing.Size(100, 20); this.mpsTextBox.TabIndex = 3; this.mpsTextBox.Leave += new System.EventHandler(this.mpsTextBox_TextChanged); // // mpsLabel // this.mpsLabel.AutoSize = true; this.mpsLabel.Location = new System.Drawing.Point(18, 83); this.mpsLabel.Name = "mpsLabel"; this.mpsLabel.Size = new System.Drawing.Size(96, 13); this.mpsLabel.TabIndex = 2; this.mpsLabel.Text = "Meters Per Sample"; // // heightOutsideTextBox // this.heightOutsideTextBox.Enabled = false; this.heightOutsideTextBox.Location = new System.Drawing.Point(131, 46); this.heightOutsideTextBox.Name = "heightOutsideTextBox"; this.heightOutsideTextBox.Size = new System.Drawing.Size(100, 20); this.heightOutsideTextBox.TabIndex = 1; this.heightOutsideTextBox.Leave += new System.EventHandler(this.heightOutsideTextBox_TextChanged); // // heightOutsideLabel // this.heightOutsideLabel.AutoSize = true; this.heightOutsideLabel.Location = new System.Drawing.Point(18, 49); this.heightOutsideLabel.Name = "heightOutsideLabel"; this.heightOutsideLabel.Size = new System.Drawing.Size(101, 13); this.heightOutsideLabel.TabIndex = 0; this.heightOutsideLabel.Text = "Height Outside Map"; // // heightMapEditor // this.heightMapEditor.Controls.Add(this.flowLayoutPanel2); this.heightMapEditor.Location = new System.Drawing.Point(4, 22); this.heightMapEditor.Name = "heightMapEditor"; this.heightMapEditor.Padding = new System.Windows.Forms.Padding(3); this.heightMapEditor.Size = new System.Drawing.Size(282, 623); this.heightMapEditor.TabIndex = 1; this.heightMapEditor.Tag = "heightMapEditor"; this.heightMapEditor.Text = "Height Map Editor"; this.heightMapEditor.UseVisualStyleBackColor = true; // // flowLayoutPanel2 // this.flowLayoutPanel2.Controls.Add(this.hmeOptionsButton); this.flowLayoutPanel2.Controls.Add(this.hmeOptionsGroupBox); this.flowLayoutPanel2.Location = new System.Drawing.Point(6, 3); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(270, 614); this.flowLayoutPanel2.TabIndex = 0; // // hmeOptionsButton // this.hmeOptionsButton.Image = global::TerrainGenerator.Properties.Resources.group_up_icon; this.hmeOptionsButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.hmeOptionsButton.Location = new System.Drawing.Point(3, 3); this.hmeOptionsButton.Name = "hmeOptionsButton"; this.hmeOptionsButton.Size = new System.Drawing.Size(267, 23); this.hmeOptionsButton.TabIndex = 0; this.hmeOptionsButton.Text = "Options"; this.hmeOptionsButton.UseVisualStyleBackColor = true; this.hmeOptionsButton.Click += new System.EventHandler(this.hmeOptionsButton_Click); // // hmeOptionsGroupBox // this.hmeOptionsGroupBox.Controls.Add(this.heightMapEditorHelpLink); this.hmeOptionsGroupBox.Controls.Add(this.brushShapeComboBox); this.hmeOptionsGroupBox.Controls.Add(this.brushShapeLabel); this.hmeOptionsGroupBox.Controls.Add(this.brushTaperUpDown); this.hmeOptionsGroupBox.Controls.Add(this.brushTaperLabel); this.hmeOptionsGroupBox.Controls.Add(this.brushWidthUpDown); this.hmeOptionsGroupBox.Controls.Add(this.brushWidthLabel); this.hmeOptionsGroupBox.Controls.Add(this.heightAdjustSpeedLabel); this.hmeOptionsGroupBox.Controls.Add(this.heightAdjustSpeedUpDown); this.hmeOptionsGroupBox.Controls.Add(this.adjustHeightRadioButton); this.hmeOptionsGroupBox.Controls.Add(this.moveCameraRadioButton); this.hmeOptionsGroupBox.Controls.Add(this.mouseModeLabel); this.hmeOptionsGroupBox.Location = new System.Drawing.Point(3, 32); this.hmeOptionsGroupBox.Name = "hmeOptionsGroupBox"; this.hmeOptionsGroupBox.Size = new System.Drawing.Size(267, 248); this.hmeOptionsGroupBox.TabIndex = 1; this.hmeOptionsGroupBox.TabStop = false; // // heightMapEditorHelpLink // this.heightMapEditorHelpLink.AutoSize = true; this.heightMapEditorHelpLink.Location = new System.Drawing.Point(176, 213); this.heightMapEditorHelpLink.Name = "heightMapEditorHelpLink"; this.heightMapEditorHelpLink.Size = new System.Drawing.Size(69, 13); this.heightMapEditorHelpLink.TabIndex = 1; this.heightMapEditorHelpLink.TabStop = true; this.heightMapEditorHelpLink.Text = "What\'s This?"; this.heightMapEditorHelpLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.heightMapEditorHelpLink_LinkClicked); // // brushShapeComboBox // this.brushShapeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.brushShapeComboBox.Enabled = false; this.brushShapeComboBox.FormattingEnabled = true; this.brushShapeComboBox.Items.AddRange(new object[] { "Square", "Circle", "Diamond", "Slash", "Backslash", "HBar", "VBar"}); this.brushShapeComboBox.Location = new System.Drawing.Point(150, 162); this.brushShapeComboBox.Name = "brushShapeComboBox"; this.brushShapeComboBox.Size = new System.Drawing.Size(95, 21); this.brushShapeComboBox.TabIndex = 10; this.brushShapeComboBox.SelectedIndexChanged += new System.EventHandler(this.brushShapeComboBox_SelectedIndexChanged); // // brushShapeLabel // this.brushShapeLabel.AutoSize = true; this.brushShapeLabel.Location = new System.Drawing.Point(19, 165); this.brushShapeLabel.Name = "brushShapeLabel"; this.brushShapeLabel.Size = new System.Drawing.Size(68, 13); this.brushShapeLabel.TabIndex = 9; this.brushShapeLabel.Text = "Brush Shape"; // // brushTaperUpDown // this.brushTaperUpDown.Enabled = false; this.brushTaperUpDown.Increment = new decimal(new int[] { 5, 0, 0, 0}); this.brushTaperUpDown.Location = new System.Drawing.Point(150, 132); this.brushTaperUpDown.Name = "brushTaperUpDown"; this.brushTaperUpDown.Size = new System.Drawing.Size(95, 20); this.brushTaperUpDown.TabIndex = 8; this.brushTaperUpDown.Value = new decimal(new int[] { 100, 0, 0, 0}); this.brushTaperUpDown.ValueChanged += new System.EventHandler(this.brushTaperUpDown_ValueChanged); // // brushTaperLabel // this.brushTaperLabel.AutoSize = true; this.brushTaperLabel.Location = new System.Drawing.Point(19, 134); this.brushTaperLabel.Name = "brushTaperLabel"; this.brushTaperLabel.Size = new System.Drawing.Size(65, 13); this.brushTaperLabel.TabIndex = 7; this.brushTaperLabel.Text = "Brush Taper"; // // brushWidthUpDown // this.brushWidthUpDown.Enabled = false; this.brushWidthUpDown.Increment = new decimal(new int[] { 2, 0, 0, 0}); this.brushWidthUpDown.Location = new System.Drawing.Point(150, 103); this.brushWidthUpDown.Maximum = new decimal(new int[] { 29, 0, 0, 0}); this.brushWidthUpDown.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.brushWidthUpDown.Name = "brushWidthUpDown"; this.brushWidthUpDown.Size = new System.Drawing.Size(95, 20); this.brushWidthUpDown.TabIndex = 6; this.brushWidthUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); this.brushWidthUpDown.ValueChanged += new System.EventHandler(this.brushWidthUpDown_ValueChanged); // // brushWidthLabel // this.brushWidthLabel.AutoSize = true; this.brushWidthLabel.Location = new System.Drawing.Point(19, 105); this.brushWidthLabel.Name = "brushWidthLabel"; this.brushWidthLabel.Size = new System.Drawing.Size(65, 13); this.brushWidthLabel.TabIndex = 5; this.brushWidthLabel.Text = "Brush Width"; // // heightAdjustSpeedLabel // this.heightAdjustSpeedLabel.AutoSize = true; this.heightAdjustSpeedLabel.Location = new System.Drawing.Point(19, 76); this.heightAdjustSpeedLabel.Name = "heightAdjustSpeedLabel"; this.heightAdjustSpeedLabel.Size = new System.Drawing.Size(104, 13); this.heightAdjustSpeedLabel.TabIndex = 4; this.heightAdjustSpeedLabel.Text = "Height Adjust Speed"; // // heightAdjustSpeedUpDown // this.heightAdjustSpeedUpDown.Enabled = false; this.heightAdjustSpeedUpDown.Location = new System.Drawing.Point(150, 74); this.heightAdjustSpeedUpDown.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.heightAdjustSpeedUpDown.Name = "heightAdjustSpeedUpDown"; this.heightAdjustSpeedUpDown.Size = new System.Drawing.Size(95, 20); this.heightAdjustSpeedUpDown.TabIndex = 3; this.heightAdjustSpeedUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); this.heightAdjustSpeedUpDown.ValueChanged += new System.EventHandler(this.heightAdjustSpeedUpDown_ValueChanged); // // adjustHeightRadioButton // this.adjustHeightRadioButton.AutoSize = true; this.adjustHeightRadioButton.Enabled = false; this.adjustHeightRadioButton.Location = new System.Drawing.Point(157, 43); this.adjustHeightRadioButton.Name = "adjustHeightRadioButton"; this.adjustHeightRadioButton.Size = new System.Drawing.Size(88, 17); this.adjustHeightRadioButton.TabIndex = 2; this.adjustHeightRadioButton.Text = "Adjust Height"; this.adjustHeightRadioButton.UseVisualStyleBackColor = true; this.adjustHeightRadioButton.CheckedChanged += new System.EventHandler(this.adjustHeightRadioButton_CheckedChanged); // // moveCameraRadioButton // this.moveCameraRadioButton.AutoSize = true; this.moveCameraRadioButton.Checked = true; this.moveCameraRadioButton.Location = new System.Drawing.Point(42, 43); this.moveCameraRadioButton.Name = "moveCameraRadioButton"; this.moveCameraRadioButton.Size = new System.Drawing.Size(91, 17); this.moveCameraRadioButton.TabIndex = 1; this.moveCameraRadioButton.TabStop = true; this.moveCameraRadioButton.Text = "Move Camera"; this.moveCameraRadioButton.UseVisualStyleBackColor = true; this.moveCameraRadioButton.CheckedChanged += new System.EventHandler(this.moveCameraRadioButton_CheckedChanged); // // mouseModeLabel // this.mouseModeLabel.AutoSize = true; this.mouseModeLabel.Location = new System.Drawing.Point(19, 27); this.mouseModeLabel.Name = "mouseModeLabel"; this.mouseModeLabel.Size = new System.Drawing.Size(69, 13); this.mouseModeLabel.TabIndex = 0; this.mouseModeLabel.Text = "Mouse Mode"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabel2}); this.statusStrip1.Location = new System.Drawing.Point(0, 719); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(1016, 22); this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(0, 17); // // axiomPictureBox // this.axiomPictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.axiomPictureBox.Location = new System.Drawing.Point(293, 66); this.axiomPictureBox.Name = "axiomPictureBox"; this.axiomPictureBox.Size = new System.Drawing.Size(723, 650); this.axiomPictureBox.TabIndex = 2; this.axiomPictureBox.TabStop = false; this.axiomPictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.axiomPictureBox_MouseDown); this.axiomPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.axiomPictureBox_MouseMove); this.axiomPictureBox.Resize += new System.EventHandler(this.axiomPictureBox_Resize); this.axiomPictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.axiomPictureBox_MouseUp); this.axiomPictureBox.MouseEnter += new System.EventHandler(this.axiomPictureBox_MouseEnter); // // launchReleaseNotesToolStripMenuItem // this.launchReleaseNotesToolStripMenuItem.Name = "launchReleaseNotesToolStripMenuItem"; this.launchReleaseNotesToolStripMenuItem.Size = new System.Drawing.Size(209, 22); this.launchReleaseNotesToolStripMenuItem.Text = "Launch Release Notes"; this.launchReleaseNotesToolStripMenuItem.Click += new System.EventHandler(this.launchReleaseNotesToolStripMenuItem_Click); // // TerrainGenerator // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1016, 741); this.Controls.Add(this.tabControl1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.axiomPictureBox); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.MainMenuStrip = this.menuStrip1; this.Name = "TerrainGenerator"; this.Text = "Terrain Generator"; this.Resize += new System.EventHandler(this.TerrainGenerator_Resize); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TerrainGenerator_FormClosing); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.TerrainGenerator_KeyUp); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TerrainGenerator_KeyDown); this.Load += new System.EventHandler(this.TerrainGenerator_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.tabControl1.ResumeLayout(false); this.terrainProperties.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.generalTerrainGroupBox.ResumeLayout(false); this.generalTerrainGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.featureSpacingTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.heightOffsetTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.heightFloorTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.heightScaleTrackBar)).EndInit(); this.fractalParamsGroupBox.ResumeLayout(false); this.fractalParamsGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.seedZUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.seedYUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.seedXUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.fractalOffsetTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.iterationsUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.lacunarityTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.hTrackBar)).EndInit(); this.heightMapGroupBox.ResumeLayout(false); this.heightMapGroupBox.PerformLayout(); this.heightMapEditor.ResumeLayout(false); this.flowLayoutPanel2.ResumeLayout(false); this.hmeOptionsGroupBox.ResumeLayout(false); this.hmeOptionsGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.brushTaperUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.brushWidthUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.heightAdjustSpeedUpDown)).EndInit(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axiomPictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem1; private System.Windows.Forms.PictureBox axiomPictureBox; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem wireFrameToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem displayOceanToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem spinCameraToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage terrainProperties; private System.Windows.Forms.TabPage heightMapEditor; private System.Windows.Forms.Label seedZLabel; private System.Windows.Forms.Label seedYLabel; private System.Windows.Forms.Label seedXLabel; private System.Windows.Forms.Button fractalParamsButton; private System.Windows.Forms.Label lacunarityLabel; private System.Windows.Forms.Label hLabel; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button generalTerrainButton; private System.Windows.Forms.Label iterationsLabel; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.GroupBox generalTerrainGroupBox; private System.Windows.Forms.GroupBox fractalParamsGroupBox; private System.Windows.Forms.Button heightMapParamsButton; private System.Windows.Forms.GroupBox heightMapGroupBox; private System.Windows.Forms.TextBox heightOutsideTextBox; private System.Windows.Forms.Label heightOutsideLabel; private System.Windows.Forms.TextBox mapOriginZTextBox; private System.Windows.Forms.Label mapOriginZLabel; private System.Windows.Forms.Label mapOriginXLabel; private System.Windows.Forms.TextBox mapOriginXTextBox; private System.Windows.Forms.TextBox mpsTextBox; private System.Windows.Forms.Label mpsLabel; private System.Windows.Forms.Label fractalOffsetLabel; private System.Windows.Forms.Label featureSpacingLabel; private System.Windows.Forms.Label heightFloorLabel; private System.Windows.Forms.Label heightOffsetLabel; private System.Windows.Forms.Label heightScaleLabel; private System.Windows.Forms.TrackBar heightScaleTrackBar; private System.Windows.Forms.Label heightScaleValueLabel; private System.Windows.Forms.Label heightFloorValueLabel; private System.Windows.Forms.TrackBar heightFloorTrackBar; private System.Windows.Forms.TrackBar heightOffsetTrackBar; private System.Windows.Forms.Label heightOffsetValueLabel; private System.Windows.Forms.TrackBar featureSpacingTrackBar; private System.Windows.Forms.Label featureSpacingValueLabel; private System.Windows.Forms.Label hValueLabel; private System.Windows.Forms.TrackBar hTrackBar; private System.Windows.Forms.TrackBar fractalOffsetTrackBar; private System.Windows.Forms.Label fractalOffsetValueLabel; private System.Windows.Forms.NumericUpDown iterationsUpDown; private System.Windows.Forms.TrackBar lacunarityTrackBar; private System.Windows.Forms.Label lacunarityValueLabel; private System.Windows.Forms.NumericUpDown seedZUpDown; private System.Windows.Forms.NumericUpDown seedYUpDown; private System.Windows.Forms.NumericUpDown seedXUpDown; private System.Windows.Forms.CheckBox useSeedMapCheckBox; private System.Windows.Forms.ToolStripMenuItem loadSeedMapToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.Button hmeOptionsButton; private System.Windows.Forms.GroupBox hmeOptionsGroupBox; private System.Windows.Forms.RadioButton adjustHeightRadioButton; private System.Windows.Forms.RadioButton moveCameraRadioButton; private System.Windows.Forms.Label mouseModeLabel; private System.Windows.Forms.Label heightAdjustSpeedLabel; private System.Windows.Forms.NumericUpDown heightAdjustSpeedUpDown; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; private System.Windows.Forms.NumericUpDown brushWidthUpDown; private System.Windows.Forms.Label brushWidthLabel; private System.Windows.Forms.ToolStripMenuItem loadTerrainToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveTerrainToolStripMenuItem; private System.Windows.Forms.NumericUpDown brushTaperUpDown; private System.Windows.Forms.Label brushTaperLabel; private System.Windows.Forms.ComboBox brushShapeComboBox; private System.Windows.Forms.Label brushShapeLabel; private System.Windows.Forms.ToolStripMenuItem resetCameraToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem createSeedHeightmapToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem launchOnlineHelpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutTerrainGeneratorToolStripMenuItem; private System.Windows.Forms.LinkLabel generalTerrainHelpLink; private System.Windows.Forms.LinkLabel fractalParamsHelpLink; private System.Windows.Forms.LinkLabel heightMapParamsHelpLink; private System.Windows.Forms.LinkLabel heightMapEditorHelpLink; private System.Windows.Forms.ToolStripMenuItem submitABugReToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem designateRepositoryMenuItem; private System.Windows.Forms.ToolStripMenuItem launchReleaseNotesToolStripMenuItem; } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using Grpc.Core; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// grpc_call from <grpc/grpc.h> /// </summary> internal class CallSafeHandle : SafeHandleZeroIsInvalid { const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionRegistry completionRegistry; [DllImport("grpc_csharp_ext.dll")] static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern void grpcsharp_call_destroy(IntPtr call); private CallSafeHandle() { } public static CallSafeHandle Create(ChannelSafeHandle channel, CompletionRegistry registry, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline) { var result = grpcsharp_channel_create_call(channel, cq, method, host, deadline); result.SetCompletionRegistry(registry); return result; } public void SetCompletionRegistry(CompletionRegistry completionRegistry) { this.completionRegistry = completionRegistry; } public void StartUnary(byte[] payload, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray) .CheckOk(); } public void StartUnary(byte[] payload, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray) { grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray) .CheckOk(); } public void StartClientStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_client_streaming(this, ctx, metadataArray).CheckOk(); } public void StartServerStreaming(byte[] payload, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray).CheckOk(); } public void StartDuplexStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray).CheckOk(); } public void StartSendMessage(byte[] payload, BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length)).CheckOk(); } public void StartSendCloseFromClient(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } public void StartSendStatusFromServer(Status status, BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, status.Detail, metadataArray).CheckOk(); } public void StartReceiveMessage(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_recv_message(this, ctx).CheckOk(); } public void StartServerSide(BatchCompletionDelegate callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_call_start_serverside(this, ctx).CheckOk(); } public void Cancel() { grpcsharp_call_cancel(this).CheckOk(); } public void CancelWithStatus(Status status) { grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk(); } protected override bool ReleaseHandle() { grpcsharp_call_destroy(handle); return true; } private static uint GetFlags(bool buffered) { return buffered ? 0 : GRPC_WRITE_BUFFER_HINT; } } }
namespace IrcSays.Preferences.Models { public class ColorsPreferences : PreferenceBase { private string _background; private string _editBackground; private string _edit; private string _default; private string _action; private string _ctcp; private string _info; private string _invite; private string _join; private string _kick; private string _mode; private string _nick; private string _notice; private string _own; private string _part; private string _quit; private string _topic; private string _error; private string _newMarker; private string _oldMarker; private string _attention; private string _noiseActivity; private string _chatActivity; private string _alert; private string _windowBackground; private string _windowForeground; private string _highlight; private string _color0; private string _color1; private string _color2; private string _color3; private string _color4; private string _color5; private string _color6; private string _color7; private string _color8; private string _color9; private string _color10; private string _color11; private string _color12; private string _color13; private string _color14; private string _color15; private string _transmit; private ChatPalette _palette; public ColorsPreferences() { _background = "Black"; _editBackground = "Black"; _edit = "White"; _default = "White"; _action = "White"; _ctcp = "Yellow"; _info = "White"; _invite = "Yellow"; _join = "Lavender"; _kick = "Lavender"; _mode = "Yellow"; _nick = "Yellow"; _notice = "Yellow"; _own = "Gray"; _part = "Lavender"; _quit = "Lavender"; _topic = "Yellow"; _error = "Red"; _newMarker = "#FF002B00"; _oldMarker = "#FF3C0000"; _attention = "#404000"; _noiseActivity = "#647491"; _chatActivity = "#A58F5A"; _alert = "#FFFF00"; _windowBackground = "#293955"; _windowForeground = "White"; _highlight = "#3399FF"; _color0 = "#FFFFFF"; _color1 = "#000000"; _color2 = "#00007F"; _color3 = "#009300"; _color4 = "#FF0000"; _color5 = "#7F0000"; _color6 = "#9C009C"; _color7 = "#FC7F00"; _color8 = "#FFFF00"; _color9 = "#00FC00"; _color10 = "#009393"; _color11 = "#00FFFF"; _color12 = "#0000FC"; _color13 = "#FF00FF"; _color14 = "#7F7F7F"; _color15 = "#D2D2D2"; _transmit = "#00FF00"; _palette = default(ChatPalette); } public string Background { get { return _background; } set { _background = value; OnPropertyChanged(); } } public string EditBackground { get { return _editBackground; } set { _editBackground = value; OnPropertyChanged(); } } public string Edit { get { return _edit; } set { _edit = value; OnPropertyChanged(); } } public string Default { get { return _default; } set { _default = value; OnPropertyChanged(); } } public string Action { get { return _action; } set { _action = value; OnPropertyChanged(); } } public string Ctcp { get { return _ctcp; } set { _ctcp = value; OnPropertyChanged(); } } public string Info { get { return _info; } set { _info = value; OnPropertyChanged(); } } public string Invite { get { return _invite; } set { _invite = value; OnPropertyChanged(); } } public string Join { get { return _join; } set { _join = value; OnPropertyChanged(); } } public string Kick { get { return _kick; } set { _kick = value; OnPropertyChanged(); } } public string Mode { get { return _mode; } set { _mode = value; OnPropertyChanged(); } } public string Nick { get { return _nick; } set { _nick = value; OnPropertyChanged(); } } public string Notice { get { return _notice; } set { _notice = value; OnPropertyChanged(); } } public string Own { get { return _own; } set { _own = value; OnPropertyChanged(); } } public string Part { get { return _part; } set { _part = value; OnPropertyChanged(); } } public string Quit { get { return _quit; } set { _quit = value; OnPropertyChanged(); } } public string Topic { get { return _topic; } set { _topic = value; OnPropertyChanged(); } } public string Error { get { return _error; } set { _error = value; OnPropertyChanged(); } } public string NewMarker { get { return _newMarker; } set { _newMarker = value; OnPropertyChanged(); } } public string OldMarker { get { return _oldMarker; } set { _oldMarker = value; OnPropertyChanged(); } } public string Attention { get { return _attention; } set { _attention = value; OnPropertyChanged(); } } public string NoiseActivity { get { return _noiseActivity; } set { _noiseActivity = value; OnPropertyChanged(); } } public string ChatActivity { get { return _chatActivity; } set { _chatActivity = value; OnPropertyChanged(); } } public string Alert { get { return _alert; } set { _alert = value; OnPropertyChanged(); } } public string WindowBackground { get { return _windowBackground; } set { _windowBackground = value; OnPropertyChanged(); } } public string WindowForeground { get { return _windowForeground; } set { _windowForeground = value; OnPropertyChanged(); } } public string Highlight { get { return _highlight; } set { _highlight = value; OnPropertyChanged(); } } public string Color0 { get { return _color0; } set { _color0 = value; OnPropertyChanged(); } } public string Color1 { get { return _color1; } set { _color1 = value; OnPropertyChanged(); } } public string Color2 { get { return _color2; } set { _color2 = value; OnPropertyChanged(); } } public string Color3 { get { return _color3; } set { _color3 = value; OnPropertyChanged(); } } public string Color4 { get { return _color4; } set { _color4 = value; OnPropertyChanged(); } } public string Color5 { get { return _color5; } set { _color5 = value; OnPropertyChanged(); } } public string Color6 { get { return _color6; } set { _color6 = value; OnPropertyChanged(); } } public string Color7 { get { return _color7; } set { _color7 = value; OnPropertyChanged(); } } public string Color8 { get { return _color8; } set { _color8 = value; OnPropertyChanged(); } } public string Color9 { get { return _color9; } set { _color9 = value; OnPropertyChanged(); } } public string Color10 { get { return _color10; } set { _color10 = value; OnPropertyChanged(); } } public string Color11 { get { return _color11; } set { _color11 = value; OnPropertyChanged(); } } public string Color12 { get { return _color12; } set { _color12 = value; OnPropertyChanged(); } } public string Color13 { get { return _color13; } set { _color13 = value; OnPropertyChanged(); } } public string Color14 { get { return _color14; } set { _color14 = value; OnPropertyChanged(); } } public string Color15 { get { return _color15; } set { _color15 = value; OnPropertyChanged(); } } public string Transmit { get { return _transmit; } set { _transmit = value; OnPropertyChanged(); } } public ChatPalette Palette { get { return _palette; } set { _palette = value; OnPropertyChanged(); } } } }
// Copyright (C) 2009-2017 Luca Piccioni // // 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.Drawing; using System.Drawing.Imaging; using System.IO; namespace OpenGL.Objects { /// <summary> /// Basic <see cref="IImageCodecPlugin"/> implementation based on actual .NET framework implementation. /// </summary> public class CoreImagingImageCodecPlugin : IImageCodecPlugin { #region OpenGL Interoperability static void ConvertImageFormat(System.Drawing.Imaging.ImageFormat from, out string to) { if (from.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid) { to = ImageFormat.Bitmap; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid) { to = ImageFormat.Jpeg; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid) { to = ImageFormat.Png; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Exif.Guid) { to = ImageFormat.Exif; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid) { to = ImageFormat.Tiff; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid) { to = ImageFormat.Gif; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Icon.Guid) { to = ImageFormat.Ico; } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Emf.Guid) { throw new ArgumentException(String.Format("not supported image format {0}", from)); } else if (from.Guid == System.Drawing.Imaging.ImageFormat.MemoryBmp.Guid) { throw new ArgumentException(String.Format("not supported image format {0}", from)); } else if (from.Guid == System.Drawing.Imaging.ImageFormat.Wmf.Guid) { throw new ArgumentException(String.Format("not supported image format {0}", from)); } else throw new ArgumentException(String.Format("not supported image format {0}", from)); } static void ConvertImageFormat(string from, out System.Drawing.Imaging.ImageFormat to) { switch (from) { case ImageFormat.Bitmap: to = System.Drawing.Imaging.ImageFormat.Bmp; break; case ImageFormat.Jpeg: to = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ImageFormat.Png: to = System.Drawing.Imaging.ImageFormat.Png; break; case ImageFormat.Exif: to = System.Drawing.Imaging.ImageFormat.Exif; break; case ImageFormat.Tiff: to = System.Drawing.Imaging.ImageFormat.Tiff; break; case ImageFormat.Gif: to = System.Drawing.Imaging.ImageFormat.Gif; break; case ImageFormat.Ico: to = System.Drawing.Imaging.ImageFormat.Icon; break; default: throw new NotSupportedException(String.Format("{0} is not supported image format", from)); } } static void ConvertPixelFormat(System.Drawing.Bitmap bitmap, out PixelLayout to) { System.Drawing.Imaging.PixelFormat from = bitmap.PixelFormat; int flags = bitmap.Flags; bool sRGB = false; #if false foreach (System.Drawing.Imaging.PropertyItem exifProperty in bitmap.PropertyItems) { switch (exifProperty.Id) { case ImageCodecPlugin.ExifTagColorSpace: ImageCodecPlugin.ExifColorSpace value = (ImageCodecPlugin.ExifColorSpace)BitConverter.ToUInt16(exifProperty.Value, 0); switch (value) { case ImageCodecPlugin.ExifColorSpace.sRGB: sRGB = true; break; default: break; } break; case ImageCodecPlugin.ExifTagGamma: UInt32 a1 = BitConverter.ToUInt32(exifProperty.Value, 0); UInt32 a2 = BitConverter.ToUInt32(exifProperty.Value, 4); Double gamma = (Double)a1 / (Double)a2; break; } } #endif if ((flags & (int)ImageFlags.ColorSpaceRgb) != 0) { ConvertPixelFormatRgb(from, out to, sRGB); } else if ((flags & (int)ImageFlags.ColorSpaceGray) != 0) { switch (from) { case System.Drawing.Imaging.PixelFormat.Format1bppIndexed: case System.Drawing.Imaging.PixelFormat.Format4bppIndexed: case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: to = PixelLayout.R8; break; case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale: to = PixelLayout.R16; break; case System.Drawing.Imaging.PixelFormat.Format32bppArgb: to = PixelLayout.BGRA32; break; default: throw new ArgumentException(String.Format("GRAY pixel format {0} not supported", from)); } } else if ((flags & (int)ImageFlags.ColorSpaceYcck) != 0) { throw new ArgumentException(String.Format("YCCK pixel format {0} not supported", from)); } else if ((flags & (int)ImageFlags.ColorSpaceYcbcr) != 0) { ConvertPixelFormatRgb(from, out to, sRGB); } else if ((flags & (int)ImageFlags.ColorSpaceCmyk) != 0) { throw new ArgumentException(String.Format("CMYK pixel format {0} not supported", from)); } else { ConvertPixelFormatNoFlags(from, out to, sRGB); } } private static void ConvertPixelFormatNoFlags(System.Drawing.Imaging.PixelFormat from, out PixelLayout to, bool sRGB) { switch (from) { case System.Drawing.Imaging.PixelFormat.Format16bppRgb555: to = PixelLayout.BGR15; break; case System.Drawing.Imaging.PixelFormat.Format16bppRgb565: to = PixelLayout.BGR16; break; case System.Drawing.Imaging.PixelFormat.Format24bppRgb: to = sRGB ? PixelLayout.SBGR24 : PixelLayout.BGR24; break; case System.Drawing.Imaging.PixelFormat.Format32bppRgb: to = PixelLayout.BGRA32; break; case System.Drawing.Imaging.PixelFormat.Format16bppArgb1555: to = PixelLayout.BGR15; break; case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale: to = PixelLayout.R16; break; case System.Drawing.Imaging.PixelFormat.Format48bppRgb: to = PixelLayout.BGR48; break; case System.Drawing.Imaging.PixelFormat.Format64bppPArgb: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); case System.Drawing.Imaging.PixelFormat.Canonical: to = (sRGB) ? PixelLayout.SBGR24 : PixelLayout.BGR24; break; case System.Drawing.Imaging.PixelFormat.Format32bppArgb: to = PixelLayout.BGRA32; break; case System.Drawing.Imaging.PixelFormat.Format64bppArgb: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); default: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); } } private static void ConvertPixelFormatRgb(System.Drawing.Imaging.PixelFormat from, out PixelLayout to, bool sRGB) { switch (from) { case System.Drawing.Imaging.PixelFormat.Format1bppIndexed: case System.Drawing.Imaging.PixelFormat.Format4bppIndexed: case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: to = PixelLayout.BGR24; break; case System.Drawing.Imaging.PixelFormat.Format16bppRgb555: to = PixelLayout.BGR15; break; case System.Drawing.Imaging.PixelFormat.Format16bppRgb565: to = PixelLayout.BGR16; break; case System.Drawing.Imaging.PixelFormat.Format24bppRgb: to = sRGB ? PixelLayout.SBGR24 : PixelLayout.BGR24; break; case System.Drawing.Imaging.PixelFormat.Format32bppRgb: to = PixelLayout.BGRA32; break; case System.Drawing.Imaging.PixelFormat.Format16bppArgb1555: to = PixelLayout.BGR15; break; case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale: to = PixelLayout.R16; break; case System.Drawing.Imaging.PixelFormat.Format48bppRgb: to = PixelLayout.BGR48; break; case System.Drawing.Imaging.PixelFormat.Format64bppPArgb: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); case System.Drawing.Imaging.PixelFormat.Canonical: to = (sRGB) ? PixelLayout.SBGR24 : PixelLayout.BGR24; break; case System.Drawing.Imaging.PixelFormat.Format32bppArgb: to = PixelLayout.BGRA32; break; case System.Drawing.Imaging.PixelFormat.Format64bppArgb: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); default: throw new ArgumentException(String.Format("RGB pixel format {0} not supported", from)); } } static void ConvertPixelFormat(PixelLayout from, out System.Drawing.Imaging.PixelFormat to, out int flags) { switch (from) { case PixelLayout.R8: to = System.Drawing.Imaging.PixelFormat.Format8bppIndexed; flags = (int)ImageFlags.ColorSpaceGray; break; case PixelLayout.R16: to = System.Drawing.Imaging.PixelFormat.Format16bppGrayScale; flags = (int)ImageFlags.ColorSpaceGray; break; case PixelLayout.BGR15: to = System.Drawing.Imaging.PixelFormat.Format16bppRgb555; flags = (int)ImageFlags.ColorSpaceRgb; break; case PixelLayout.BGR16: to = System.Drawing.Imaging.PixelFormat.Format16bppRgb565; flags = (int)ImageFlags.ColorSpaceRgb; break; case PixelLayout.BGR24: to = System.Drawing.Imaging.PixelFormat.Format24bppRgb; flags = (int)ImageFlags.ColorSpaceRgb; break; case PixelLayout.BGRA32: to = System.Drawing.Imaging.PixelFormat.Format32bppArgb; flags = (int)ImageFlags.ColorSpaceRgb; break; default: throw new ArgumentException(String.Format("pixel format {0} not supported", from)); } } #endregion #region IImageCodecPlugin Implementation /// <summary> /// Plugin name. /// </summary> public string Name { get { return ("CoreImaging"); } } /// <summary> /// Determine whether this plugin is available for the current process. /// </summary> /// <returns> /// It returns a boolean value indicating whether the plugin is available for the current /// process. /// </returns> public bool CheckAvailability() { // This plugin is always available return (true); } /// <summary> /// Gets the list of media formats supported for reading. /// </summary> /// <value> /// The supported formats which this media codec plugin can read. /// </value> public IEnumerable<string> SupportedReadFormats { get { List<string> supportedFormats = new List<string>(); foreach (ImageCodecInfo decoder in ImageCodecInfo.GetImageDecoders()) { if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Bmp.Guid) supportedFormats.Add(ImageFormat.Bitmap); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid) supportedFormats.Add(ImageFormat.Jpeg); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Icon.Guid) supportedFormats.Add(ImageFormat.Ico); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Png.Guid) supportedFormats.Add(ImageFormat.Png); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Tiff.Guid) supportedFormats.Add(ImageFormat.Tiff); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Gif.Guid) supportedFormats.Add(ImageFormat.Gif); else if (decoder.FormatID == System.Drawing.Imaging.ImageFormat.Exif.Guid) supportedFormats.Add(ImageFormat.Exif); } return (supportedFormats); } } /// <summary> /// Check whether an media format is supported for reading. /// </summary> /// <param name="format"> /// A <see cref="String"/> that specify the media format to test for read support. /// </param> /// <returns> /// A <see cref="Boolean"/> indicating whether <paramref name="format"/> is supported. /// </returns> public bool IsReadSupported(string format) { System.Drawing.Imaging.ImageFormat imagingFormat; try { ConvertImageFormat(format, out imagingFormat); } catch (NotSupportedException) { return (false); } int formatIndex = Array.FindIndex(ImageCodecInfo.GetImageDecoders(), 0, delegate(ImageCodecInfo item) { return (item.FormatID == imagingFormat.Guid); }); return (formatIndex >= 0); } /// <summary> /// Gets the list of media formats supported for writing. /// </summary> /// <value> /// The supported formats which this media codec plugin can write. /// </value> public IEnumerable<string> SupportedWriteFormats { get { List<string> supportedFormats = new List<string>(); foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders()) { if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Bmp.Guid) supportedFormats.Add(ImageFormat.Bitmap); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid) supportedFormats.Add(ImageFormat.Jpeg); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Icon.Guid) supportedFormats.Add(ImageFormat.Ico); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Png.Guid) supportedFormats.Add(ImageFormat.Png); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Tiff.Guid) supportedFormats.Add(ImageFormat.Tiff); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Gif.Guid) supportedFormats.Add(ImageFormat.Gif); else if (encoder.FormatID == System.Drawing.Imaging.ImageFormat.Exif.Guid) supportedFormats.Add(ImageFormat.Exif); } return (supportedFormats); } } /// <summary> /// Check whether an media format is supported for writing. /// </summary> /// <param name="format"> /// An <see cref="String"/> that specify the media format to test for write support. /// </param> /// <returns> /// A <see cref="Boolean"/> indicating whether <paramref name="format"/> is supported. /// </returns> public bool IsWriteSupported(string format) { System.Drawing.Imaging.ImageFormat imagingFormat; try { ConvertImageFormat(format, out imagingFormat); } catch (NotSupportedException) { return (false); } int formatIndex = Array.FindIndex(ImageCodecInfo.GetImageEncoders(), 0, delegate(ImageCodecInfo item) { return (item.FormatID == imagingFormat.Guid); }); return (formatIndex >= 0); } /// <summary> /// Determine the plugin priority for a certain image format. /// </summary> /// <param name="format"> /// An <see cref="ImageFormat"/> specifying the image format to test for priority. /// </param> /// <returns> /// It returns an integer value indicating the priority of this implementation respect other ones supporting the same /// image format. Conventionally, a value of 0 indicates a totally impartial plugin implementation; a value less than 0 indicates /// a more confident implementation respect other plugins; a value greater than 0 indicates a fallback implementation respect other /// plugins. /// /// This implementation of this routine returns -1. The reasoning is that this plugin implementation is very slow in Query and Load, due /// the .NET abstraction. However, it is a very usefull fallback plugin since it can open the most of common image formats. /// </returns> public int GetPriority(string format) { switch (format) { default: return (-1); } } /// <summary> /// Query media informations. /// </summary> /// <param name="path"> /// A <see cref="String"/> that specify the media path. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream. /// </param> /// <returns> /// A <see cref="ImageInfo"/> containing information about the specified media. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null. /// </exception> public ImageInfo QueryInfo(string path, ImageCodecCriteria criteria) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { return (QueryInfo(fs, criteria)); } } /// <summary> /// Query media informations. /// </summary> /// <param name="path"> /// A <see cref="String"/> that specify the media path. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream. /// </param> /// <returns> /// A <see cref="ImageInfo"/> containing information about the specified media. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null. /// </exception> public ImageInfo QueryInfo(Stream stream, ImageCodecCriteria criteria) { if (stream == null) throw new ArgumentNullException("stream"); if (criteria == null) throw new ArgumentNullException("criteria"); ImageInfo info = new ImageInfo(); using (Bitmap iBitmap = new Bitmap(stream)) { PixelLayout iBitmapPixelType; string containerFormat; ConvertImageFormat(iBitmap.RawFormat, out containerFormat); ConvertPixelFormat(iBitmap, out iBitmapPixelType); info.ContainerFormat = containerFormat; info.PixelType = iBitmapPixelType; info.Width = (uint)iBitmap.Width; info.Height = (uint)iBitmap.Height; } return (info); } /// <summary> /// Load media from stream. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> where the media data is stored. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream. /// </param> /// <returns> /// An <see cref="Image"/> holding the media data. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null. /// </exception> public Image Load(string path, ImageCodecCriteria criteria) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { return (Load(fs, criteria)); } } /// <summary> /// Load media from stream. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> where the media data is stored. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an media stream. /// </param> /// <returns> /// An <see cref="Image"/> holding the media data. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/> or <paramref name="criteria"/> is null. /// </exception> public Image Load(Stream stream, ImageCodecCriteria criteria) { if (stream == null) throw new ArgumentNullException("stream"); if (criteria == null) throw new ArgumentNullException("criteria"); using (System.Drawing.Bitmap iBitmap = new System.Drawing.Bitmap(stream)) { Image image; PixelLayout pType, pConvType; // Allocate image raster ConvertPixelFormat(iBitmap, out pType); // Check for hardware/software support if (pType.IsSupportedInternalFormat() == false) { if (criteria.IsSet(ImageCodecCriteria.SoftwareSupport) && (bool)criteria[ImageCodecCriteria.SoftwareSupport]) { // Pixel type not directly supported by hardware... try to guess suitable software conversion throw new NotImplementedException("pixel type " + pType.ToString() + " is not supported by hardware neither software"); } else throw new InvalidOperationException("pixel type " + pType.ToString() + " is not supported by hardware"); } else pConvType = pType; image = new Image(); image.Create(pType, (uint)iBitmap.Width, (uint)iBitmap.Height); switch (iBitmap.PixelFormat) { case System.Drawing.Imaging.PixelFormat.Format1bppIndexed: case System.Drawing.Imaging.PixelFormat.Format4bppIndexed: case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: if (Khronos.Platform.RunningMono) { // Bug 676362 - Bitmap Clone does not format return image to requested PixelFormat // https://bugzilla.novell.com/show_bug.cgi?id=676362 // // ATM no mono version has resolved the bug; current workaround is performing image // sampling pixel by pixel, using internal conversion routines, even if it is very slow LoadBitmapByPixel(iBitmap, image); } else LoadBitmapByClone(iBitmap, image); break; default: LoadBitmapByLockBits(iBitmap, image); break; } return (image); } } /// <summary> /// Internal method for creating Image from Bitmap. /// </summary> /// <param name="bitmap"> /// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify image conversion criteria. /// </param> /// <returns> /// It returns a <see cref="Image"/> instance that's equivalent to <paramref name="bitmap"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="bitmap"/> or <see cref="criteria"/> is null. /// </exception> internal static Image LoadFromBitmap(Bitmap bitmap, ImageCodecCriteria criteria) { if (bitmap == null) throw new ArgumentNullException("bitmap"); if (criteria == null) throw new ArgumentNullException("criteria"); PixelLayout pType, pConvType; // Allocate image raster ConvertPixelFormat(bitmap, out pType); // Check for hardware/software support if (pType.IsSupportedInternalFormat() == false) { if (criteria.IsSet(ImageCodecCriteria.SoftwareSupport) && ((bool)criteria[ImageCodecCriteria.SoftwareSupport])) { // Pixel type not directly supported by hardware... try to guess suitable software conversion throw new NotImplementedException(String.Format("pixel type {0} is not supported by hardware neither software", pType)); } else throw new InvalidOperationException(String.Format("pixel type {0} is not supported by hardware", pType)); } else pConvType = pType; Image image = new Image(pType, (uint)bitmap.Width, (uint)bitmap.Height); switch (bitmap.PixelFormat) { case System.Drawing.Imaging.PixelFormat.Format1bppIndexed: case System.Drawing.Imaging.PixelFormat.Format4bppIndexed: case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: if (Khronos.Platform.RunningMono) { // Bug 676362 - Bitmap Clone does not format return image to requested PixelFormat // https://bugzilla.novell.com/show_bug.cgi?id=676362 // // ATM no mono version has resolved the bug; current workaround is performing image // sampling pixel by pixel, using internal conversion routines, even if it is very slow LoadBitmapByPixel(bitmap, image); } else LoadBitmapByClone(bitmap, image); break; default: LoadBitmapByLockBits(bitmap, image); break; } return (image); } /// <summary> /// Loads the bitmap by locking its bits. /// </summary> /// <param name="bitmap"> /// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance. /// </param> /// <param name='image'> /// A <see cref="Image"/> instance that will store <paramref name="bitmap"/> data. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="bitmap"/> or <paramref name="image"/> is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Exception thrown if <paramref name="image"/> line stride is greater than <paramref name="bitmap"/> line /// stride. This never happens if <paramref name="image"/> is dimensionally compatible with <paramref name="bitmap"/>. /// </exception> private static void LoadBitmapByLockBits(Bitmap bitmap, Image image) { if (bitmap == null) throw new ArgumentNullException("bitmap"); if (image == null) throw new ArgumentNullException("image"); System.Drawing.Imaging.BitmapData iBitmapData = null; IntPtr imageData = image.ImageBuffer; try { // Obtain source and destination data pointers iBitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); // Copy Bitmap data dst Image unsafe { byte* hImageDataPtr = (byte*)imageData.ToPointer(); byte* iBitmapDataPtr = (byte*)iBitmapData.Scan0.ToPointer(); uint hImageDataStride = image.Stride; uint iBitmapDataStride = (uint)iBitmapData.Stride; if (hImageDataStride > iBitmapDataStride) throw new InvalidOperationException("invalid bitmap stride"); // .NET Image library stores bitmap scan line data in memory padded dst 4 bytes boundaries // .NET Image Library present a bottom up image, so invert the scan line order iBitmapDataPtr = iBitmapDataPtr + ((image.Height-1) * iBitmapDataStride); for (uint line = 0; line < image.Height; line++, hImageDataPtr += hImageDataStride, iBitmapDataPtr -= iBitmapDataStride) Memory.Copy(hImageDataPtr, iBitmapDataPtr, hImageDataStride); } } finally { if (iBitmapData != null) bitmap.UnlockBits(iBitmapData); } } /// <summary> /// Loads the bitmap by cloning its data to a more compatible format. /// </summary> /// <param name="bitmap"> /// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance. /// </param> /// <param name='image'> /// A <see cref="Image"/> instance that will store <paramref name="bitmap"/> data. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="bitmap"/> or <paramref name="image"/> is null. /// </exception> /// <remarks> /// <para> /// Cloning <paramref name="bitmap"/> is useful whenever the bitmap have a pixel format not directly portable /// to any well-known format (i.e. 1 bit pixel, palettized pixel, etc.). /// </para> /// <para> /// This method is very memory consuming, because cloning cause to use additionally memory. /// </para> /// </remarks> private static void LoadBitmapByPixel(Bitmap bitmap, Image image) { if (bitmap == null) throw new ArgumentNullException("bitmap"); if (image == null) throw new ArgumentNullException("image"); // FIXME Maybe this method is no more necessary throw new NotImplementedException(); #if false for (uint y = 0; y < image.Height; y++) { for (uint x = 0; x < image.Width; x++) { System.Drawing.Color bitmapColor = bitmap.GetPixel((int)x, (int)y); //image[x, y] = Pixel.GetNativeIColor(new ColorRGBA32(bitmapColor.R, bitmapColor.G, bitmapColor.B, bitmapColor.A), image.PixelLayout); //image[x, y] = new ColorBGR24(bitmapColor.R, bitmapColor.G, bitmapColor.B); } } #endif } /// <summary> /// Loads the bitmap by cloning its data to a more compatible format. /// </summary> /// <param name="bitmap"> /// A <see cref="Drawing.Bitmap"/> to be converted into an <see cref="Image"/> instance. /// </param> /// <param name='image'> /// A <see cref="Image"/> instance that will store <paramref name="bitmap"/> data. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="bitmap"/> or <paramref name="image"/> is null. /// </exception> /// <remarks> /// <para> /// Cloning <paramref name="bitmap"/> is useful whenever the bitmap have a pixel format not directly portable /// to any well-known format (i.e. 1 bit pixel, palettized pixel, etc.). /// </para> /// <para> /// This method is very memory consuming, because cloning cause to use additionally memory. /// </para> /// </remarks> private static void LoadBitmapByClone(Bitmap bitmap, Image image) { if (bitmap == null) throw new ArgumentNullException("bitmap"); if (image == null) throw new ArgumentNullException("image"); System.Drawing.Imaging.PixelFormat iBitmapFormat; int iBitmapFlags; // Determine the clone bitmap pixel format ConvertPixelFormat(image.PixelLayout, out iBitmapFormat, out iBitmapFlags); // Clone image converting the pixel format using (System.Drawing.Bitmap clonedBitmap = bitmap.Clone(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), iBitmapFormat)) { LoadBitmapByLockBits(clonedBitmap, image); } } /// <summary> /// Save media to stream. /// </summary> /// <param name="path"> /// A <see cref="String"/> that specify the media path. /// </param> /// <param name="image"> /// A <see cref="Image"/> holding the data to be stored. /// </param> /// <param name="format"> /// A <see cref="String"/> that specify the media format to used for saving <paramref name="image"/>. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an image stream. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/>, <paramref name="image"/> or <paramref name="criteria"/> is null. /// </exception> public void Save(string path, Image image, string format, ImageCodecCriteria criteria) { using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write)) { Save(fs, image, format, criteria); } } /// <summary> /// Save media to stream. /// </summary> /// <param name="stream"> /// A <see cref="IO.Stream"/> which stores the media data. /// </param> /// <param name="image"> /// A <see cref="Image"/> holding the data to be stored. /// </param> /// <param name="format"> /// A <see cref="String"/> that specify the media format to used for saving <paramref name="image"/>. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an image stream. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/>, <paramref name="image"/> or <paramref name="criteria"/> is null. /// </exception> public void Save(Stream stream, Image image, string format, ImageCodecCriteria criteria) { System.Drawing.Imaging.ImageFormat bitmapFormat; System.Drawing.Imaging.PixelFormat bitmapPixelFormat; int iBitmapFlags; ConvertImageFormat(format, out bitmapFormat); ConvertPixelFormat(image.PixelLayout, out bitmapPixelFormat, out iBitmapFlags); // Obtain source and destination data pointers using (Bitmap bitmap = new Bitmap((int)image.Width, (int)image.Height, bitmapPixelFormat)) { #region Copy Image To Bitmap BitmapData iBitmapData = null; IntPtr imageData = image.ImageBuffer; try { iBitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); // Copy Image data dst Bitmap unsafe { byte* hImageDataPtr = (byte*)imageData.ToPointer(); byte* iBitmapDataPtr = (byte*)iBitmapData.Scan0.ToPointer(); uint hImageDataStride = image.Stride; uint iBitmapDataStride = (uint)iBitmapData.Stride; // .NET Image Library stores bitmap scan line data in memory padded dst 4 bytes boundaries // .NET Image Library expect a bottom up image, so invert the scan line order iBitmapDataPtr = iBitmapDataPtr + ((image.Height-1) * iBitmapDataStride); for (uint line = 0; line < image.Height; line++, hImageDataPtr += hImageDataStride, iBitmapDataPtr -= iBitmapDataStride) Memory.Copy(iBitmapDataPtr, hImageDataPtr, hImageDataStride); } } finally { if (iBitmapData != null) bitmap.UnlockBits(iBitmapData); } #endregion #region Support Indexed Pixel Formats if ((iBitmapFlags & (int)ImageFlags.ColorSpaceGray) != 0) { ColorPalette bitmapPalette = bitmap.Palette; switch (bitmapPixelFormat) { case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: // Create grayscale palette for (int i = 0; i <= 255; i++) bitmapPalette.Entries[i] = Color.FromArgb(i, i, i); break; } bitmap.Palette = bitmapPalette; } #endregion // Save image with the specified format ImageCodecInfo encoderInfo = Array.Find(ImageCodecInfo.GetImageEncoders(), delegate(ImageCodecInfo item) { return (item.FormatID == bitmapFormat.Guid); }); EncoderParameters encoderParams = null; try { EncoderParameters encoderInfoParamList = bitmap.GetEncoderParameterList(encoderInfo.Clsid); EncoderParameter[] encoderInfoParams = encoderInfoParamList != null ? encoderInfoParamList.Param : null; bool supportQuality = false; int paramsCount = 0; if (encoderInfoParams != null) { Array.ForEach(encoderInfoParams, delegate(EncoderParameter item) { if (item.Encoder.Guid == Encoder.Quality.Guid) { supportQuality = true; paramsCount++; } }); } encoderParams = new EncoderParameters(paramsCount); paramsCount = 0; if (supportQuality) encoderParams.Param[paramsCount++] = new EncoderParameter(Encoder.Quality, 100); } catch (Exception) { // Encoder does not support parameters } bitmap.Save(stream, encoderInfo, encoderParams); } } #endregion } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// RangeAttribute is used to supply a range of values to an /// individual parameter of a parameterized test. /// </summary> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)] public class RangeAttribute : DataAttribute, IParameterDataSource { // We use an object[] so that the individual // elements may have their type changed in GetData // if necessary // TODO: This causes a lot of boxing so we should eliminate it private object[] _data; #region Ints /// <summary> /// Construct a range of ints using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> public RangeAttribute(int from, int to) : this(from, to, from > to ? -1 : 1) { } /// <summary> /// Construct a range of ints specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(int from, int to, int step) { Guard.ArgumentValid(step > 0 && to >= from || step < 0 && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); int count = (to - from) / step + 1; _data = new object[count]; int index = 0; for (int val = from; index < count; val += step) _data[index++] = val; } #endregion #region Unsigned Ints /// <summary> /// Construct a range of unsigned ints using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> [CLSCompliant(false)] public RangeAttribute(uint from, uint to) : this(from, to, 1u) { } /// <summary> /// Construct a range of unsigned ints specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> [CLSCompliant(false)] public RangeAttribute(uint from, uint to, uint step) { Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step"); Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to"); uint count = (to - from) / step + 1; _data = new object[count]; uint index = 0; for (uint val = from; index < count; val += step) _data[index++] = val; } #endregion #region Longs /// <summary> /// Construct a range of longs using a default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> public RangeAttribute(long from, long to) : this(from, to, from > to ? -1L : 1L) { } /// <summary> /// Construct a range of longs /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(long from, long to, long step) { Guard.ArgumentValid(step > 0L && to >= from || step < 0L && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); long count = (to - from) / step + 1; _data = new object[count]; int index = 0; for (long val = from; index < count; val += step) _data[index++] = val; } #endregion #region Unsigned Longs /// <summary> /// Construct a range of unsigned longs using default step of 1 /// </summary> /// <param name="from"></param> /// <param name="to"></param> [CLSCompliant(false)] public RangeAttribute(ulong from, ulong to) : this(from, to, 1ul) { } /// <summary> /// Construct a range of unsigned longs specifying the step size /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> [CLSCompliant(false)] public RangeAttribute(ulong from, ulong to, ulong step) { Guard.ArgumentValid(step > 0, "Step must be greater than zero", "step"); Guard.ArgumentValid(to >= from, "Value of to must be greater than or equal to from", "to"); ulong count = (to - from) / step + 1; _data = new object[count]; ulong index = 0; for (ulong val = from; index < count; val += step) _data[index++] = val; } #endregion #region Doubles /// <summary> /// Construct a range of doubles /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(double from, double to, double step) { Guard.ArgumentValid(step > 0.0D && to >= from || step < 0.0D && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); double aStep = Math.Abs(step); double tol = aStep / 1000; int count = (int)(Math.Abs(to - from) / aStep + tol + 1); _data = new object[count]; int index = 0; for (double val = from; index < count; val += step) _data[index++] = val; } #endregion #region Floats /// <summary> /// Construct a range of floats /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="step"></param> public RangeAttribute(float from, float to, float step) { Guard.ArgumentValid(step > 0.0F && to >= from || step < 0.0F && to <= from, "Step must be positive with to >= from or negative with to <= from", "step"); float aStep = Math.Abs(step); float tol = aStep / 1000; int count = (int)(Math.Abs(to - from) / aStep + tol + 1); _data = new object[count]; int index = 0; for (float val = from; index < count; val += step) _data[index++] = val; } #endregion /// <summary> /// Get the range of values to be used as arguments /// </summary> public IEnumerable GetData(IParameterInfo parameter) { return ParamAttributeTypeConversions.ConvertData(_data, parameter.ParameterType); } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.1 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software (typically granted by licensing Spine), you * may not (a) modify, translate, adapt or otherwise create derivative works, * improvements of the Software or develop new applications using the Software * or (b) remove, delete, alter or obscure any trademarks or any copyright, * trademark, patent or other intellectual property or proprietary rights * notices on or in the Software, including any copy thereof. Redistributions * in binary or source form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.IO; using System.Collections.Generic; #if WINDOWS_STOREAPP using System.Threading.Tasks; using Windows.Storage; #endif namespace Spine { public class SkeletonJson { private AttachmentLoader attachmentLoader; public float Scale { get; set; } public SkeletonJson (Atlas atlas) : this(new AtlasAttachmentLoader(atlas)) { } public SkeletonJson (AttachmentLoader attachmentLoader) { if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader cannot be null."); this.attachmentLoader = attachmentLoader; Scale = 1; } #if WINDOWS_STOREAPP private async Task<SkeletonData> ReadFile(string path) { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false); using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) { SkeletonData skeletonData = ReadSkeletonData(reader); skeletonData.Name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } public SkeletonData ReadSkeletonData (String path) { return this.ReadFile(path).Result; } #else public SkeletonData ReadSkeletonData (String path) { #if WINDOWS_PHONE Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream(path); using (StreamReader reader = new StreamReader(stream)) { #else using (StreamReader reader = new StreamReader(path)) { #endif SkeletonData skeletonData = ReadSkeletonData(reader); skeletonData.name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } #endif public SkeletonData ReadSkeletonData (TextReader reader) { if (reader == null) throw new ArgumentNullException("reader cannot be null."); var skeletonData = new SkeletonData(); var root = Json.Deserialize(reader) as Dictionary<String, Object>; if (root == null) throw new Exception("Invalid JSON."); // Skeleton. if (root.ContainsKey("skeleton")) { var skeletonMap = (Dictionary<String, Object>)root["skeleton"]; skeletonData.hash = (String)skeletonMap["hash"]; skeletonData.version = (String)skeletonMap["spine"]; skeletonData.width = GetFloat(skeletonMap, "width", 0); skeletonData.height = GetFloat(skeletonMap, "height", 0); } // Bones. foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) { BoneData parent = null; if (boneMap.ContainsKey("parent")) { parent = skeletonData.FindBone((String)boneMap["parent"]); if (parent == null) throw new Exception("Parent bone not found: " + boneMap["parent"]); } var boneData = new BoneData((String)boneMap["name"], parent); boneData.length = GetFloat(boneMap, "length", 0) * Scale; boneData.x = GetFloat(boneMap, "x", 0) * Scale; boneData.y = GetFloat(boneMap, "y", 0) * Scale; boneData.rotation = GetFloat(boneMap, "rotation", 0); boneData.scaleX = GetFloat(boneMap, "scaleX", 1); boneData.scaleY = GetFloat(boneMap, "scaleY", 1); boneData.flipX = GetBoolean(boneMap, "flipX", false); boneData.flipY = GetBoolean(boneMap, "flipY", false); boneData.inheritScale = GetBoolean(boneMap, "inheritScale", true); boneData.inheritRotation = GetBoolean(boneMap, "inheritRotation", true); skeletonData.bones.Add(boneData); } // IK constraints. if (root.ContainsKey("ik")) { foreach (Dictionary<String, Object> ikMap in (List<Object>)root["ik"]) { IkConstraintData ikConstraintData = new IkConstraintData((String)ikMap["name"]); foreach (String boneName in (List<Object>)ikMap["bones"]) { BoneData bone = skeletonData.FindBone(boneName); if (bone == null) throw new Exception("IK bone not found: " + boneName); ikConstraintData.bones.Add(bone); } String targetName = (String)ikMap["target"]; ikConstraintData.target = skeletonData.FindBone(targetName); if (ikConstraintData.target == null) throw new Exception("Target bone not found: " + targetName); ikConstraintData.bendDirection = GetBoolean(ikMap, "bendPositive", true) ? 1 : -1; ikConstraintData.mix = GetFloat(ikMap, "mix", 1); skeletonData.ikConstraints.Add(ikConstraintData); } } // Slots. if (root.ContainsKey("slots")) { foreach (Dictionary<String, Object> slotMap in (List<Object>)root["slots"]) { var slotName = (String)slotMap["name"]; var boneName = (String)slotMap["bone"]; BoneData boneData = skeletonData.FindBone(boneName); if (boneData == null) throw new Exception("Slot bone not found: " + boneName); var slotData = new SlotData(slotName, boneData); if (slotMap.ContainsKey("color")) { var color = (String)slotMap["color"]; slotData.r = ToColor(color, 0); slotData.g = ToColor(color, 1); slotData.b = ToColor(color, 2); slotData.a = ToColor(color, 3); } if (slotMap.ContainsKey("attachment")) slotData.attachmentName = (String)slotMap["attachment"]; if (slotMap.ContainsKey("additive")) slotData.additiveBlending = (bool)slotMap["additive"]; skeletonData.slots.Add(slotData); } } // Skins. if (root.ContainsKey("skins")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["skins"]) { var skin = new Skin(entry.Key); foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)entry.Value) { int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key); foreach (KeyValuePair<String, Object> attachmentEntry in ((Dictionary<String, Object>)slotEntry.Value)) { Attachment attachment = ReadAttachment(skin, attachmentEntry.Key, (Dictionary<String, Object>)attachmentEntry.Value); if (attachment != null) skin.AddAttachment(slotIndex, attachmentEntry.Key, attachment); } } skeletonData.skins.Add(skin); if (skin.name == "default") skeletonData.defaultSkin = skin; } } // Events. if (root.ContainsKey("events")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["events"]) { var entryMap = (Dictionary<String, Object>)entry.Value; var eventData = new EventData(entry.Key); eventData.Int = GetInt(entryMap, "int", 0); eventData.Float = GetFloat(entryMap, "float", 0); eventData.String = GetString(entryMap, "string", null); skeletonData.events.Add(eventData); } } // Animations. if (root.ContainsKey("animations")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"]) ReadAnimation(entry.Key, (Dictionary<String, Object>)entry.Value, skeletonData); } skeletonData.bones.TrimExcess(); skeletonData.slots.TrimExcess(); skeletonData.skins.TrimExcess(); skeletonData.animations.TrimExcess(); return skeletonData; } private Attachment ReadAttachment (Skin skin, String name, Dictionary<String, Object> map) { if (map.ContainsKey("name")) name = (String)map["name"]; var type = AttachmentType.region; if (map.ContainsKey("type")) type = (AttachmentType)Enum.Parse(typeof(AttachmentType), (String)map["type"], false); String path = name; if (map.ContainsKey("path")) path = (String)map["path"]; switch (type) { case AttachmentType.region: RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path); if (region == null) return null; region.Path = path; region.x = GetFloat(map, "x", 0) * Scale; region.y = GetFloat(map, "y", 0) * Scale; region.scaleX = GetFloat(map, "scaleX", 1); region.scaleY = GetFloat(map, "scaleY", 1); region.rotation = GetFloat(map, "rotation", 0); region.width = GetFloat(map, "width", 32) * Scale; region.height = GetFloat(map, "height", 32) * Scale; region.UpdateOffset(); if (map.ContainsKey("color")) { var color = (String)map["color"]; region.r = ToColor(color, 0); region.g = ToColor(color, 1); region.b = ToColor(color, 2); region.a = ToColor(color, 3); } return region; case AttachmentType.mesh: { MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; mesh.vertices = GetFloatArray(map, "vertices", Scale); mesh.triangles = GetIntArray(map, "triangles"); mesh.regionUVs = GetFloatArray(map, "uvs", 1); mesh.UpdateUVs(); if (map.ContainsKey("color")) { var color = (String)map["color"]; mesh.r = ToColor(color, 0); mesh.g = ToColor(color, 1); mesh.b = ToColor(color, 2); mesh.a = ToColor(color, 3); } mesh.HullLength = GetInt(map, "hull", 0) * 2; if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges"); mesh.Width = GetInt(map, "width", 0) * Scale; mesh.Height = GetInt(map, "height", 0) * Scale; return mesh; } case AttachmentType.skinnedmesh: { SkinnedMeshAttachment mesh = attachmentLoader.NewSkinnedMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; float[] uvs = GetFloatArray(map, "uvs", 1); float[] vertices = GetFloatArray(map, "vertices", 1); var weights = new List<float>(uvs.Length * 3 * 3); var bones = new List<int>(uvs.Length * 3); float scale = Scale; for (int i = 0, n = vertices.Length; i < n; ) { int boneCount = (int)vertices[i++]; bones.Add(boneCount); for (int nn = i + boneCount * 4; i < nn; ) { bones.Add((int)vertices[i]); weights.Add(vertices[i + 1] * scale); weights.Add(vertices[i + 2] * scale); weights.Add(vertices[i + 3]); i += 4; } } mesh.bones = bones.ToArray(); mesh.weights = weights.ToArray(); mesh.triangles = GetIntArray(map, "triangles"); mesh.regionUVs = uvs; mesh.UpdateUVs(); if (map.ContainsKey("color")) { var color = (String)map["color"]; mesh.r = ToColor(color, 0); mesh.g = ToColor(color, 1); mesh.b = ToColor(color, 2); mesh.a = ToColor(color, 3); } mesh.HullLength = GetInt(map, "hull", 0) * 2; if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges"); mesh.Width = GetInt(map, "width", 0) * Scale; mesh.Height = GetInt(map, "height", 0) * Scale; return mesh; } case AttachmentType.boundingbox: BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name); if (box == null) return null; box.vertices = GetFloatArray(map, "vertices", Scale); return box; } return null; } private float[] GetFloatArray (Dictionary<String, Object> map, String name, float scale) { var list = (List<Object>)map[name]; var values = new float[list.Count]; if (scale == 1) { for (int i = 0, n = list.Count; i < n; i++) values[i] = (float)list[i]; } else { for (int i = 0, n = list.Count; i < n; i++) values[i] = (float)list[i] * scale; } return values; } private int[] GetIntArray (Dictionary<String, Object> map, String name) { var list = (List<Object>)map[name]; var values = new int[list.Count]; for (int i = 0, n = list.Count; i < n; i++) values[i] = (int)(float)list[i]; return values; } private float GetFloat (Dictionary<String, Object> map, String name, float defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (float)map[name]; } private int GetInt (Dictionary<String, Object> map, String name, int defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (int)(float)map[name]; } private bool GetBoolean (Dictionary<String, Object> map, String name, bool defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (bool)map[name]; } private String GetString (Dictionary<String, Object> map, String name, String defaultValue) { if (!map.ContainsKey(name)) return defaultValue; return (String)map[name]; } public static float ToColor (String hexString, int colorIndex) { if (hexString.Length != 8) throw new ArgumentException("Color hexidecimal length must be 8, recieved: " + hexString); return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255; } private void ReadAnimation (String name, Dictionary<String, Object> map, SkeletonData skeletonData) { var timelines = new List<Timeline>(); float duration = 0; float scale = Scale; if (map.ContainsKey("slots")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)map["slots"]) { String slotName = entry.Key; int slotIndex = skeletonData.FindSlotIndex(slotName); var timelineMap = (Dictionary<String, Object>)entry.Value; foreach (KeyValuePair<String, Object> timelineEntry in timelineMap) { var values = (List<Object>)timelineEntry.Value; var timelineName = (String)timelineEntry.Key; if (timelineName == "color") { var timeline = new ColorTimeline(values.Count); timeline.slotIndex = slotIndex; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; String c = (String)valueMap["color"]; timeline.setFrame(frameIndex, time, ToColor(c, 0), ToColor(c, 1), ToColor(c, 2), ToColor(c, 3)); ReadCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount * 5 - 5]); } else if (timelineName == "attachment") { var timeline = new AttachmentTimeline(values.Count); timeline.slotIndex = slotIndex; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; timeline.setFrame(frameIndex++, time, (String)valueMap["name"]); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); } else throw new Exception("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); } } } if (map.ContainsKey("bones")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)map["bones"]) { String boneName = entry.Key; int boneIndex = skeletonData.FindBoneIndex(boneName); if (boneIndex == -1) throw new Exception("Bone not found: " + boneName); var timelineMap = (Dictionary<String, Object>)entry.Value; foreach (KeyValuePair<String, Object> timelineEntry in timelineMap) { var values = (List<Object>)timelineEntry.Value; var timelineName = (String)timelineEntry.Key; if (timelineName == "rotate") { var timeline = new RotateTimeline(values.Count); timeline.boneIndex = boneIndex; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; timeline.SetFrame(frameIndex, time, (float)valueMap["angle"]); ReadCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount * 2 - 2]); } else if (timelineName == "translate" || timelineName == "scale") { TranslateTimeline timeline; float timelineScale = 1; if (timelineName == "scale") timeline = new ScaleTimeline(values.Count); else { timeline = new TranslateTimeline(values.Count); timelineScale = scale; } timeline.boneIndex = boneIndex; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; float x = valueMap.ContainsKey("x") ? (float)valueMap["x"] : 0; float y = valueMap.ContainsKey("y") ? (float)valueMap["y"] : 0; timeline.SetFrame(frameIndex, time, (float)x * timelineScale, (float)y * timelineScale); ReadCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount * 3 - 3]); } else if (timelineName == "flipX" || timelineName == "flipY") { bool x = timelineName == "flipX"; var timeline = x ? new FlipXTimeline(values.Count) : new FlipYTimeline(values.Count); timeline.boneIndex = boneIndex; String field = x ? "x" : "y"; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; timeline.SetFrame(frameIndex, time, valueMap.ContainsKey(field) ? (bool)valueMap[field] : false); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount * 2 - 2]); } else throw new Exception("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); } } } if (map.ContainsKey("ik")) { foreach (KeyValuePair<String, Object> ikMap in (Dictionary<String, Object>)map["ik"]) { IkConstraintData ikConstraint = skeletonData.FindIkConstraint(ikMap.Key); var values = (List<Object>)ikMap.Value; var timeline = new IkConstraintTimeline(values.Count); timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(ikConstraint); int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float time = (float)valueMap["time"]; float mix = valueMap.ContainsKey("mix") ? (float)valueMap["mix"] : 1; bool bendPositive = valueMap.ContainsKey("bendPositive") ? (bool)valueMap["bendPositive"] : true; timeline.setFrame(frameIndex, time, mix, bendPositive ? 1 : -1); ReadCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount * 3 - 3]); } } if (map.ContainsKey("ffd")) { foreach (KeyValuePair<String, Object> ffdMap in (Dictionary<String, Object>)map["ffd"]) { Skin skin = skeletonData.FindSkin(ffdMap.Key); foreach (KeyValuePair<String, Object> slotMap in (Dictionary<String, Object>)ffdMap.Value) { int slotIndex = skeletonData.FindSlotIndex(slotMap.Key); foreach (KeyValuePair<String, Object> meshMap in (Dictionary<String, Object>)slotMap.Value) { var values = (List<Object>)meshMap.Value; var timeline = new FFDTimeline(values.Count); Attachment attachment = skin.GetAttachment(slotIndex, meshMap.Key); if (attachment == null) throw new Exception("FFD attachment not found: " + meshMap.Key); timeline.slotIndex = slotIndex; timeline.attachment = attachment; int vertexCount; if (attachment is MeshAttachment) vertexCount = ((MeshAttachment)attachment).vertices.Length; else vertexCount = ((SkinnedMeshAttachment)attachment).Weights.Length / 3 * 2; int frameIndex = 0; foreach (Dictionary<String, Object> valueMap in values) { float[] vertices; if (!valueMap.ContainsKey("vertices")) { if (attachment is MeshAttachment) vertices = ((MeshAttachment)attachment).vertices; else vertices = new float[vertexCount]; } else { var verticesValue = (List<Object>)valueMap["vertices"]; vertices = new float[vertexCount]; int start = GetInt(valueMap, "offset", 0); if (scale == 1) { for (int i = 0, n = verticesValue.Count; i < n; i++) vertices[i + start] = (float)verticesValue[i]; } else { for (int i = 0, n = verticesValue.Count; i < n; i++) vertices[i + start] = (float)verticesValue[i] * scale; } if (attachment is MeshAttachment) { float[] meshVertices = ((MeshAttachment)attachment).vertices; for (int i = 0; i < vertexCount; i++) vertices[i] += meshVertices[i]; } } timeline.setFrame(frameIndex, (float)valueMap["time"], vertices); ReadCurve(timeline, frameIndex, valueMap); frameIndex++; } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); } } } } if (map.ContainsKey("drawOrder") || map.ContainsKey("draworder")) { var values = (List<Object>)map[map.ContainsKey("drawOrder") ? "drawOrder" : "draworder"]; var timeline = new DrawOrderTimeline(values.Count); int slotCount = skeletonData.slots.Count; int frameIndex = 0; foreach (Dictionary<String, Object> drawOrderMap in values) { int[] drawOrder = null; if (drawOrderMap.ContainsKey("offsets")) { drawOrder = new int[slotCount]; for (int i = slotCount - 1; i >= 0; i--) drawOrder[i] = -1; var offsets = (List<Object>)drawOrderMap["offsets"]; int[] unchanged = new int[slotCount - offsets.Count]; int originalIndex = 0, unchangedIndex = 0; foreach (Dictionary<String, Object> offsetMap in offsets) { int slotIndex = skeletonData.FindSlotIndex((String)offsetMap["slot"]); if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]); // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; // Set changed items. drawOrder[originalIndex + (int)(float)offsetMap["offset"]] = originalIndex++; } // Collect remaining unchanged items. while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; // Fill in unchanged items. for (int i = slotCount - 1; i >= 0; i--) if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex]; } timeline.setFrame(frameIndex++, (float)drawOrderMap["time"], drawOrder); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); } if (map.ContainsKey("events")) { var eventsMap = (List<Object>)map["events"]; var timeline = new EventTimeline(eventsMap.Count); int frameIndex = 0; foreach (Dictionary<String, Object> eventMap in eventsMap) { EventData eventData = skeletonData.FindEvent((String)eventMap["name"]); if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]); var e = new Event(eventData); e.Int = GetInt(eventMap, "int", eventData.Int); e.Float = GetFloat(eventMap, "float", eventData.Float); e.String = GetString(eventMap, "string", eventData.String); timeline.setFrame(frameIndex++, (float)eventMap["time"], e); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); } timelines.TrimExcess(); skeletonData.animations.Add(new Animation(name, timelines, duration)); } private void ReadCurve (CurveTimeline timeline, int frameIndex, Dictionary<String, Object> valueMap) { if (!valueMap.ContainsKey("curve")) return; Object curveObject = valueMap["curve"]; if (curveObject.Equals("stepped")) timeline.SetStepped(frameIndex); else if (curveObject is List<Object>) { var curve = (List<Object>)curveObject; timeline.SetCurve(frameIndex, (float)curve[0], (float)curve[1], (float)curve[2], (float)curve[3]); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// </summary> public partial class Solution { // SolutionState that doesn't hold onto Project/Document private readonly SolutionState _state; // Values for all these are created on demand. private ImmutableHashMap<ProjectId, Project> _projectIdToProjectMap; private Solution(SolutionState state) { _projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty; _state = state; } internal Solution(Workspace workspace, SolutionInfo info) : this(new SolutionState(workspace, info)) { } internal SolutionState State => _state; internal int WorkspaceVersion => _state.WorkspaceVersion; internal SolutionServices Services => _state.Services; internal BranchId BranchId => _state.BranchId; internal ProjectState GetProjectState(ProjectId projectId) => _state.GetProjectState(projectId); /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _state.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _state.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string FilePath => _state.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _state.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds => _state.ProjectIds; /// <summary> /// A list of all the projects contained by the solution. /// </summary> public IEnumerable<Project> Projects => ProjectIds.Select(id => GetProject(id)); /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() => _state.GetLatestProjectVersion(); /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject(ProjectId projectId) => _state.ContainsProject(projectId); /// <summary> /// Gets the project in this solution with the specified project ID. /// /// If the id is not an id of a project that is part of this solution the method returns null. /// </summary> public Project GetProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (this.ContainsProject(projectId)) { return ImmutableHashMapExtensions.GetOrAdd(ref _projectIdToProjectMap, projectId, s_createProjectFunction, this); } return null; } private static readonly Func<ProjectId, Solution, Project> s_createProjectFunction = CreateProject; private static Project CreateProject(ProjectId projectId, Solution solution) { return new Project(solution, solution.State.GetProjectState(projectId)); } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public Project GetProject(IAssemblySymbol assemblySymbol, CancellationToken cancellationToken = default(CancellationToken)) { var projectState = _state.GetProjectState(assemblySymbol, cancellationToken); return projectState == null ? null : GetProject(projectState.Id); } /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument(DocumentId documentId) => _state.ContainsDocument(documentId); /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument(DocumentId documentId) => _state.ContainsAdditionalDocument(documentId); /// <summary> /// Gets the documentId in this solution with the specified syntax tree. /// </summary> public DocumentId GetDocumentId(SyntaxTree syntaxTree) => GetDocumentId(syntaxTree, projectId: null); /// <summary> /// Gets the documentId in this solution with the specified syntax tree. /// </summary> public DocumentId GetDocumentId(SyntaxTree syntaxTree, ProjectId projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? if (this.ContainsDocument(documentId)) { return documentId; } } } return null; } /// <summary> /// Gets the document in this solution with the specified document ID. /// </summary> public Document GetDocument(DocumentId documentId) { if (documentId != null && this.ContainsDocument(documentId)) { return this.GetProject(documentId.ProjectId).GetDocument(documentId); } return null; } /// <summary> /// Gets the additional document in this solution with the specified document ID. /// </summary> public TextDocument GetAdditionalDocument(DocumentId documentId) { if (documentId != null && this.ContainsAdditionalDocument(documentId)) { return this.GetProject(documentId.ProjectId).GetAdditionalDocument(documentId); } return null; } /// <summary> /// Gets the document in this solution with the specified syntax tree. /// </summary> public Document GetDocument(SyntaxTree syntaxTree) { return this.GetDocument(syntaxTree, projectId: null); } internal Document GetDocument(SyntaxTree syntaxTree, ProjectId projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var docId = DocumentState.GetDocumentIdForTree(syntaxTree); if (docId != null && (projectId == null || docId.ProjectId == projectId)) { // does this solution even have the document? var document = this.GetDocument(docId); if (document != null) { // does this document really have the syntax tree? SyntaxTree documentTree; if (document.TryGetSyntaxTree(out documentTree) && documentTree == syntaxTree) { return document; } } } } return null; } /// <summary> /// Creates a new solution instance that includes a project with the specified language and names. /// Returns the new project. /// </summary> public Project AddProject(string name, string assemblyName, string language) { var id = ProjectId.CreateNewId(debugName: name); return this.AddProject(id, name, assemblyName, language).GetProject(id); } /// <summary> /// Creates a new solution instance that includes a project with the specified language and names. /// </summary> public Solution AddProject(ProjectId projectId, string name, string assemblyName, string language) { return this.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), name, assemblyName, language)); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public Solution AddProject(ProjectInfo projectInfo) { var newState = _state.AddProject(projectInfo); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance without the project specified. /// </summary> public Solution RemoveProject(ProjectId projectId) { var newState = _state.RemoveProject(projectId); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public Solution WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var newState = _state.WithProjectAssemblyName(projectId, assemblyName); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public Solution WithProjectOutputFilePath(ProjectId projectId, string outputFilePath) { var newState = _state.WithProjectOutputFilePath(projectId, outputFilePath); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public Solution WithProjectName(ProjectId projectId, string name) { var newState = _state.WithProjectName(projectId, name); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public Solution WithProjectFilePath(ProjectId projectId, string filePath) { var newState = _state.WithProjectFilePath(projectId, filePath); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public Solution WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var newState = _state.WithProjectCompilationOptions(projectId, options); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public Solution WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var newState = _state.WithProjectParseOptions(projectId, options); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> // TODO: make it public internal Solution WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var newState = _state.WithHasAllInformation(projectId, hasAllInformation); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project reference. /// </summary> public Solution AddProjectReference(ProjectId projectId, ProjectReference projectReference) { var newState = _state.AddProjectReference(projectId, projectReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public Solution AddProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences) { var newState = _state.AddProjectReferences(projectId, projectReferences); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public Solution RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var newState = _state.RemoveProjectReference(projectId, projectReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public Solution WithProjectReferences(ProjectId projectId, IEnumerable<ProjectReference> projectReferences) { var newState = _state.WithProjectReferences(projectId, projectReferences); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata reference. /// </summary> public Solution AddMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var newState = _state.AddMetadataReference(projectId, metadataReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public Solution AddMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences) { var newState = _state.AddMetadataReferences(projectId, metadataReferences); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public Solution RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var newState = _state.RemoveMetadataReference(projectId, metadataReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public Solution WithProjectMetadataReferences(ProjectId projectId, IEnumerable<MetadataReference> metadataReferences) { var newState = _state.WithProjectMetadataReferences(projectId, metadataReferences); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer reference. /// </summary> public Solution AddAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var newState = _state.AddAnalyzerReference(projectId, analyzerReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public Solution AddAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var newState = _state.AddAnalyzerReferences(projectId, analyzerReferences); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public Solution RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var newState = _state.RemoveAnalyzerReference(projectId, analyzerReference); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public Solution WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var newState = _state.WithProjectAnalyzerReferences(projectId, analyzerReferences); if (newState == _state) { return this; } return new Solution(newState); } private static SourceCodeKind GetSourceCodeKind(ProjectState project) { return project.ParseOptions != null ? project.ParseOptions.Kind : SourceCodeKind.Regular; } /// <summary> /// Creates a new solution instance with the corresponding project updated to include a new /// document instance defined by its name and text. /// </summary> public Solution AddDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null) { return this.AddDocument(documentId, name, SourceText.From(text), folders, filePath); } /// <summary> /// Creates a new solution instance with the corresponding project updated to include a new /// document instance defined by its name and text. /// </summary> public Solution AddDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } var project = _state.GetProjectState(documentId.ProjectId); var version = VersionStamp.Create(); var loader = TextLoader.From(TextAndVersion.Create(text, version, name)); var info = DocumentInfo.Create( documentId, name: name, folders: folders, sourceCodeKind: GetSourceCodeKind(project), loader: loader, filePath: filePath, isGenerated: isGenerated); return this.AddDocument(info); } /// <summary> /// Creates a new solution instance with the corresponding project updated to include a new /// document instance defined by its name and root <see cref="SyntaxNode"/>. /// </summary> public Solution AddDocument(DocumentId documentId, string name, SyntaxNode syntaxRoot, IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false, PreservationMode preservationMode = PreservationMode.PreserveValue) { return this.AddDocument(documentId, name, SourceText.From(string.Empty), folders, filePath, isGenerated).WithDocumentSyntaxRoot(documentId, syntaxRoot, preservationMode); } /// <summary> /// Creates a new solution instance with the project updated to include a new document with /// the arguments specified. /// </summary> public Solution AddDocument(DocumentId documentId, string name, TextLoader loader, IEnumerable<string> folders = null) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (loader == null) { throw new ArgumentNullException(nameof(loader)); } var project = _state.GetProjectState(documentId.ProjectId); var info = DocumentInfo.Create( documentId, name: name, folders: folders, sourceCodeKind: GetSourceCodeKind(project), loader: loader); return this.AddDocument(info); } /// <summary> /// Create a new solution instance with the corresponding project updated to include a new /// document instanced defined by the document info. /// </summary> public Solution AddDocument(DocumentInfo documentInfo) { var newState = _state.AddDocument(documentInfo); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the corresponding project updated to include a new /// additional document instance defined by its name and text. /// </summary> public Solution AddAdditionalDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders = null, string filePath = null) { return this.AddAdditionalDocument(documentId, name, SourceText.From(text), folders, filePath); } /// <summary> /// Creates a new solution instance with the corresponding project updated to include a new /// additional document instance defined by its name and text. /// </summary> public Solution AddAdditionalDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string> folders = null, string filePath = null) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } var project = _state.GetProjectState(documentId.ProjectId); var version = VersionStamp.Create(); var loader = TextLoader.From(TextAndVersion.Create(text, version, name)); var info = DocumentInfo.Create( documentId, name: name, folders: folders, sourceCodeKind: GetSourceCodeKind(project), loader: loader, filePath: filePath); return this.AddAdditionalDocument(info); } public Solution AddAdditionalDocument(DocumentInfo documentInfo) { var newState = _state.AddAdditionalDocument(documentInfo); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public Solution RemoveDocument(DocumentId documentId) { var newState = _state.RemoveDocument(documentId); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance that no longer includes the specified additional document. /// </summary> public Solution RemoveAdditionalDocument(DocumentId documentId) { var newState = _state.RemoveAdditionalDocument(documentId); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public Solution WithDocumentFolders(DocumentId documentId, IEnumerable<string> folders) { var newState = _state.WithDocumentFolders(documentId, folders); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public Solution WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithDocumentText(documentId, text, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public Solution WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithAdditionalDocumentText(documentId, text, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public Solution WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithDocumentText(documentId, textAndVersion, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public Solution WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithAdditionalDocumentText(documentId, textAndVersion, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public Solution WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithDocumentSyntaxRoot(documentId, root, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public Solution WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var newState = _state.WithDocumentSourceCodeKind(documentId, sourceCodeKind); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// supplied by the text loader. /// </summary> public Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { return WithDocumentTextLoader(documentId, loader, textOpt: null, mode: mode); } internal Solution WithDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText textOpt, PreservationMode mode) { var newState = _state.WithDocumentTextLoader(documentId, loader, textOpt, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public Solution WithAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var newState = _state.WithAdditionalDocumentTextLoader(documentId, loader, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> internal async Task<Solution> WithFrozenPartialCompilationIncludingSpecificDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { var newState = await _state.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); return new Solution(newState); } internal async Task<Solution> WithMergedLinkedFileChangesAsync( Solution oldSolution, SolutionChanges? solutionChanges = null, IMergeConflictHandler mergeConflictHandler = null, CancellationToken cancellationToken = default(CancellationToken)) { // we only log sessioninfo for actual changes committed to workspace which should exclude ones from preview var session = new LinkedFileDiffMergingSession(oldSolution, this, solutionChanges ?? this.GetChanges(oldSolution), logSessionInfo: solutionChanges != null); return (await session.MergeDiffsAsync(mergeConflictHandler, cancellationToken).ConfigureAwait(false)).MergedSolution; } internal ImmutableArray<DocumentId> GetRelatedDocumentIds(DocumentId documentId) { var projectState = _state.GetProjectState(documentId.ProjectId); if (projectState == null) { // this document no longer exist return ImmutableArray<DocumentId>.Empty; } var documentState = projectState.GetDocumentState(documentId); if (documentState == null) { // this document no longer exist return ImmutableArray<DocumentId>.Empty; } var filePath = documentState.FilePath; if (string.IsNullOrEmpty(filePath)) { // this document can't have any related document. only related document is itself. return ImmutableArray.Create<DocumentId>(documentId); } var documentIds = this.GetDocumentIdsWithFilePath(filePath); return this.FilterDocumentIdsByLanguage(documentIds, projectState.ProjectInfo.Language).ToImmutableArray(); } internal Solution WithNewWorkspace(Workspace workspace, int workspaceVersion) { var newState = _state.WithNewWorkspace(workspace, workspaceVersion); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Gets a copy of the solution isolated from the original so that they do not share computed state. /// /// Use isolated solutions when doing operations that are likely to access a lot of text, /// syntax trees or compilations that are unlikely to be needed again after the operation is done. /// When the isolated solution is reclaimed so will the computed state. /// </summary> public Solution GetIsolatedSolution() { var newState = _state.GetIsolatedSolution(); return new Solution(newState); } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public Solution WithDocumentText(IEnumerable<DocumentId> documentIds, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var newState = _state.WithDocumentText(documentIds, text, mode); if (newState == _state) { return this; } return new Solution(newState); } /// <summary> /// Gets an objects that lists the added, changed and removed projects between /// this solution and the specified solution. /// </summary> public SolutionChanges GetChanges(Solution oldSolution) { if (oldSolution == null) { throw new ArgumentNullException(nameof(oldSolution)); } return new SolutionChanges(this, oldSolution); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string filePath) => _state.GetDocumentIdsWithFilePath(filePath); /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _state.GetProjectDependencyGraph(); /// <summary> /// Returns the options that should be applied to this solution. This is equivalent to <see cref="Workspace.Options" /> when the <see cref="Solution"/> /// instance was created. /// </summary> public OptionSet Options { get { // TODO: actually make this a snapshot return this.Workspace.Options; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; namespace Microsoft.Azure.Insights.Models { /// <summary> /// A log value set represents a set of log values in a time period. /// </summary> public partial class LogValue { private string _callerIpAddress; /// <summary> /// Optional. Gets or sets the caller IP address. /// </summary> public string CallerIpAddress { get { return this._callerIpAddress; } set { this._callerIpAddress = value; } } private string _category; /// <summary> /// Optional. Gets or sets the category of the log. /// </summary> public string Category { get { return this._category; } set { this._category = value; } } private string _correlationId; /// <summary> /// Optional. Gets or sets the correlation id of the log. Used to /// group together a set of related log. /// </summary> public string CorrelationId { get { return this._correlationId; } set { this._correlationId = value; } } private int _durationMs; /// <summary> /// Optional. Gets or sets the duration of the operation in /// milliseconds. /// </summary> public int DurationMs { get { return this._durationMs; } set { this._durationMs = value; } } private string _identity; /// <summary> /// Optional. Gets or sets the identity that generated the event. /// </summary> public string Identity { get { return this._identity; } set { this._identity = value; } } private string _level; /// <summary> /// Optional. Gets or sets the level /// (Informational/Warning/Error/Critical) of the event. /// </summary> public string Level { get { return this._level; } set { this._level = value; } } private string _location; /// <summary> /// Optional. Gets or sets tThe location of the resource emitting the /// event. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private string _operationName; /// <summary> /// Optional. Gets or sets the name of the operation. /// </summary> public string OperationName { get { return this._operationName; } set { this._operationName = value; } } private string _operationVersion; /// <summary> /// Optional. Gets or sets the version of the operation. /// </summary> public string OperationVersion { get { return this._operationVersion; } set { this._operationVersion = value; } } private IDictionary<string, string> _properties; /// <summary> /// Optional. Gets or sets the collection of extended properties. /// </summary> public IDictionary<string, string> Properties { get { return this._properties; } set { this._properties = value; } } private string _resourceId; /// <summary> /// Optional. Gets or sets id of the reosurce related to the log. /// </summary> public string ResourceId { get { return this._resourceId; } set { this._resourceId = value; } } private string _resultDescription; /// <summary> /// Optional. Gets or sets the substatus of the operation. /// </summary> public string ResultDescription { get { return this._resultDescription; } set { this._resultDescription = value; } } private string _resultSignature; /// <summary> /// Optional. Gets or sets the substatus of the operation. /// </summary> public string ResultSignature { get { return this._resultSignature; } set { this._resultSignature = value; } } private string _resultType; /// <summary> /// Optional. Gets or sets the status of the operation. /// </summary> public string ResultType { get { return this._resultType; } set { this._resultType = value; } } private DateTime _time; /// <summary> /// Optional. Gets or sets the time when the log was generated /// </summary> public DateTime Time { get { return this._time; } set { this._time = value; } } /// <summary> /// Initializes a new instance of the LogValue class. /// </summary> public LogValue() { this.Properties = new LazyDictionary<string, string>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSingle() { var test = new SimpleBinaryOpTest__AddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddSingle testClass) { var result = Sse.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.Add( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__AddSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.Add( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.Add( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.Add( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.Add( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddSingle(); var result = Sse.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.Add( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.Add( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.Add( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.Add)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); private IDictionary<OptionKey, object> AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithNoneEnforcement)); internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, int index = 0, bool ignoreTrivia = true, IDictionary<OptionKey, object> options = null) { options = options ?? new Dictionary<OptionKey, object>(); foreach (var kvp in AllOptionsOff) { options.Add(kvp); } return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, index: index, ignoreTrivia: ignoreTrivia, options: options); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestSimpleMethods() { await TestAllOptionsOffAsync( @"abstract class Foo { protected abstract string FooMethod(); public abstract void Blah(); } abstract class Bar : Foo { public abstract bool BarMethod(); public override void Blah() { } } class [|Program|] : Foo { static void Main(string[] args) { } }", @"abstract class Foo { protected abstract string FooMethod(); public abstract void Blah(); } abstract class Bar : Foo { public abstract bool BarMethod(); public override void Blah() { } } class Program : Foo { static void Main(string[] args) { } public override void Blah() { throw new System.NotImplementedException(); } protected override string FooMethod() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [WorkItem(16434, "https://github.com/dotnet/roslyn/issues/16434")] public async Task TestMethodWithTupleNames() { await TestAllOptionsOffAsync( @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class [|Program|] : Base { }", @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class Program : Base { protected override (int a, int b) Method((string, string d) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(543234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNotAvailableForStruct() { await TestMissingInRegularAndScriptAsync( @"abstract class Foo { public abstract void Bar(); } struct [|Program|] : Foo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(int x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(int x = 3); } class b : d { public override void foo(int x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalCharParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(char x = 'a'); } class [|b|] : d { }", @"abstract class d { public abstract void foo(char x = 'a'); } class b : d { public override void foo(char x = 'a') { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStringParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(string x = ""x""); } class [|b|] : d { }", @"abstract class d { public abstract void foo(string x = ""x""); } class b : d { public override void foo(string x = ""x"") { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalShortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(short x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(short x = 3); } class b : d { public override void foo(short x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDecimalParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(decimal x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(decimal x = 3); } class b : d { public override void foo(decimal x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDoubleParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(double x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(double x = 3); } class b : d { public override void foo(double x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalLongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(long x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(long x = 3); } class b : d { public override void foo(long x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalFloatParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(float x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(float x = 3); } class b : d { public override void foo(float x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUshortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(ushort x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(ushort x = 3); } class b : d { public override void foo(ushort x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUintParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(uint x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(uint x = 3); } class b : d { public override void foo(uint x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUlongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void foo(ulong x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void foo(ulong x = 3); } class b : d { public override void foo(ulong x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void foo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void foo(b x = new b()); } class c : d { public override void foo(b x = default(b)) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class c : d { public override void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class [|c|] : d { }", @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class c : d { public override void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalObjectParameter() { await TestAllOptionsOffAsync( @"class b { } abstract class d { public abstract void foo(b x = null); } class [|c|] : d { }", @"class b { } abstract class d { public abstract void foo(b x = null); } class c : d { public override void foo(b x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(543883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543883")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestDifferentAccessorAccessibility() { await TestAllOptionsOffAsync( @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class [|c2|] : c1 { }", @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class c2 : c1 { public override c1 this[c1 x] { get { throw new System.NotImplementedException(); } internal set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestEvent1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract event Action E; } class [|D|] : C { }", @"using System; abstract class C { public abstract event Action E; } class D : C { public override event Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestIndexer1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class [|D|] : C { }", @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class D : C { public override int this[string s] { get { throw new NotImplementedException(); } internal set { throw new NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestMissingInHiddenType() { await TestMissingInRegularAndScriptAsync( @"using System; abstract class Foo { public abstract void F(); } class [|Program|] : Foo { #line hidden } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIntoNonHiddenPart() { await TestAllOptionsOffAsync( @"using System; abstract class Foo { public abstract void F(); } partial class [|Program|] : Foo { #line hidden } #line default partial class Program ", @"using System; abstract class Foo { public abstract void F(); } partial class Program : Foo { #line hidden } #line default partial class Program { public override void F() { throw new NotImplementedException(); } } ", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIfLocationAvailable() { await TestAllOptionsOffAsync( @"#line default using System; abstract class Foo { public abstract void F(); } partial class [|Program|] : Foo { void Bar() { } #line hidden } #line default", @"#line default using System; abstract class Foo { public abstract void F(); } partial class Program : Foo { public override void F() { throw new NotImplementedException(); } void Bar() { } #line hidden } #line default", ignoreTrivia: false); } [WorkItem(545585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545585")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOnlyGenerateUnimplementedAccessors() { await TestAllOptionsOffAsync( @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class [|C|] : B { }", @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class C : B { public override int X { set { throw new NotImplementedException(); } } }"); } [WorkItem(545615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestParamsArray() { await TestAllOptionsOffAsync( @"class A { public virtual void Foo(int x, params int[] y) { } } abstract class B : A { public abstract override void Foo(int x, int[] y = null); } class [|C|] : B { }", @"class A { public virtual void Foo(int x, params int[] y) { } } abstract class B : A { public abstract override void Foo(int x, int[] y = null); } class C : B { public override void Foo(int x, params int[] y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545636")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullPointerType() { await TestAllOptionsOffAsync( @"abstract class C { unsafe public abstract void Foo(int* x = null); } class [|D|] : C { }", @"abstract class C { unsafe public abstract void Foo(int* x = null); } class D : C { public override unsafe void Foo(int* x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545637")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestErrorTypeCalledVar() { await TestAllOptionsOffAsync( @"extern alias var; abstract class C { public abstract void Foo(var::X x); } class [|D|] : C { }", @"extern alias var; abstract class C { public abstract void Foo(var::X x); } class D : C { public override void Foo(X x) { throw new System.NotImplementedException(); } }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_581500() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<T> { } } }", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<T> { public override void M(B.T x) { throw new System.NotImplementedException(); } } } }"); } [WorkItem(625442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625442")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_625442() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<B.T> { } } } ", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<B.T> { public override void M(A<A<T>.B>.B.T x) { throw new System.NotImplementedException(); } } } } ", ignoreTrivia: false); } [WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task ImplementClassWithInaccessibleMembers() { await TestAllOptionsOffAsync( @"using System; using System.Globalization; public class [|x|] : EastAsianLunisolarCalendar { }", @"using System; using System.Globalization; public class x : EastAsianLunisolarCalendar { public override int[] Eras { get { throw new NotImplementedException(); } } internal override int MinCalendarYear { get { throw new NotImplementedException(); } } internal override int MaxCalendarYear { get { throw new NotImplementedException(); } } internal override EraInfo[] CalEraInfo { get { throw new NotImplementedException(); } } internal override DateTime MinDate { get { throw new NotImplementedException(); } } internal override DateTime MaxDate { get { throw new NotImplementedException(); } } public override int GetEra(DateTime time) { throw new NotImplementedException(); } internal override int GetGregorianYear(int year, int era) { throw new NotImplementedException(); } internal override int GetYear(int year, DateTime time) { throw new NotImplementedException(); } internal override int GetYearInfo(int LunarYear, int Index) { throw new NotImplementedException(); } }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass1() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] : Base { } partial class A { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A : Base { public override void Dispose() { throw new NotImplementedException(); } } partial class A { }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass2() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] { } partial class A : Base { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A { public override void Dispose() { throw new NotImplementedException(); } } partial class A : Base { }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Method1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract void M(int x); } class [|T|] : A { }", @"abstract class A { public abstract void M(int x); } class T : A { public override void M(int x) => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexers1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; } } class T : A { public override int this[int i] => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { set; } } class T : A { public override int this[int i] { set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; set; } } class T : A { public override int this[int i] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M { get => throw new System.NotImplementedException(); } }", options: OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption.None), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption.None))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithGroupingOff1() { await TestInRegularAndScriptAsync( @"abstract class Base { public abstract int Prop { get; } } class [|Derived|] : Base { void Foo() { } }", @"abstract class Base { public abstract int Prop { get; } } class Derived : Base { void Foo() { } public override int Prop => throw new System.NotImplementedException(); }", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd)); } [WorkItem(17274, "https://github.com/dotnet/roslyn/issues/17274")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAddedUsingWithBanner1() { await TestInRegularAndScriptAsync( @"// Copyright ... using Microsoft.Win32; namespace My { public abstract class Foo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class [|Foo2|] : Foo // Implement Abstract Class { } }", @"// Copyright ... using System.Collections.Generic; using Microsoft.Win32; namespace My { public abstract class Foo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class Foo2 : Foo // Implement Abstract Class { public override void Bar(List<object> values) { throw new System.NotImplementedException(); } } }", ignoreTrivia: false); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")] [WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAutoProperties() { await TestInRegularAndScript1Async( @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class [|C|] : AbstractClass { }", @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class C : AbstractClass { public override int ReadOnlyProp { get; } public override int ReadWriteProp { get; set; } public override int WriteOnlyProp { set => throw new System.NotImplementedException(); } }", parameters: new TestParameters(options: Option( ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties))); } } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.IO; using System.Net; using System.Xml; using System.Web; using System.Text; using System.Drawing; using System.Diagnostics; using System.Collections.Generic; namespace MSNPSharp { using MSNPSharp.Core; using MSNPSharp.P2P; using MSNPSharp.Apps; partial class NSMessageHandler { #region Public Events /// <summary> /// Occurs when any contact changes status. /// </summary> public event EventHandler<ContactStatusChangedEventArgs> ContactStatusChanged; protected internal virtual void OnContactStatusChanged(ContactStatusChangedEventArgs e) { if (ContactStatusChanged != null) ContactStatusChanged(this, e); } /// <summary> /// Occurs when any contact goes from offline status to another status. /// </summary> public event EventHandler<ContactStatusChangedEventArgs> ContactOnline; protected internal virtual void OnContactOffline(ContactStatusChangedEventArgs e) { if (ContactOffline != null) ContactOffline(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, e.Contact.ToString() + " goes to " + e.NewStatus + " from " + e.OldStatus + (e.Via == null ? String.Empty : " via=" + e.Via.ToString()) + "\r\n", GetType().Name); } /// <summary> /// Occurs when any contact goes from any status to offline status. /// </summary> public event EventHandler<ContactStatusChangedEventArgs> ContactOffline; protected internal virtual void OnContactOnline(ContactStatusChangedEventArgs e) { if (ContactOnline != null) ContactOnline(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, e.Contact.ToString() + " goes to " + e.NewStatus + " from " + e.OldStatus + (e.Via == null ? String.Empty : " via=" + e.Via.ToString()) + "\r\n", GetType().Name); } /// <summary> /// Occurs when a user is typing. /// </summary> public event EventHandler<TypingArrivedEventArgs> TypingMessageReceived; protected virtual void OnTypingMessageReceived(TypingArrivedEventArgs e) { if (TypingMessageReceived != null) TypingMessageReceived(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "TYPING: " + e.OriginalSender.ToString() + (e.Sender == e.OriginalSender ? String.Empty : ";by=" + e.Sender.ToString())); } /// <summary> /// Occurs when we receive a nudge message by a user. /// </summary> public event EventHandler<NudgeArrivedEventArgs> NudgeReceived; protected virtual void OnNudgeReceived(NudgeArrivedEventArgs e) { if (NudgeReceived != null) NudgeReceived(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "NUDGE: " + e.OriginalSender + (e.Sender == e.OriginalSender ? String.Empty : ";by=" + e.Sender.ToString())); } /// <summary> /// Occurs when we receive a text message from a user. /// </summary> public event EventHandler<TextMessageArrivedEventArgs> TextMessageReceived; protected virtual void OnTextMessageReceived(TextMessageArrivedEventArgs e) { if (TextMessageReceived != null) TextMessageReceived(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "TEXT MESSAGE: " + e.OriginalSender.ToString() + (e.Sender == e.OriginalSender ? String.Empty : ";by=" + e.Sender.ToString()) + "\r\n" + e.TextMessage.ToDebugString()); } /// <summary> /// Fired when a contact sends a emoticon definition. /// </summary> public event EventHandler<EmoticonDefinitionEventArgs> EmoticonDefinitionReceived; protected virtual void OnEmoticonDefinitionReceived(EmoticonDefinitionEventArgs e) { if (EmoticonDefinitionReceived != null) EmoticonDefinitionReceived(this, e); } /// <summary> /// Fired when a contact sends a wink definition. /// </summary> public event EventHandler<WinkEventArgs> WinkDefinitionReceived; protected virtual void OnWinkDefinitionReceived(WinkEventArgs e) { if (WinkDefinitionReceived != null) WinkDefinitionReceived(this, e); } /// <summary> /// Occurs when a multiparty chat created remotely. Owner is joined automatically by the library. /// </summary> public event EventHandler<MultipartyCreatedEventArgs> MultipartyCreatedRemotely; protected virtual void OnMultipartyCreatedRemotely(MultipartyCreatedEventArgs e) { if (MultipartyCreatedRemotely != null) MultipartyCreatedRemotely(this, e); } /// <summary> /// Occurs when a contact joined the group chat. /// </summary> public event EventHandler<GroupChatParticipationEventArgs> JoinedGroupChat; protected virtual void OnJoinedGroupChat(GroupChatParticipationEventArgs e) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, e.Contact + " joined group chat " + e.Via.ToString(), GetType().Name); if (JoinedGroupChat != null) JoinedGroupChat(this, e); } /// <summary> /// Occurs when a contact left the group chat. /// </summary> public event EventHandler<GroupChatParticipationEventArgs> LeftGroupChat; protected virtual void OnLeftGroupChat(GroupChatParticipationEventArgs e) { if (LeftGroupChat != null) LeftGroupChat(this, e); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, e.Contact + " left group chat " + e.Via.ToString(), GetType().Name); } /// <summary> /// Occurs after the user on another end point closed the IM window. /// </summary> public event EventHandler<CloseIMWindowEventArgs> RemoteEndPointCloseIMWindow; protected virtual void OnRemoteEndPointCloseIMWindow(CloseIMWindowEventArgs e) { if (RemoteEndPointCloseIMWindow != null) RemoteEndPointCloseIMWindow(this, e); if (e.Sender != null && e.SenderEndPoint != null) { string partiesString = string.Empty; foreach (Contact party in e.Parties) { partiesString += party.ToString() + "\r\n"; } Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "User at End Point: " + e.SenderEndPoint.ToString() + " has closed the IM window.\r\n" + "Parties in the conversation: \r\n" + partiesString); } } #endregion #region MULTIPARTY #region CreateMultiparty internal class MultipartyObject { public event EventHandler<MultipartyCreatedEventArgs> MultipartyCreatedLocally; public int TransactionID; public List<string> InviteQueueHash; public Contact MultiParty; public MultipartyObject(int transId, List<string> inviteQueueHash, Contact multiParty, EventHandler<MultipartyCreatedEventArgs> onCreated) { TransactionID = transId; InviteQueueHash = new List<string>(inviteQueueHash); MultiParty = multiParty; if (onCreated != null) MultipartyCreatedLocally += onCreated; } internal void OnMultipartyCreatedLocally(object sender, MultipartyCreatedEventArgs e) { if (MultipartyCreatedLocally != null) { MultipartyCreatedLocally(sender, e); MultipartyCreatedLocally -= OnMultipartyCreatedLocally; } } }; /// <summary> /// Creates a new multiparty (Group chat) /// </summary> /// <param name="inviteQueue">Contacts to be invited (don't add yourself)</param> /// <param name="onCreated">The handler to be executed when multiparty created (must be provided)</param> /// <exception cref="ArgumentNullException">inviteQueue or event handler is null</exception> /// <exception cref="InvalidOperationException">At least 2 contacts is required except you and contacts must support multiparty</exception> /// <returns>Transaction ID</returns> public int CreateMultiparty(List<Contact> inviteQueue, EventHandler<MultipartyCreatedEventArgs> onCreated) { if (inviteQueue == null || inviteQueue.Count == 0) throw new ArgumentNullException("inviteQueue"); if (onCreated == null) throw new ArgumentNullException("onCreated"); List<string> newQueue = new List<string>(); foreach (Contact c in inviteQueue) { if (c != null && !c.IsSibling(Owner) && !newQueue.Contains(c.SiblingString) && c.SupportsMultiparty) { newQueue.Add(c.SiblingString); } } if (newQueue.Count < 2) throw new InvalidOperationException("At least 2 contacts is required except you and contacts must support multiparty."); NSMessageProcessor nsmp = (NSMessageProcessor)MessageProcessor; int transId = nsmp.IncreaseTransactionID(); lock (multiParties) multiParties[transId] = new MultipartyObject(transId, newQueue, null, onCreated); string to = ((int)IMAddressInfoType.TemporaryGroup).ToString() + ":" + Guid.Empty.ToString("D").ToLowerInvariant() + "@" + Contact.DefaultHostDomain; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/circle"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/multiparty+xml"; mmMessage.InnerBody = new byte[0]; NSMessage putPayload = new NSMessage("PUT"); putPayload.InnerMessage = mmMessage; nsmp.SendMessage(putPayload, transId); return transId; } #endregion #region GetMultiparty public Contact GetMultiparty(string tempGroupAddress) { if (!String.IsNullOrEmpty(tempGroupAddress)) { lock (multiParties) { foreach (MultipartyObject group in multiParties.Values) { if (group.MultiParty != null && group.MultiParty.Account == tempGroupAddress) return group.MultiParty; } } } return null; } internal MultipartyObject GetMultipartyObject(string tempGroupAddress) { if (!String.IsNullOrEmpty(tempGroupAddress)) { lock (multiParties) { foreach (MultipartyObject group in multiParties.Values) { if (group.MultiParty != null && group.MultiParty.Account == tempGroupAddress) return group; } } } return null; } #endregion #region InviteContactToMultiparty public void InviteContactToMultiparty(Contact contact, Contact group) { string to = ((int)group.ClientType).ToString() + ":" + group.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.RoutingHeaders[MIMERoutingHeaders.To][MIMERoutingHeaders.Path] = "IM"; mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/circle"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/multiparty+xml"; string xml = "<circle><roster><id>IM</id><user><id>" + ((int)contact.ClientType).ToString() + ":" + contact.Account + "</id></user></roster></circle>"; mmMessage.InnerBody = Encoding.UTF8.GetBytes(xml); NSMessage putPayload = new NSMessage("PUT"); putPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(putPayload); } #region LeaveMultiparty public void LeaveMultiparty(Contact group) { string to = ((int)group.ClientType).ToString() + ":" + group.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/circle/roster(IM)/user(" + from + ")"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/circles+xml"; mmMessage.InnerBody = new byte[0]; NSMessage delPayload = new NSMessage("DEL"); delPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(delPayload); lock (multiParties) { int delTransId = 0; foreach (MultipartyObject g in multiParties.Values) { if (g.MultiParty != null && g.MultiParty.Account == group.Account) { delTransId = g.TransactionID; break; } } if (delTransId != 0) multiParties.Remove(delTransId); } } #endregion #endregion #region JoinMultiparty internal void JoinMultiparty(Contact group) { if (group.ClientType == IMAddressInfoType.Circle || group.ClientType == IMAddressInfoType.TemporaryGroup) { string to = ((int)group.ClientType).ToString() + ":" + group.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/circle"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/circles+xml"; string xml = "<circle><roster><id>IM</id><user><id>1:" + Owner.Account + "</id></user></roster></circle>"; mmMessage.InnerBody = Encoding.UTF8.GetBytes(xml); NSMessage putPayload = new NSMessage("PUT"); putPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(putPayload); OnJoinedGroupChat(new GroupChatParticipationEventArgs(Owner, group)); } } #endregion #endregion #region MESSAGING #region SendTypingMessage protected internal virtual void SendTypingMessage(Contact remoteContact) { string to = ((int)remoteContact.ClientType).ToString() + ":" + remoteContact.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = NSMessageHandler.MachineGuid.ToString("B").ToLowerInvariant(); if (remoteContact.ClientType == IMAddressInfoType.Circle) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To][MIMERoutingHeaders.Path] = "IM"; } if (remoteContact.Via != null) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To]["via"] = ((int)remoteContact.Via.ClientType).ToString() + ":" + remoteContact.Via.Account; } mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.ControlTyping; mmMessage.InnerBody = new byte[0]; NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); } #endregion #region SendNudge protected internal virtual void SendNudge(Contact remoteContact) { string to = ((int)remoteContact.ClientType).ToString() + ":" + remoteContact.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = NSMessageHandler.MachineGuid.ToString("B").ToLowerInvariant(); if (remoteContact.ClientType == IMAddressInfoType.Circle) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To][MIMERoutingHeaders.Path] = "IM"; } if (remoteContact.Via != null) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To]["via"] = ((int)remoteContact.Via.ClientType).ToString() + ":" + remoteContact.Via.Account; } mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.Nudge; mmMessage.InnerBody = Encoding.ASCII.GetBytes("\r\n"); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); } #endregion #region SendTextMessage protected internal virtual void SendTextMessage(Contact remoteContact, TextMessage textMessage) { textMessage.PrepareMessage(); string to = ((int)remoteContact.ClientType).ToString() + ":" + remoteContact.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = NSMessageHandler.MachineGuid.ToString("B").ToLowerInvariant(); if (remoteContact.ClientType == IMAddressInfoType.Circle) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To][MIMERoutingHeaders.Path] = "IM"; } else if (remoteContact.Online) { mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Online"; } else { mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Offline"; } if (remoteContact.Via != null) { mmMessage.RoutingHeaders[MIMERoutingHeaders.To]["via"] = ((int)remoteContact.Via.ClientType).ToString() + ":" + remoteContact.Via.Account; } mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.Text; mmMessage.ContentHeaders[MIMEHeaderStrings.X_MMS_IM_Format] = textMessage.GetStyleString(); mmMessage.InnerBody = Encoding.UTF8.GetBytes(textMessage.Text); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); } protected internal virtual void SendOIMMessage(Contact remoteContact, TextMessage textMessage) { SendTextMessage(remoteContact, textMessage); } #endregion #region SendMobileMessage /// <summary> /// Sends a mobile message to the specified remote contact. This only works when /// the remote contact has it's mobile device enabled and has MSN-direct enabled. /// </summary> /// <param name="receiver"></param> /// <param name="text"></param> protected internal virtual void SendMobileMessage(Contact receiver, string text) { TextMessage txtMsg = new TextMessage(text); string to = ((int)receiver.ClientType).ToString() + ":" + ((receiver.ClientType == IMAddressInfoType.Telephone) ? "tel:" + receiver.Account : receiver.Account); string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.RoutingHeaders[MIMERoutingHeaders.ServiceChannel] = "IM/Mobile"; mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.Text; mmMessage.ContentHeaders[MIMEContentHeaders.MSIMFormat] = txtMsg.GetStyleString(); mmMessage.InnerBody = Encoding.UTF8.GetBytes(txtMsg.Text); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); } #endregion #region SendEmoticonDefinitions protected internal virtual void SendEmoticonDefinitions(Contact remoteContact, List<Emoticon> emoticons, EmoticonType icontype) { EmoticonMessage emoticonMessage = new EmoticonMessage(emoticons, icontype); string to = ((int)remoteContact.ClientType).ToString() + ":" + remoteContact.Account; string from = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(to, from); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.ContentKeyVersion = "2.0"; mmMessage.ContentHeaders[MIMEContentHeaders.MessageType] = MessageTypes.CustomEmoticon; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = icontype == EmoticonType.AnimEmoticon ? "text/x-mms-animemoticon" : "text/x-mms-emoticon"; mmMessage.InnerBody = emoticonMessage.GetBytes(); NSMessage sdgPayload = new NSMessage("SDG"); sdgPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(sdgPayload); } #endregion #endregion #region PRESENCE #region SignoutFrom internal void SignoutFrom(Guid endPointID) { if (messageProcessor == null || messageProcessor.Connected == false) return; if (endPointID == MachineGuid) { messageProcessor.Disconnect(); return; } string me = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(me, me); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/user"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/user+xml"; string xml = "<user><sep n=\"IM\" epid=\"" + endPointID.ToString("B").ToLowerInvariant() + "\"/></user>"; mmMessage.InnerBody = Encoding.UTF8.GetBytes(xml); NSMessage delPayload = new NSMessage("DEL"); delPayload.InnerMessage = mmMessage; MessageProcessor.SendMessage(delPayload); } #endregion #region SetScreenName & SetPersonalMessage /// <summary> /// Sets the contactlist owner's screenname. After receiving confirmation from the server /// this will set the Owner object's name which will in turn raise the NameChange event. /// </summary> internal void SetScreenName(string newName) { if (Owner == null) throw new MSNPSharpException("Not a valid owner"); if (string.IsNullOrEmpty(newName)) { newName = Owner.Account; } PersonalMessage pm = Owner.PersonalMessage; pm.FriendlyName = newName; SetPersonalMessage(pm); } /// <summary> /// Sets personal message. /// </summary> internal void SetPersonalMessage(PersonalMessage newPSM) { if (Owner == null) throw new MSNPSharpException("Not a valid owner"); if (Owner.Status != PresenceStatus.Offline) { SetPresenceStatus( Owner.Status, Owner.LocalEndPointIMCapabilities, Owner.LocalEndPointIMCapabilitiesEx, Owner.LocalEndPointPECapabilities, Owner.LocalEndPointPECapabilitiesEx, Owner.EpName, newPSM, true); } } /// <summary> /// Sets the scene image and scheme context. /// </summary> internal void SetSceneData(SceneImage scimg, Color sccolor) { if (Owner == null) throw new MSNPSharpException("Not a valid owner"); PersonalMessage pm = Owner.PersonalMessage; pm.ColorScheme = sccolor; pm.Scene = scimg.IsDefaultImage ? String.Empty : scimg.ContextPlain; SetPresenceStatus(Owner.Status, Owner.LocalEndPointIMCapabilities, Owner.LocalEndPointIMCapabilitiesEx, Owner.LocalEndPointPECapabilities, Owner.LocalEndPointPECapabilitiesEx, Owner.EpName, pm, true); } #endregion #region SetPresenceStatus /// <summary> /// Set the status of the contact list owner (the client). /// </summary> /// <remarks>You can only set the status _after_ SignedIn event. Otherwise you won't receive online notifications from other clients or the connection is closed by the server.</remarks> internal void SetPresenceStatus( PresenceStatus newStatus, ClientCapabilities newLocalIMCaps, ClientCapabilitiesEx newLocalIMCapsex, ClientCapabilities newLocalPECaps, ClientCapabilitiesEx newLocalPECapsex, string newEPName, PersonalMessage newPSM, bool forcePEservice) { if (IsSignedIn == false) throw new MSNPSharpException("Can't set status. You must wait for the SignedIn event before you can set an initial status."); if (newStatus == PresenceStatus.Offline) { SignoutFrom(MachineGuid); return; } bool setAll = (Owner.Status == PresenceStatus.Offline); if (setAll || forcePEservice || newStatus != Owner.Status || newLocalIMCaps != Owner.LocalEndPointIMCapabilities || newLocalIMCapsex != Owner.LocalEndPointIMCapabilitiesEx || newLocalPECaps != Owner.LocalEndPointPECapabilities || newLocalPECapsex != Owner.LocalEndPointPECapabilitiesEx || newEPName != Owner.EpName) { XmlDocument xmlDoc = new XmlDocument(); XmlElement userElement = xmlDoc.CreateElement("user"); // s.IM (Status, CurrentMedia) if (setAll || forcePEservice || newStatus != Owner.Status) { XmlElement service = xmlDoc.CreateElement("s"); service.SetAttribute("n", ServiceShortNames.IM.ToString()); service.InnerXml = "<Status>" + ParseStatus(newStatus) + "</Status>" + "<CurrentMedia>" + MSNHttpUtility.XmlEncode(newPSM.CurrentMedia) + "</CurrentMedia>"; userElement.AppendChild(service); if (BotMode) { Owner.SetStatus(newStatus); // Don't call Status = newStatus. It is recursive call to this method. } } // s.PE (UserTileLocation, FriendlyName, PSM, Scene, ColorScheme) if (setAll || forcePEservice) { XmlElement service = xmlDoc.CreateElement("s"); service.SetAttribute("n", ServiceShortNames.PE.ToString()); service.InnerXml = newPSM.Payload; userElement.AppendChild(service); // Don't set owner.PersonalMessage here. It is replaced (with a new reference) when NFY PUT received. // Exception: Bots if (BotMode) { // Don't call Owner.PersonalMessage. It is recursive call to this method. ((Contact)Owner).PersonalMessage = newPSM; } } // sep.IM (Capabilities) if (setAll || newLocalIMCaps != Owner.LocalEndPointIMCapabilities || newLocalIMCapsex != Owner.LocalEndPointIMCapabilitiesEx) { ClientCapabilities localIMCaps = setAll ? ClientCapabilities.DefaultIM : newLocalIMCaps; ClientCapabilitiesEx localIMCapsEx = setAll ? ClientCapabilitiesEx.DefaultIM : newLocalIMCapsex; if (BotMode) { localIMCaps |= ClientCapabilities.IsBot; } XmlElement sep = xmlDoc.CreateElement("sep"); sep.SetAttribute("n", ServiceShortNames.IM.ToString()); XmlElement capabilities = xmlDoc.CreateElement("Capabilities"); capabilities.InnerText = ((long)localIMCaps).ToString() + ":" + ((long)localIMCapsEx).ToString(); sep.AppendChild(capabilities); userElement.AppendChild(sep); if (BotMode) { // Don't call Owner.LocalEndPointIMCapabilities. It is recursive call to this method. Owner.EndPointData[MachineGuid].IMCapabilities = localIMCaps; Owner.EndPointData[MachineGuid].IMCapabilitiesEx = localIMCapsEx; } } // sep.PE (Capabilities) if (setAll || newLocalPECaps != Owner.LocalEndPointPECapabilities || newLocalPECapsex != Owner.LocalEndPointPECapabilitiesEx) { ClientCapabilities localPECaps = setAll ? ClientCapabilities.DefaultPE : newLocalPECaps; ClientCapabilitiesEx localPECapsEx = setAll ? ClientCapabilitiesEx.DefaultPE : newLocalPECapsex; XmlElement sep = xmlDoc.CreateElement("sep"); sep.SetAttribute("n", ServiceShortNames.PE.ToString()); XmlElement VER = xmlDoc.CreateElement("VER"); VER.InnerText = Credentials.ClientInfo.MessengerClientName + ":" + Credentials.ClientInfo.MessengerClientBuildVer; sep.AppendChild(VER); XmlElement TYP = xmlDoc.CreateElement("TYP"); TYP.InnerText = "1"; sep.AppendChild(TYP); XmlElement capabilities = xmlDoc.CreateElement("Capabilities"); capabilities.InnerText = ((long)localPECaps).ToString() + ":" + ((long)localPECapsEx).ToString(); sep.AppendChild(capabilities); userElement.AppendChild(sep); if (BotMode) { // Don't call Owner.LocalEndPointPECapabilities. It is recursive call to this method. Owner.EndPointData[MachineGuid].PECapabilities = localPECaps; Owner.EndPointData[MachineGuid].PECapabilitiesEx = localPECapsEx; } } // sep.PD (EpName, State) if (setAll || newEPName != Owner.EpName || newStatus != Owner.Status) { XmlElement sep = xmlDoc.CreateElement("sep"); sep.SetAttribute("n", ServiceShortNames.PD.ToString()); XmlElement clientType = xmlDoc.CreateElement("ClientType"); clientType.InnerText = "1"; sep.AppendChild(clientType); XmlElement epName = xmlDoc.CreateElement("EpName"); epName.InnerText = MSNHttpUtility.XmlEncode(newEPName); sep.AppendChild(epName); XmlElement idle = xmlDoc.CreateElement("Idle"); idle.InnerText = ((newStatus == PresenceStatus.Idle) ? "true" : "false"); sep.AppendChild(idle); XmlElement state = xmlDoc.CreateElement("State"); state.InnerText = ParseStatus(newStatus); sep.AppendChild(state); userElement.AppendChild(sep); if (BotMode) { // Don't call Owner.EpName. It is recursive call to this method. PrivateEndPointData privateEndPoint = Owner.EndPointData[MachineGuid] as PrivateEndPointData; privateEndPoint.ClientType = String.Copy(clientType.InnerText); privateEndPoint.Name = newEPName; privateEndPoint.Idle = bool.Parse(((newStatus == PresenceStatus.Idle) ? "true" : "false")); privateEndPoint.State = newStatus; } } if (userElement.HasChildNodes) { string xml = userElement.OuterXml; string me = ((int)Owner.ClientType).ToString() + ":" + Owner.Account; MultiMimeMessage mmMessage = new MultiMimeMessage(me, me); mmMessage.RoutingHeaders[MIMERoutingHeaders.From][MIMERoutingHeaders.EPID] = NSMessageHandler.MachineGuid.ToString("B").ToLowerInvariant(); mmMessage.Stream = 1; mmMessage.ReliabilityHeaders[MIMEReliabilityHeaders.Flags] = "ACK"; mmMessage.ContentKey = MIMEContentHeaders.Publication; mmMessage.ContentHeaders[MIMEContentHeaders.URI] = "/user"; mmMessage.ContentHeaders[MIMEContentHeaders.ContentType] = "application/user+xml"; mmMessage.InnerBody = System.Text.Encoding.UTF8.GetBytes(xml); NSMessage nsMessage = new NSMessage("PUT"); nsMessage.InnerMessage = mmMessage; MessageProcessor.SendMessage(nsMessage); } } } #endregion #endregion #region COMMAND HANDLERS (PUT, DEL, NFY, SDG) #region OnPUTReceived /// <summary> /// Called when a PUT command message has been received. /// </summary> /// <param name="message"></param> protected virtual void OnPUTReceived(NSMessage message) { bool ok = message.CommandValues.Count > 0 && message.CommandValues[0].ToString() == "OK"; if (multiParties.ContainsKey(message.TransactionID)) { if (ok == false || message.InnerBody == null || message.InnerBody.Length == 0) { lock (multiParties) multiParties.Remove(message.TransactionID); return; } MultiMimeMessage mmMessage = new MultiMimeMessage(message.InnerBody); string[] tempGroup = mmMessage.From.Value.Split(':'); IMAddressInfoType addressType = (IMAddressInfoType)int.Parse(tempGroup[0]); if (addressType == IMAddressInfoType.TemporaryGroup) { Contact group = new Contact(tempGroup[1].ToLowerInvariant(), IMAddressInfoType.TemporaryGroup, this); group.ContactList = new ContactList(new Guid(tempGroup[1].ToLowerInvariant().Split('@')[0]), null, group, this); MultipartyObject mpo = multiParties[message.TransactionID]; mpo.TransactionID = message.TransactionID; mpo.MultiParty = group; JoinMultiparty(group); List<string> copy = new List<string>(mpo.InviteQueueHash); foreach (string siblingHash in copy) { string[] addressTypeAndAccount = siblingHash.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); Contact contact = ContactList.GetContactWithCreate(addressTypeAndAccount[1], (IMAddressInfoType)Enum.Parse(typeof(IMAddressInfoType), addressTypeAndAccount[0].ToString())); InviteContactToMultiparty(contact, group); } mpo.OnMultipartyCreatedLocally(this, new MultipartyCreatedEventArgs(group)); group.SetStatus(PresenceStatus.Online); Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "MultipartyCreated: " + group.Account); } else { lock (multiParties) multiParties.Remove(message.TransactionID); } } } #endregion #region OnDELReceived /// <summary> /// Called when a DEL command message has been received. /// </summary> /// <param name="message"></param> protected virtual void OnDELReceived(NSMessage message) { bool ok = message.CommandValues.Count > 0 && message.CommandValues[0].ToString() == "OK"; if (ok) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "DEL command accepted", GetType().Name); } } #endregion #region OnNFYReceived private void OnNFYPUTReceived(MultiMimeMessage multiMimeMessage, RoutingInfo routingInfo) { switch (multiMimeMessage.ContentHeaders[MIMEContentHeaders.ContentType].Value) { #region user xml case "application/user+xml": { if (multiMimeMessage.ContentHeaders[MIMEHeaderStrings.NotifType].Value == "Sync") { if (routingInfo.SenderGateway != null && routingInfo.SenderGateway.ClientType == IMAddressInfoType.Circle) { JoinMultiparty(routingInfo.SenderGateway); } //Sync the contact in contact list with the contact in gateway. // TODO: Set the NSMessagehandler.ContactList contact to the gateway // TODO: triger the ContactOnline event for the gateway contact. //Just wait for my fix. } if (multiMimeMessage.InnerBody == null || multiMimeMessage.InnerBody.Length == 0) return; //No xml content. if (multiMimeMessage.ContentHeaders[MIMEHeaderStrings.NotifType].Value == "Full") { //This is an initial NFY } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(Encoding.UTF8.GetString(multiMimeMessage.InnerBody)); XmlNodeList services = xmlDoc.SelectNodes("//user/s"); XmlNodeList serviceEndPoints = xmlDoc.SelectNodes("//user/sep"); if (services.Count > 0) { foreach (XmlNode service in services) { ServiceShortNames serviceEnum = (ServiceShortNames)Enum.Parse(typeof(ServiceShortNames), service.Attributes["n"].Value); switch (serviceEnum) { case ServiceShortNames.IM: { foreach (XmlNode node in service.ChildNodes) { switch (node.Name) { case "Status": if (routingInfo.FromOwner && IsSignedIn == false) { // We have already signed in another place, but not here... // Don't set status... This place will set the status later. return; } PresenceStatus oldStatus = routingInfo.Sender.Status; PresenceStatus newStatus = ParseStatus(node.InnerText); routingInfo.Sender.SetStatus(newStatus); OnContactStatusChanged(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); OnContactOnline(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); break; case "CurrentMedia": //MSNP21TODO: UBX implementation break; } } break; } case ServiceShortNames.PE: { // Create a new reference to fire PersonalMessageChanged event. PersonalMessage personalMessage = new PersonalMessage(service.ChildNodes); if (!String.IsNullOrEmpty(personalMessage.Payload) && routingInfo.Sender.PersonalMessage != personalMessage) { // FriendlyName if (!String.IsNullOrEmpty(personalMessage.FriendlyName)) { //Only Windows Live Messenger Contact has friendly name. routingInfo.Sender.SetName(personalMessage.FriendlyName); } // UserTileLocation if (!String.IsNullOrEmpty(personalMessage.UserTileLocation) && routingInfo.Sender.UserTileLocation != personalMessage.UserTileLocation) { routingInfo.Sender.UserTileLocation = personalMessage.UserTileLocation; routingInfo.Sender.FireDisplayImageContextChangedEvent(personalMessage.UserTileLocation); } // Scene if (!String.IsNullOrEmpty(personalMessage.Scene)) { if (routingInfo.Sender.SceneContext != personalMessage.Scene) { routingInfo.Sender.SceneContext = personalMessage.Scene; routingInfo.Sender.FireSceneImageContextChangedEvent(personalMessage.Scene); } } // ColorScheme if (personalMessage.ColorScheme != Color.Empty) { if (routingInfo.Sender.ColorScheme != personalMessage.ColorScheme) { routingInfo.Sender.ColorScheme = personalMessage.ColorScheme; routingInfo.Sender.OnColorSchemeChanged(); } } // This must be final... routingInfo.Sender.PersonalMessage = personalMessage; } break; } case ServiceShortNames.PF: { // Profile Annotation, it is AB.Me.annotations/Live.Profile.Expression.LastChanged // <user><s n="PF" ts="2011-04-16T06:00:58Z"></s></user> if (routingInfo.FromOwner) { DateTime ts = WebServiceDateTimeConverter.ConvertToDateTime(service.Attributes["ts"].Value); } break; } } } } if (serviceEndPoints.Count > 0) { foreach (XmlNode serviceEndPoint in serviceEndPoints) { ServiceShortNames serviceEnum = (ServiceShortNames)Enum.Parse(typeof(ServiceShortNames), serviceEndPoint.Attributes["n"].Value); Guid epid = serviceEndPoint.Attributes["epid"] == null ? Guid.Empty : new Guid(serviceEndPoint.Attributes["epid"].Value); if (!routingInfo.Sender.EndPointData.ContainsKey(epid)) { lock (routingInfo.Sender.SyncObject) routingInfo.Sender.EndPointData.Add(epid, routingInfo.FromOwner ? new PrivateEndPointData(routingInfo.Sender.Account, epid) : new EndPointData(routingInfo.Sender.Account, epid)); } switch (serviceEnum) { case ServiceShortNames.IM: { foreach (XmlNode node in serviceEndPoint.ChildNodes) { switch (node.Name) { case "Capabilities": ClientCapabilities cap = ClientCapabilities.None; ClientCapabilitiesEx capEx = ClientCapabilitiesEx.None; string[] caps = node.InnerText.Split(':'); if (caps.Length > 1) { capEx = (ClientCapabilitiesEx)long.Parse(caps[1]); } cap = (ClientCapabilities)long.Parse(caps[0]); routingInfo.Sender.EndPointData[epid].IMCapabilities = cap; routingInfo.Sender.EndPointData[epid].IMCapabilitiesEx = capEx; break; } } break; } case ServiceShortNames.PE: { foreach (XmlNode node in serviceEndPoint.ChildNodes) { switch (node.Name) { case "Capabilities": ClientCapabilities cap = ClientCapabilities.None; ClientCapabilitiesEx capEx = ClientCapabilitiesEx.None; string[] caps = node.InnerText.Split(':'); if (caps.Length > 1) { capEx = (ClientCapabilitiesEx)long.Parse(caps[1]); } cap = (ClientCapabilities)long.Parse(caps[0]); routingInfo.Sender.EndPointData[epid].PECapabilities = cap; routingInfo.Sender.EndPointData[epid].PECapabilitiesEx = capEx; break; } } routingInfo.Sender.SetChangedPlace(new PlaceChangedEventArgs(routingInfo.Sender.EndPointData[epid], PlaceChangedReason.SignedIn)); break; } case ServiceShortNames.PD: { PrivateEndPointData privateEndPoint = routingInfo.Sender.EndPointData[epid] as PrivateEndPointData; foreach (XmlNode node in serviceEndPoint.ChildNodes) { switch (node.Name) { case "ClientType": privateEndPoint.ClientType = node.InnerText; break; case "EpName": privateEndPoint.Name = node.InnerText; break; case "Idle": privateEndPoint.Idle = bool.Parse(node.InnerText); break; case "State": privateEndPoint.State = ParseStatus(node.InnerText); break; } } Owner.SetChangedPlace(new PlaceChangedEventArgs(privateEndPoint, PlaceChangedReason.SignedIn)); break; } } } } } break; #endregion #region circles xml case "application/circles+xml": { if (routingInfo.SenderType == IMAddressInfoType.Circle) { Contact circle = ContactList.GetCircle(routingInfo.SenderAccount); if (circle == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnNFYReceived] Cannot complete the operation since circle not found: " + multiMimeMessage.From.ToString()); return; } if (multiMimeMessage.InnerBody == null || multiMimeMessage.InnerBody.Length == 0 || "<circle></circle>" == Encoding.UTF8.GetString(multiMimeMessage.InnerBody)) { // No xml content and full notify... Circle goes online... if (multiMimeMessage.ContentHeaders[MIMEHeaderStrings.NotifType].Value == "Full") { PresenceStatus oldStatus = circle.Status; PresenceStatus newStatus = PresenceStatus.Online; circle.SetStatus(newStatus); // The contact changed status OnContactStatusChanged(new ContactStatusChangedEventArgs(circle, oldStatus, newStatus)); // The contact goes online OnContactOnline(new ContactStatusChangedEventArgs(circle, oldStatus, newStatus)); } return; } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(Encoding.UTF8.GetString(multiMimeMessage.InnerBody)); XmlNodeList ids = xmlDoc.SelectNodes("//circle/roster/user/id"); if (ids.Count == 0) { return; //I hate indent. } foreach (XmlNode node in ids) { IMAddressInfoType accountAddressType; string account; IMAddressInfoType viaAccountAddressType; string viaAccount; string fullAccount = node.InnerText; if (false == Contact.ParseFullAccount(fullAccount, out accountAddressType, out account, out viaAccountAddressType, out viaAccount)) { continue; } if (account == Owner.Account) continue; if (circle.ContactList.HasContact(account, accountAddressType)) { Contact contact = circle.ContactList.GetContact(account, accountAddressType); OnJoinedGroupChat(new GroupChatParticipationEventArgs(contact, circle)); } } } else if (routingInfo.SenderType == IMAddressInfoType.TemporaryGroup) { MultipartyObject mpo = GetMultipartyObject(routingInfo.SenderAccount); Contact group = null; if (mpo == null) { // Created remotely. NSMessageProcessor nsmp = (NSMessageProcessor)MessageProcessor; int transId = nsmp.IncreaseTransactionID(); group = new Contact(routingInfo.SenderAccount, IMAddressInfoType.TemporaryGroup, this); group.ContactList = new ContactList(new Guid(routingInfo.SenderAccount.Split('@')[0]), null, group, this); mpo = new MultipartyObject(transId, new List<string>(), group, null); lock (multiParties) multiParties[transId] = mpo; OnMultipartyCreatedRemotely(new MultipartyCreatedEventArgs(group)); group.SetStatus(PresenceStatus.Online); } else { group = mpo.MultiParty; } if (multiMimeMessage.InnerBody == null || multiMimeMessage.InnerBody.Length == 0) { // No xml content and full notify... Circle goes online... if (multiMimeMessage.ContentHeaders[MIMEHeaderStrings.NotifType].Value == "Full") { PresenceStatus oldStatus = group.Status; PresenceStatus newStatus = PresenceStatus.Online; group.SetStatus(newStatus); // The contact changed status OnContactStatusChanged(new ContactStatusChangedEventArgs(group, oldStatus, newStatus)); // The contact goes online OnContactOnline(new ContactStatusChangedEventArgs(group, oldStatus, newStatus)); } return; } // Join multiparty if state is Pending XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(Encoding.UTF8.GetString(multiMimeMessage.InnerBody)); XmlNodeList rosters = xmlDoc.SelectNodes("//circle/roster/user"); foreach (XmlNode roster in rosters) { string state = (roster["state"] == null) ? string.Empty : roster["state"].InnerText; string[] fullAccount = roster["id"].InnerText.Split(':'); IMAddressInfoType addressType = (IMAddressInfoType)int.Parse(fullAccount[0]); string memberAccount = fullAccount[1].ToLowerInvariant(); // Me contact if ("pending" == state.ToLowerInvariant() && addressType == Owner.ClientType && memberAccount == Owner.Account) { JoinMultiparty(group); } else { Contact part = group.ContactList.GetContactWithCreate(memberAccount, addressType); Contact real = ContactList.GetContactWithCreate(memberAccount, addressType); part.SetStatus(real.Status); OnJoinedGroupChat(new GroupChatParticipationEventArgs(part, group)); if (mpo.InviteQueueHash.Contains(part.SiblingString)) mpo.InviteQueueHash.Remove(part.SiblingString); } } } } break; #endregion #region network xml case "application/network+xml": { if (routingInfo.Sender.ClientType == IMAddressInfoType.RemoteNetwork && routingInfo.Sender.Account == RemoteNetworkGateways.FaceBookGatewayAccount) { string status = Encoding.UTF8.GetString(multiMimeMessage.InnerBody); PresenceStatus oldStatus = routingInfo.Sender.Status; PresenceStatus newStatus = PresenceStatus.Unknown; if (status.Contains("SignedIn")) newStatus = PresenceStatus.Online; else if (status.Contains("SignedOut")) newStatus = PresenceStatus.Offline; if (newStatus != PresenceStatus.Unknown) { routingInfo.Sender.SetStatus(newStatus); // The contact changed status OnContactStatusChanged(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); if (newStatus == PresenceStatus.Online) OnContactOnline(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); else OnContactOffline(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); } } } break; #endregion } } private void OnNFYDELReceived(MultiMimeMessage multiMimeMessage, RoutingInfo routingInfo) { switch (multiMimeMessage.ContentHeaders[MIMEContentHeaders.ContentType].Value) { #region user xml case "application/user+xml": { if (multiMimeMessage.InnerBody == null || multiMimeMessage.InnerBody.Length == 0) return; //No xml content. if (multiMimeMessage.ContentHeaders[MIMEHeaderStrings.NotifType].Value == "Full") { //This is an initial NFY } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(Encoding.UTF8.GetString(multiMimeMessage.InnerBody)); XmlNodeList services = xmlDoc.SelectNodes("//user/s"); XmlNodeList serviceEndPoints = xmlDoc.SelectNodes("//user/sep"); if (serviceEndPoints.Count > 0) { foreach (XmlNode serviceEndPoint in serviceEndPoints) { ServiceShortNames serviceEnum = (ServiceShortNames)Enum.Parse(typeof(ServiceShortNames), serviceEndPoint.Attributes["n"].Value); Guid epid = serviceEndPoint.Attributes["epid"] == null ? Guid.Empty : new Guid(serviceEndPoint.Attributes["epid"].Value); switch (serviceEnum) { case ServiceShortNames.IM: case ServiceShortNames.PD: { if (routingInfo.Sender.EndPointData.ContainsKey(epid)) { routingInfo.Sender.SetChangedPlace(new PlaceChangedEventArgs(routingInfo.Sender.EndPointData[epid], PlaceChangedReason.SignedOut)); } if (routingInfo.FromOwner && epid == MachineGuid && messageProcessor != null) { SignoutFrom(epid); } break; } } } } if (services.Count > 0) { foreach (XmlNode service in services) { ServiceShortNames serviceEnum = (ServiceShortNames)Enum.Parse(typeof(ServiceShortNames), service.Attributes["n"].Value); switch (serviceEnum) { case ServiceShortNames.IM: { PresenceStatus oldStatus = routingInfo.Sender.Status; PresenceStatus newStatus = PresenceStatus.Offline; routingInfo.Sender.SetStatus(newStatus); OnContactStatusChanged(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); OnContactOffline(new ContactStatusChangedEventArgs(routingInfo.Sender, routingInfo.SenderGateway, oldStatus, newStatus)); break; } } } } } break; #endregion #region circles xml case "application/circles+xml": { Contact circle = null; Contact group = null; if (routingInfo.SenderType == IMAddressInfoType.Circle) { circle = ContactList.GetCircle(routingInfo.SenderAccount); if (circle == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnNFYReceived] Cannot complete the operation since circle not found: " + multiMimeMessage.From.ToString()); return; } } else if (routingInfo.SenderType == IMAddressInfoType.TemporaryGroup) { group = GetMultiparty(routingInfo.SenderAccount); if (group == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnNFYReceived] temp group not found: " + multiMimeMessage.From.ToString()); return; } } else { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnNFYReceived] sender is not circle nor temp group: " + multiMimeMessage.From.ToString()); return; } if (multiMimeMessage.ContentHeaders.ContainsKey(MIMEHeaderStrings.Uri)) { string xpathUri = multiMimeMessage.ContentHeaders[MIMEHeaderStrings.Uri].ToString(); if (xpathUri.Contains("/circle/roster(IM)/user")) { string typeAccount = xpathUri.Substring("/circle/roster(IM)/user".Length); typeAccount = typeAccount.Substring(typeAccount.IndexOf("(") + 1); typeAccount = typeAccount.Substring(0, typeAccount.IndexOf(")")); string[] member = typeAccount.Split(':'); string memberAccount = member[1]; IMAddressInfoType memberNetwork = (IMAddressInfoType)int.Parse(member[0]); Contact c = null; if (circle != null) { if (!circle.ContactList.HasContact(memberAccount, memberNetwork)) return; c = circle.ContactList.GetContact(memberAccount, memberNetwork); OnLeftGroupChat(new GroupChatParticipationEventArgs(c, circle)); } if (group != null) { if (!group.ContactList.HasContact(memberAccount, memberNetwork)) return; c = group.ContactList.GetContact(memberAccount, memberNetwork); group.ContactList.Remove(memberAccount, memberNetwork); OnLeftGroupChat(new GroupChatParticipationEventArgs(c, group)); } } else { Contact goesOfflineGroup = null; if (circle != null) goesOfflineGroup = circle; else if (group != null) goesOfflineGroup = group; // Group goes offline... if (goesOfflineGroup != null) { PresenceStatus oldStatus = goesOfflineGroup.Status; PresenceStatus newStatus = PresenceStatus.Offline; goesOfflineGroup.SetStatus(newStatus); // the contact changed status OnContactStatusChanged(new ContactStatusChangedEventArgs(goesOfflineGroup, routingInfo.SenderGateway, oldStatus, newStatus)); // the contact goes offline OnContactOffline(new ContactStatusChangedEventArgs(goesOfflineGroup, routingInfo.SenderGateway, oldStatus, newStatus)); } } } } break; #endregion #region network xml case "application/network+xml": { } break; #endregion } } /// <summary> /// Called when a NFY command has been received. /// <code> /// NFY [TransactionID] [Operation: PUT|DEL] [Payload Length]\r\n[Payload Data] /// </code> /// </summary> /// <param name="message"></param> protected virtual void OnNFYReceived(NSMessage message) { NetworkMessage networkMessage = message as NetworkMessage; if (networkMessage.InnerBody == null || networkMessage.InnerBody.Length == 0) return; //PUT or DEL string command = message.CommandValues[0].ToString(); MultiMimeMessage multiMimeMessage = new MultiMimeMessage(networkMessage.InnerBody); if (!(multiMimeMessage.ContentHeaders.ContainsKey(MIMEContentHeaders.ContentType))) return; RoutingInfo routingInfo = RoutingInfo.FromMultiMimeMessage(multiMimeMessage, this); if (routingInfo == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnNFYReceived] Get Rounting Info Error."); return; } if (command == "PUT") { OnNFYPUTReceived(multiMimeMessage, routingInfo); } else if (command == "DEL") { OnNFYDELReceived(multiMimeMessage, routingInfo); } } #endregion #region OnSDGReceived //This is actually another OnMSGxxx /// <summary> /// Called when a SDG command has been received. /// <remarks>Indicates that someone send us a message.</remarks> /// <code> /// SDG 0 [Payload Length]\r\n[Payload Data] /// </code> /// </summary> /// <param name="message"></param> protected virtual void OnSDGReceived(NSMessage message) { if (message.InnerBody == null || (message.InnerMessage is MultiMimeMessage) == false) { // This is not an SDG MultiMimeMessage message return; } MultiMimeMessage multiMimeMessage = message.InnerMessage as MultiMimeMessage; #region Get the Routing Info RoutingInfo routingInfo = RoutingInfo.FromMultiMimeMessage(multiMimeMessage, this); if (routingInfo == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnSDGReceived] Get Rounting Info Error."); return; } Contact sender = null; // via=fb, circle or temporary group Contact originalSender = null; // invidiual sender, 1 on 1 chat if (routingInfo.ReceiverType == IMAddressInfoType.Circle || routingInfo.ReceiverType == IMAddressInfoType.TemporaryGroup) { sender = routingInfo.Receiver; if (sender == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "[OnSDGReceived] Error: Cannot find group: " + multiMimeMessage.To.ToString()); return; } originalSender = routingInfo.Sender; } // External Network if (originalSender == null && routingInfo.SenderGateway != null) { originalSender = routingInfo.SenderGateway; sender = routingInfo.Sender; } if (originalSender == null) { sender = routingInfo.Sender; originalSender = sender; } #endregion if (multiMimeMessage.ContentHeaders.ContainsKey(MIMEContentHeaders.MessageType)) { switch (multiMimeMessage.ContentHeaders[MIMEContentHeaders.MessageType].ToString()) { default: Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "[OnSDGReceived] UNHANDLED MESSAGE TYPE: \r\n" + multiMimeMessage.ContentHeaders[MIMEContentHeaders.MessageType].ToString() + "\r\n\r\nMessage Body: \r\n\r\n" + multiMimeMessage.ToDebugString()); break; case MessageTypes.Nudge: OnNudgeReceived(new NudgeArrivedEventArgs(sender, originalSender, routingInfo)); break; case MessageTypes.ControlTyping: OnTypingMessageReceived(new TypingArrivedEventArgs(sender, originalSender, routingInfo)); break; case MessageTypes.Text: OnSDGTextMessageReceived(multiMimeMessage, sender, originalSender, routingInfo); break; case MessageTypes.CustomEmoticon: OnSDGCustomEmoticonReceived(multiMimeMessage, sender, originalSender, routingInfo); break; case MessageTypes.Wink: OnSDGWinkReceived(multiMimeMessage, sender, originalSender, routingInfo); break; case MessageTypes.SignalP2P: OnSDGP2PSignalReceived(multiMimeMessage, sender, originalSender, routingInfo); break; case MessageTypes.SignalCloseIMWindow: OnSDGCloseIMWindowReceived(multiMimeMessage, routingInfo); break; case MessageTypes.Data: OnSDGDataMessageReceived(multiMimeMessage, sender, originalSender, routingInfo); break; } } } #region Process SDG Messages private void OnSDGCloseIMWindowReceived(MultiMimeMessage multiMimeMessage, RoutingInfo routingInfo) { string partiesString = (multiMimeMessage.InnerMessage as TextPayloadMessage).Text; if (string.IsNullOrEmpty(partiesString)) return; string[] parties = partiesString.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); IMAddressInfoType addressInfo = IMAddressInfoType.None; string account = string.Empty; List<Contact> partiesList = new List<Contact>(0); for (int i = 0; i < parties.Length; i++) { Contact.ParseFullAccount(parties[i], out addressInfo, out account); Contact party = ContactList.GetContact(account, addressInfo); if (party != null) partiesList.Add(party); } EndPointData senderEndPoint = null; EndPointData receiverEndPoint = null; if (routingInfo.Sender != null) { if (routingInfo.Sender.EndPointData.ContainsKey(routingInfo.SenderEndPointID)) senderEndPoint = routingInfo.Sender.EndPointData[routingInfo.SenderEndPointID]; } if (routingInfo.Receiver != null) { if (routingInfo.Receiver.EndPointData.ContainsKey(routingInfo.ReceiverEndPointID)) receiverEndPoint = routingInfo.Receiver.EndPointData[routingInfo.ReceiverEndPointID]; } OnRemoteEndPointCloseIMWindow(new CloseIMWindowEventArgs(routingInfo.Sender, senderEndPoint, routingInfo.Receiver, receiverEndPoint, partiesList.ToArray())); } private void OnSDGWinkReceived(MultiMimeMessage multiMimeMessage, Contact sender, Contact originalSender, RoutingInfo routingInfo) { Wink wink = new Wink(); wink.SetContext((multiMimeMessage.InnerMessage as TextPayloadMessage).Text); OnWinkDefinitionReceived(new WinkEventArgs(originalSender, wink, routingInfo)); } private void OnSDGCustomEmoticonReceived(MultiMimeMessage multiMimeMessage, Contact sender, Contact originalSender, RoutingInfo routingInfo) { EmoticonMessage emoticonMessage = multiMimeMessage.InnerMessage as EmoticonMessage; foreach (Emoticon emoticon in emoticonMessage.Emoticons) { OnEmoticonDefinitionReceived(new EmoticonDefinitionEventArgs(originalSender, originalSender, routingInfo, emoticon)); } } private void OnSDGTextMessageReceived(MultiMimeMessage multiMimeMessage, Contact sender, Contact by, RoutingInfo routingInfo) { TextMessage txtMessage = multiMimeMessage.InnerMessage as TextMessage; OnTextMessageReceived(new TextMessageArrivedEventArgs(sender, txtMessage, by, routingInfo)); } private void OnSDGP2PSignalReceived(MultiMimeMessage multiMimeMessage, Contact sender, Contact by, RoutingInfo routingInfo) { //SLPMessage slpMessage = SLPMessage.Parse(multiMimeMessage.InnerBody); SLPMessage slpMessage = multiMimeMessage.InnerMessage as SLPMessage; if (slpMessage != null) { if (slpMessage.ContentType == "application/x-msnmsgr-transreqbody" || slpMessage.ContentType == "application/x-msnmsgr-transrespbody" || slpMessage.ContentType == "application/x-msnmsgr-transdestaddrupdate") { P2PSession.ProcessDirectInvite(slpMessage, this, null); } } } private MultiMimeMessage ParseSDGDataMessage(MultiMimeMessage multiMimeMessage, Contact sender, Contact by) { return multiMimeMessage; } private void OnSDGDataMessageReceived(MultiMimeMessage multiMimeMessage, Contact sender, Contact by, RoutingInfo routingInfo) { Guid senderEPID = routingInfo.SenderEndPointID; P2PVersion p2pVer = senderEPID == Guid.Empty ? P2PVersion.P2PV1 : P2PVersion.P2PV2; string[] offsets = multiMimeMessage.ContentHeaders.ContainsKey(MIMEContentHeaders.BridgingOffsets) ? multiMimeMessage.ContentHeaders[MIMEContentHeaders.BridgingOffsets].ToString().Split(',') : new string[] { "0" }; List<long> offsetList = new List<long>(); foreach (string os in offsets) { offsetList.Add(long.Parse(os)); } P2PMessage p2pData = new P2PMessage(p2pVer); P2PMessage[] p2pDatas = p2pData.CreateFromOffsets(offsetList.ToArray(), multiMimeMessage.InnerBody); if (multiMimeMessage.ContentHeaders.ContainsKey(MIMEContentHeaders.Pipe)) { SDGBridge.PackageNo = ushort.Parse(multiMimeMessage.ContentHeaders[MIMEContentHeaders.Pipe]); } foreach (P2PMessage m in p2pDatas) { SDGBridge.ProcessP2PMessage(sender, senderEPID, m); } } #endregion #endregion #endregion } };
namespace NEventStore.Persistence.Sql { using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Threading; using System.Transactions; using NEventStore.Logging; using NEventStore.Serialization; public class SqlPersistenceEngine : IPersistStreams { private static readonly ILog Logger = LogFactory.BuildLogger(typeof(SqlPersistenceEngine)); private static readonly DateTime EpochTime = new DateTime(1970, 1, 1); private readonly IConnectionFactory _connectionFactory; private readonly ISqlDialect _dialect; private readonly int _pageSize; private readonly TransactionScopeOption _scopeOption; private readonly ISerialize _serializer; private bool _disposed; private int _initialized; private readonly IStreamIdHasher _streamIdHasher; public SqlPersistenceEngine( IConnectionFactory connectionFactory, ISqlDialect dialect, ISerialize serializer, TransactionScopeOption scopeOption, int pageSize) : this(connectionFactory, dialect, serializer, scopeOption, pageSize, new Sha1StreamIdHasher()) { } public SqlPersistenceEngine( IConnectionFactory connectionFactory, ISqlDialect dialect, ISerialize serializer, TransactionScopeOption scopeOption, int pageSize, IStreamIdHasher streamIdHasher) { if (connectionFactory == null) { throw new ArgumentNullException("connectionFactory"); } if (dialect == null) { throw new ArgumentNullException("dialect"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } if (pageSize < 0) { throw new ArgumentException("pageSize"); } if (streamIdHasher == null) { throw new ArgumentNullException("streamIdHasher"); } _connectionFactory = connectionFactory; _dialect = dialect; _serializer = serializer; _scopeOption = scopeOption; _pageSize = pageSize; _streamIdHasher = new StreamIdHasherValidator(streamIdHasher); Logger.Debug(Messages.UsingScope, _scopeOption.ToString()); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual void Initialize() { if (Interlocked.Increment(ref _initialized) > 1) { return; } Logger.Debug(Messages.InitializingStorage); ExecuteCommand(statement => statement.ExecuteWithoutExceptions(_dialect.InitializeStorage)); } public virtual IEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision) { Logger.Debug(Messages.GettingAllCommitsBetween, streamId, minRevision, maxRevision); streamId = _streamIdHasher.GetHash(streamId); return ExecuteQuery(query => { string statement = _dialect.GetCommitsFromStartingRevision; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); query.AddParameter(_dialect.StreamRevision, minRevision); query.AddParameter(_dialect.MaxStreamRevision, maxRevision); query.AddParameter(_dialect.CommitSequence, 0); return query .ExecutePagedQuery(statement, _dialect.NextPageDelegate) .Select(x => x.GetCommit(_serializer, _dialect)); }); } public virtual IEnumerable<ICommit> GetStreams(string bucketId, params string[] streamIds) { Logger.Debug(Messages.GettingAllCommitsBetween, streamIds, 0, int.MaxValue); streamIds = streamIds.Select(_streamIdHasher.GetHash).ToArray(); return ExecuteQuery(query => { string statement = string.Format(_dialect.GetStreams, bucketId, "('" + string.Join("','", streamIds) + "')"); query.AddParameter(_dialect.CommitSequence, 0); query.AddParameter(_dialect.StreamRevision, int.MaxValue); return query .ExecutePagedQuery(statement, _dialect.NextPageDelegate) .Select(x => x.GetCommit(_serializer, _dialect)); }); } public virtual IEnumerable<ICommit> GetFrom(string bucketId, DateTime start) { start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second. start = start < EpochTime ? EpochTime : start; Logger.Debug(Messages.GettingAllCommitsFrom, start, bucketId); return ExecuteQuery(query => { string statement = _dialect.GetCommitsFromInstant; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.CommitStamp, start); return query.ExecutePagedQuery(statement, (q, r) => { }) .Select(x => x.GetCommit(_serializer, _dialect)); }); } public virtual ICheckpoint GetCheckpoint(string checkpointToken) { if(string.IsNullOrWhiteSpace(checkpointToken)) { return new LongCheckpoint(-1); } return LongCheckpoint.Parse(checkpointToken); } public virtual IEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end) { start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerSecond)); // Rounds down to the nearest second. start = start < EpochTime ? EpochTime : start; end = end < EpochTime ? EpochTime : end; Logger.Debug(Messages.GettingAllCommitsFromTo, start, end); return ExecuteQuery(query => { string statement = _dialect.GetCommitsFromToInstant; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.CommitStampStart, start); query.AddParameter(_dialect.CommitStampEnd, end); return query.ExecutePagedQuery(statement, (q, r) => { }) .Select(x => x.GetCommit(_serializer, _dialect)); }); } public virtual ICommit Commit(CommitAttempt attempt) { ICommit commit; try { commit = PersistCommit(attempt); Logger.Debug(Messages.CommitPersisted, attempt.CommitId); } catch (Exception e) { if (!(e is UniqueKeyViolationException)) { throw; } if (DetectDuplicate(attempt)) { Logger.Info(Messages.DuplicateCommit); throw new DuplicateCommitException(e.Message, e); } Logger.Info(Messages.ConcurrentWriteDetected); throw new ConcurrencyException(e.Message, e); } return commit; } public virtual IEnumerable<ICommit> GetUndispatchedCommits() { Logger.Debug(Messages.GettingUndispatchedCommits); return ExecuteQuery(query => query.ExecutePagedQuery(_dialect.GetUndispatchedCommits, (q, r) => { })) .Select(x => x.GetCommit(_serializer, _dialect)) .ToArray(); // avoid paging } public virtual void MarkCommitAsDispatched(ICommit commit) { Logger.Debug(Messages.MarkingCommitAsDispatched, commit.CommitId); string streamId = _streamIdHasher.GetHash(commit.StreamId); ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, commit.BucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); cmd.AddParameter(_dialect.CommitSequence, commit.CommitSequence); return cmd.ExecuteWithoutExceptions(_dialect.MarkCommitAsDispatched); }); } public virtual IEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold) { Logger.Debug(Messages.GettingStreamsToSnapshot); return ExecuteQuery(query => { string statement = _dialect.GetStreamsRequiringSnapshots; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.Threshold, maxThreshold); return query.ExecutePagedQuery(statement, (q, s) => q.SetParameter(_dialect.StreamId, _dialect.CoalesceParameterValue(s.StreamId()), DbType.AnsiString)) .Select(x => x.GetStreamToSnapshot()); }); } public virtual ISnapshot GetSnapshot(string bucketId, string streamId, int maxRevision) { Logger.Debug(Messages.GettingRevision, streamId, maxRevision); var streamIdHash = _streamIdHasher.GetHash(streamId); return ExecuteQuery(query => { string statement = _dialect.GetSnapshot; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.StreamId, streamIdHash, DbType.AnsiString); query.AddParameter(_dialect.StreamRevision, maxRevision); return query.ExecuteWithQuery(statement).Select(x => x.GetSnapshot(_serializer, streamId)); }).FirstOrDefault(); } public virtual bool AddSnapshot(ISnapshot snapshot) { Logger.Debug(Messages.AddingSnapshot, snapshot.StreamId, snapshot.StreamRevision); string streamId = _streamIdHasher.GetHash(snapshot.StreamId); return ExecuteCommand((connection, cmd) => { cmd.AddParameter(_dialect.BucketId, snapshot.BucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamRevision, snapshot.StreamRevision); _dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(snapshot.Payload)); return cmd.ExecuteWithoutExceptions(_dialect.AppendSnapshotToCommit); }) > 0; } public virtual void Purge() { Logger.Warn(Messages.PurgingStorage); ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.PurgeStorage)); } public void Purge(string bucketId) { Logger.Warn(Messages.PurgingBucket, bucketId); ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); return cmd.ExecuteNonQuery(_dialect.PurgeBucket); }); } public void Drop() { Logger.Warn(Messages.DroppingTables); ExecuteCommand(cmd => cmd.ExecuteNonQuery(_dialect.Drop)); } public void DeleteStream(string bucketId, string streamId) { Logger.Warn(Messages.DeletingStream, streamId, bucketId); streamId = _streamIdHasher.GetHash(streamId); ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); return cmd.ExecuteNonQuery(_dialect.DeleteStream); }); } public bool SafeDeleteStream(string bucketId, string streamId, int itemCount) { Logger.Warn(Messages.DeletingStream, streamId, bucketId); streamId = _streamIdHasher.GetHash(streamId); try { return ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); cmd.AddParameter(_dialect.Items, itemCount); return cmd.ExecuteNonQuery(_dialect.SafeDeleteStream); }) > 0; } catch { return false; } } public void DeleteStreams(string bucketId, List<string> streamIds) { var streamIdsFormatted = string.Join(", ", streamIds); Logger.Warn(Messages.DeletingStreams, streamIdsFormatted, bucketId); var streamIdsQuery = streamIds.Select(streamId => $"'{_streamIdHasher.GetHash(streamId)}'").ToList(); var inQuery = $"({string.Join(", ", streamIdsQuery)})"; ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); return cmd.ExecuteNonQuery(string.Format(_dialect.DeleteStreams, inQuery)); }); } public IStreamIdHasher GetStreamIdHasher() { return _streamIdHasher; } public ISerialize GetSerializer() { return _serializer; } public virtual IEnumerable<ICommit> GetFrom(string checkpointToken) { LongCheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken); Logger.Debug(Messages.GettingAllCommitsFromCheckpoint, checkpointToken); return ExecuteQuery(query => { string statement = _dialect.GetCommitsFromCheckpoint; query.AddParameter(_dialect.CheckpointNumber, checkpoint.LongValue); return query.ExecutePagedQuery(statement, _dialect.NextPageDelegate) .Select(x => x.GetCommit(_serializer, _dialect)); }); } public bool IsDisposed { get { return _disposed; } } protected virtual void Dispose(bool disposing) { if (!disposing || _disposed) { return; } Logger.Debug(Messages.ShuttingDownPersistence); _disposed = true; } protected virtual void OnPersistCommit(IDbStatement cmd, CommitAttempt attempt) { } private ICommit PersistCommit(CommitAttempt attempt) { Logger.Debug(Messages.AttemptingToCommit, attempt.Events.Count, attempt.StreamId, attempt.CommitSequence, attempt.BucketId); string streamId = _streamIdHasher.GetHash(attempt.StreamId); return ExecuteCommand((connection, cmd) => { cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamIdOriginal, attempt.StreamId); cmd.AddParameter(_dialect.StreamRevision, attempt.StreamRevision); cmd.AddParameter(_dialect.Items, attempt.Events.Count); cmd.AddParameter(_dialect.CommitId, attempt.CommitId); cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence); cmd.AddParameter(_dialect.CommitStamp, attempt.CommitStamp); cmd.AddParameter(_dialect.Headers, _serializer.Serialize(attempt.Headers)); _dialect.AddPayloadParamater(_connectionFactory, connection, cmd, _serializer.Serialize(attempt.Events.ToList())); OnPersistCommit(cmd, attempt); var checkpointNumber = cmd.ExecuteScalar(_dialect.PersistCommit).ToLong(); return new Commit( attempt.BucketId, attempt.StreamId, attempt.StreamRevision, attempt.CommitId, attempt.CommitSequence, attempt.CommitStamp, checkpointNumber.ToString(CultureInfo.InvariantCulture), attempt.Headers, attempt.Events); }); } private bool DetectDuplicate(CommitAttempt attempt) { string streamId = _streamIdHasher.GetHash(attempt.StreamId); return ExecuteCommand(cmd => { cmd.AddParameter(_dialect.BucketId, attempt.BucketId, DbType.AnsiString); cmd.AddParameter(_dialect.StreamId, streamId, DbType.AnsiString); cmd.AddParameter(_dialect.CommitId, attempt.CommitId); cmd.AddParameter(_dialect.CommitSequence, attempt.CommitSequence); object value = cmd.ExecuteScalar(_dialect.DuplicateCommit); return (value is long ? (long)value : (int)value) > 0; }); } protected virtual IEnumerable<T> ExecuteQuery<T>(Func<IDbStatement, IEnumerable<T>> query) { ThrowWhenDisposed(); TransactionScope scope = OpenQueryScope(); IDbConnection connection = null; IDbTransaction transaction = null; IDbStatement statement = null; try { connection = _connectionFactory.Open(); transaction = _dialect.OpenTransaction(connection); statement = _dialect.BuildStatement(scope, connection, transaction); statement.PageSize = _pageSize; Logger.Verbose(Messages.ExecutingQuery); return query(statement); } catch (Exception e) { if (statement != null) { statement.Dispose(); } if (transaction != null) { transaction.Dispose(); } if (connection != null) { connection.Dispose(); } if (scope != null) { scope.Dispose(); } Logger.Debug(Messages.StorageThrewException, e.GetType()); if (e is StorageUnavailableException) { throw; } throw new StorageException(e.Message, e); } } protected virtual TransactionScope OpenQueryScope() { return OpenCommandScope() ?? new TransactionScope(TransactionScopeOption.Suppress); } private void ThrowWhenDisposed() { if (!_disposed) { return; } Logger.Warn(Messages.AlreadyDisposed); throw new ObjectDisposedException(Messages.AlreadyDisposed); } private T ExecuteCommand<T>(Func<IDbStatement, T> command) { return ExecuteCommand((_, statement) => command(statement)); } protected virtual T ExecuteCommand<T>(Func<IDbConnection, IDbStatement, T> command) { ThrowWhenDisposed(); using (TransactionScope scope = OpenCommandScope()) using (IDbConnection connection = _connectionFactory.Open()) using (IDbTransaction transaction = _dialect.OpenTransaction(connection)) using (IDbStatement statement = _dialect.BuildStatement(scope, connection, transaction)) { try { Logger.Verbose(Messages.ExecutingCommand); T rowsAffected = command(connection, statement); Logger.Verbose(Messages.CommandExecuted, rowsAffected); if (transaction != null) { transaction.Commit(); } if (scope != null) { scope.Complete(); } return rowsAffected; } catch (Exception e) { Logger.Debug(Messages.StorageThrewException, e.GetType()); if (!RecoverableException(e)) { throw new StorageException(e.Message, e); } Logger.Info(Messages.RecoverableExceptionCompletesScope); if (scope != null) { scope.Complete(); } throw; } } } protected virtual TransactionScope OpenCommandScope() { return new TransactionScope(_scopeOption); } private static bool RecoverableException(Exception e) { return e is UniqueKeyViolationException || e is StorageUnavailableException; } private class StreamIdHasherValidator : IStreamIdHasher { private readonly IStreamIdHasher _streamIdHasher; private const int MaxStreamIdHashLength = 40; public StreamIdHasherValidator(IStreamIdHasher streamIdHasher) { if (streamIdHasher == null) { throw new ArgumentNullException("streamIdHasher"); } _streamIdHasher = streamIdHasher; } public string GetHash(string streamId) { if (string.IsNullOrWhiteSpace(streamId)) { throw new ArgumentException(Messages.StreamIdIsNullEmptyOrWhiteSpace); } string streamIdHash = _streamIdHasher.GetHash(streamId); if (string.IsNullOrWhiteSpace(streamIdHash)) { throw new InvalidOperationException(Messages.StreamIdHashIsNullEmptyOrWhiteSpace); } if (streamIdHash.Length > MaxStreamIdHashLength) { throw new InvalidOperationException(Messages.StreamIdHashTooLong.FormatWith(streamId, streamIdHash, streamIdHash.Length, MaxStreamIdHashLength)); } return streamIdHash; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. 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 osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Lists; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Configuration; using osu.Game.Extensions; using osu.Game.Input.Bindings; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Timing; using osu.Game.Rulesets.UI.Scrolling.Algorithms; namespace osu.Game.Rulesets.UI.Scrolling { /// <summary> /// A type of <see cref="DrawableRuleset{TObject}"/> that supports a <see cref="ScrollingPlayfield"/>. /// <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/> will scroll within the playfield. /// </summary> public abstract class DrawableScrollingRuleset<TObject> : DrawableRuleset<TObject>, IKeyBindingHandler<GlobalAction> where TObject : HitObject { /// <summary> /// The default span of time visible by the length of the scrolling axes. /// This is clamped between <see cref="time_span_min"/> and <see cref="time_span_max"/>. /// </summary> private const double time_span_default = 1500; /// <summary> /// The minimum span of time that may be visible by the length of the scrolling axes. /// </summary> private const double time_span_min = 50; /// <summary> /// The maximum span of time that may be visible by the length of the scrolling axes. /// </summary> private const double time_span_max = 20000; /// <summary> /// The step increase/decrease of the span of time visible by the length of the scrolling axes. /// </summary> private const double time_span_step = 200; protected readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); /// <summary> /// The span of time that is visible by the length of the scrolling axes. /// For example, only hit objects with start time less than or equal to 1000 will be visible with <see cref="TimeRange"/> = 1000. /// </summary> protected readonly BindableDouble TimeRange = new BindableDouble(time_span_default) { Default = time_span_default, MinValue = time_span_min, MaxValue = time_span_max }; protected virtual ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Sequential; /// <summary> /// Whether the player can change <see cref="TimeRange"/>. /// </summary> protected virtual bool UserScrollSpeedAdjustment => true; /// <summary> /// Whether <see cref="TimingControlPoint"/> beat lengths should scale relative to the most common beat length in the <see cref="Beatmap"/>. /// </summary> protected virtual bool RelativeScaleBeatLengths => false; /// <summary> /// The <see cref="MultiplierControlPoint"/>s that adjust the scrolling rate of <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/>. /// </summary> protected readonly SortedList<MultiplierControlPoint> ControlPoints = new SortedList<MultiplierControlPoint>(Comparer<MultiplierControlPoint>.Default); protected IScrollingInfo ScrollingInfo => scrollingInfo; [Cached(Type = typeof(IScrollingInfo))] private readonly LocalScrollingInfo scrollingInfo; protected DrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset, beatmap, mods) { scrollingInfo = new LocalScrollingInfo(); scrollingInfo.Direction.BindTo(Direction); scrollingInfo.TimeRange.BindTo(TimeRange); } [BackgroundDependencyLoader] private void load() { switch (VisualisationMethod) { case ScrollVisualisationMethod.Sequential: scrollingInfo.Algorithm = new SequentialScrollAlgorithm(ControlPoints); break; case ScrollVisualisationMethod.Overlapping: scrollingInfo.Algorithm = new OverlappingScrollAlgorithm(ControlPoints); break; case ScrollVisualisationMethod.Constant: scrollingInfo.Algorithm = new ConstantScrollAlgorithm(); break; } double lastObjectTime = Objects.LastOrDefault()?.GetEndTime() ?? double.MaxValue; double baseBeatLength = TimingControlPoint.DEFAULT_BEAT_LENGTH; if (RelativeScaleBeatLengths) { IReadOnlyList<TimingControlPoint> timingPoints = Beatmap.ControlPointInfo.TimingPoints; double maxDuration = 0; for (int i = 0; i < timingPoints.Count; i++) { if (timingPoints[i].Time > lastObjectTime) break; double endTime = i < timingPoints.Count - 1 ? timingPoints[i + 1].Time : lastObjectTime; double duration = endTime - timingPoints[i].Time; if (duration > maxDuration) { maxDuration = duration; // The slider multiplier is post-multiplied to determine the final velocity, but for relative scale beat lengths // the multiplier should not affect the effective timing point (the longest in the beatmap), so it is factored out here baseBeatLength = timingPoints[i].BeatLength / Beatmap.Difficulty.SliderMultiplier; } } } // Merge sequences of timing and difficulty control points to create the aggregate "multiplier" control point var lastTimingPoint = new TimingControlPoint(); var lastEffectPoint = new EffectControlPoint(); var allPoints = new SortedList<ControlPoint>(Comparer<ControlPoint>.Default); allPoints.AddRange(Beatmap.ControlPointInfo.TimingPoints); allPoints.AddRange(Beatmap.ControlPointInfo.EffectPoints); // Generate the timing points, making non-timing changes use the previous timing change and vice-versa var timingChanges = allPoints.Select(c => { switch (c) { case TimingControlPoint timingPoint: lastTimingPoint = timingPoint; break; case EffectControlPoint difficultyPoint: lastEffectPoint = difficultyPoint; break; } return new MultiplierControlPoint(c.Time) { Velocity = Beatmap.Difficulty.SliderMultiplier, BaseBeatLength = baseBeatLength, TimingPoint = lastTimingPoint, EffectPoint = lastEffectPoint }; }); // Trim unwanted sequences of timing changes timingChanges = timingChanges // Collapse sections after the last hit object .Where(s => s.StartTime <= lastObjectTime) // Collapse sections with the same start time .GroupBy(s => s.StartTime).Select(g => g.Last()).OrderBy(s => s.StartTime); ControlPoints.AddRange(timingChanges); if (ControlPoints.Count == 0) ControlPoints.Add(new MultiplierControlPoint { Velocity = Beatmap.Difficulty.SliderMultiplier }); } protected override void LoadComplete() { base.LoadComplete(); if (!(Playfield is ScrollingPlayfield)) throw new ArgumentException($"{nameof(Playfield)} must be a {nameof(ScrollingPlayfield)} when using {nameof(DrawableScrollingRuleset<TObject>)}."); } /// <summary> /// Adjusts the scroll speed of <see cref="HitObject"/>s. /// </summary> /// <param name="amount">The amount to adjust by. Greater than 0 if the scroll speed should be increased, less than 0 if it should be decreased.</param> protected virtual void AdjustScrollSpeed(int amount) => this.TransformBindableTo(TimeRange, TimeRange.Value - amount * time_span_step, 200, Easing.OutQuint); public bool OnPressed(KeyBindingPressEvent<GlobalAction> e) { if (!UserScrollSpeedAdjustment) return false; switch (e.Action) { case GlobalAction.IncreaseScrollSpeed: scheduleScrollSpeedAdjustment(1); return true; case GlobalAction.DecreaseScrollSpeed: scheduleScrollSpeedAdjustment(-1); return true; } return false; } private ScheduledDelegate scheduledScrollSpeedAdjustment; public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e) { scheduledScrollSpeedAdjustment?.Cancel(); scheduledScrollSpeedAdjustment = null; } private void scheduleScrollSpeedAdjustment(int amount) { scheduledScrollSpeedAdjustment?.Cancel(); scheduledScrollSpeedAdjustment = this.BeginKeyRepeat(Scheduler, () => AdjustScrollSpeed(amount)); } private class LocalScrollingInfo : IScrollingInfo { public IBindable<ScrollingDirection> Direction { get; } = new Bindable<ScrollingDirection>(); public IBindable<double> TimeRange { get; } = new BindableDouble(); public IScrollAlgorithm Algorithm { get; set; } } } }
using System; using System.IO; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; using Cirrus; namespace Xamarin.Parse.Json { public sealed class JsonReader { TextReader input; bool eof; uint row, col; public static Future<T> Read<T> (string fileName) { return Read<T> (new FileStream (fileName, FileMode.Open)); } public static Future<T> Read<T> (Stream stream) { return Read<T> (stream, typeof (T)); } public static Future<T> Read<T> (Stream stream, Type type) { return JsonReader.Parse<T> (new StreamReader (new BufferedStream (stream)), type); } public static Future<T> ReadKey<T> (Stream stream, string key) { return JsonReader.ParseKey<T> (new StreamReader (new BufferedStream (stream)), key); } public static Future<T> Parse<T> (string json) { return JsonReader.Parse<T> (new StringReader (json)); } public static Future<T> ParseKey<T> (string json, string key) { return JsonReader.ParseKey<T> (new StringReader (json), key); } public static Future<T> Parse<T> (TextReader json) { return Parse<T> (json, typeof (T)); } public static Future<T> Parse<T> (TextReader json, Type type) { var jso = new JsonReader (json); return As<T> (jso.Parse (type).Wait ()); } public static Future<T> ParseKey<T> (TextReader json, string key) { var jso = new JsonReader (json); return As<T> (jso.ParseObjectForKey (typeof (T), key).Wait ()); } //lil helper static T As<T> (object obj) { var srcType = obj.GetType (); var destType = typeof (T); if (destType.IsAssignableFrom (srcType)) return (T)obj; return (T)Convert.ChangeType (obj, destType); } private JsonReader (TextReader input) { this.input = input; } Future<object> Parse (Type typeHint) { var la = Peek (); /* value: * string * number * object * array * true * false * null */ if (la == '"') return ParseString (); if (char.IsDigit (la) || la == '-') return ParseNumber (typeHint); if (la == '{') return ParseObject (typeHint); if (la == '[') return ParseArray (typeHint); if (la == 't') { Consume ("true"); return true; } if (la == 'f') { Consume ("false"); return false; } if (la == 'n') { Consume ("null"); return new Future<object> { Value = null }; } Err ("unexpected '{0}'", la); return null; } string ParseString () { var next = Peek (); var sb = new StringBuilder (); var escaped = false; int unicodeShift = -1; int unicodeSeq = 0; if (next != '"') Err ("expected string"); Consume (); next = Consume (); while (next != '"' || escaped) { if (!escaped && next == '\\') { escaped = true; } else if (unicodeShift >= 0) { if (char.IsDigit (next)) unicodeSeq |= unchecked((int)(next - 48)) << unicodeShift; else if (char.IsLetter (next)) unicodeSeq |= unchecked((int)(char.ToUpperInvariant (next) - 65) + 10) << unicodeShift; else Err ("malformed Unicode escape sequence"); unicodeShift -= 4; if (unicodeShift < 0) { sb.Append ((char)unicodeSeq); unicodeSeq = 0; } } else if (escaped) { if (next == 'u') { unicodeShift = 12; } else { switch (next) { case 'a' : next = '\a'; break; case 'b' : next = '\b'; break; case 'f' : next = '\f'; break; case 'n' : next = '\n'; break; case 'r' : next = '\r'; break; case 't' : next = '\t'; break; case 'v' : next = '\v'; break; } sb.Append (next); } escaped = false; } else { sb.Append (next); } next = Consume (); } if (unicodeShift >= 0) Err ("malformed Unicode escape sequence"); return sb.ToString (); } object ParseNumber (Type typeHint) { /* number: * int * int frac * int exp * int frac exp */ var next = Peek (); var sb = new StringBuilder (); while (char.IsDigit (next) || next == '-' || next == '.' || next == 'e' || next == 'E') { Consume (); sb.Append (next); next = Peek (true); } var result = double.Parse (sb.ToString ()); var resultType = GetWorkingType (typeHint); if (resultType != null) { if (resultType.IsEnum) return Enum.ToObject (resultType, Convert.ChangeType (result, Enum.GetUnderlyingType (resultType))); if (IsNumeric (resultType)) return Convert.ChangeType (result, resultType); } return result; } Future<object> ParseObject (Type typeHint) { object result = null; var adapter = JsonAdapter.ForType (typeHint); var next = Peek (); if (next != '{') Err ("expected object literal"); Consume (); if (typeHint != null) result = Activator.CreateInstance (typeHint); next = Peek (); while (next != '}') { var key = ParseString (); Consume (':'); var value = Parse (adapter == null ? null : adapter.GetValueType (result, key)).Wait (); if (adapter != null) adapter.SetKey (result, key, value).Wait (); next = Peek (); if (next != '}') Consume (','); } Consume ('}'); return result; } Future<object> ParseObjectForKey (Type valueHint, string searchKey) { var next = Peek (); if (next != '{') Err ("expected object literal"); Consume (); next = Peek (); while (next != '}') { var key = ParseString (); Consume (':'); if (key == searchKey) return Parse (valueHint).Wait (); else Parse ((Type)null).Wait (); next = Peek (); if (next != '}') Consume (','); } Consume ('}'); return null; } Future<object> ParseArray (Type typeHint) { object result = null; var adapter = JsonAdapter.ForType (typeHint); var next = Peek (); if (next != '[') Err ("expected array literal"); Consume (); if (typeHint != null) result = Activator.CreateInstance (GetWorkingType (typeHint)); int i = 0; next = Peek (); while (next != ']') { var value = Parse (adapter == null ? null : adapter.GetValueType (result, i.ToString ())).Wait (); if (adapter != null) adapter.SetKey (result, i.ToString (), value).Wait (); i++; next = Peek (); if (next != ']') Consume (','); } Consume (']'); if (typeHint != null && typeHint.IsArray) { typeHint = typeHint.GetElementType (); var list = (ArrayList)result; var array = Array.CreateInstance (typeHint, i); for (var j = 0; j < i; j++) array.SetValue (Convert.ChangeType (list [j], typeHint), j); return array; } return result; } // scanner primitives: void Consume (string expected) { for (var i = 0; i < expected.Length; i++) { var actual = Peek (true); if (eof || actual != expected [i]) Err ("expected '{0}'", expected); Consume (); } } void Consume (char expected) { var actual = Peek (); if (eof || actual != expected) Err ("expected '{0}'", expected); while (Consume () != actual) { col++; /* eat whitespace */ } col++; } char Consume () { var r = input.Read (); if (r == -1) { Err ("unexpected EOF"); } col++; return (char)r; } char Peek () { return Peek (false); } char Peek (bool whitespaceSignificant) { top: var p = input.Peek (); if (p == -1) { eof = true; return (char)0; } var la = (char)p; if (!whitespaceSignificant) { if (la == '\r') { input.Read (); if (((char)input.Peek ()) == '\n') input.Read (); col = 1; row++; goto top; } if (la == '\n') { input.Read (); col = 1; row++; goto top; } if (char.IsWhiteSpace (la)) { Consume (); goto top; } } return la; } static Type GetWorkingType (Type typeHint) { if (typeHint == null) return null; if (typeHint.IsArray) typeHint = typeof (ArrayList); if (typeHint.IsGenericType && typeHint.GetGenericTypeDefinition () == typeof(Nullable<>)) return typeHint.GetGenericArguments () [0]; return typeHint; } static bool IsNumeric (Type typ) { switch ((int)Type.GetTypeCode (typ)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return true; }; return false; } void Err (string message, params object [] args) { // Do not try to recover with Consume() as that can cause a stack overflow if we are at EOF //Consume (); throw new JsonParseException (row, col - 1, string.Format (message, args)); } } public class JsonParseException : Exception { public uint Row { get; private set; } public uint Column { get; private set; } public string InnerMessage { get; private set; } public JsonParseException (uint row, uint col, string message) : base (string.Format ("At ({0},{1}): {2}", row, col, message)) { this.Row = row; this.Column = col; this.InnerMessage = message; } } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem.Implementation; using System; using System.Collections.Generic; using System.Linq; namespace Bridge.Translator { public partial class ConstructorBlock { protected virtual IEnumerable<string> GetEventsAndAutoStartupMethods() { var methods = this.StaticBlock ? this.TypeInfo.StaticMethods : this.TypeInfo.InstanceMethods; List<string> list = new List<string>(); bool hasReadyAttribute; var isGenericType = this.IsGenericType(); foreach (var methodGroup in methods) { foreach (var method in methodGroup.Value) { var isGenericMethod = this.IsGenericMethod(method); HandleAttributes(list, methodGroup, method, out hasReadyAttribute); if (hasReadyAttribute) { if (isGenericType || isGenericMethod) { hasReadyAttribute = false; } } else { if (this.StaticBlock && !hasReadyAttribute) { if (method.Name == CS.Methods.AUTO_STARTUP_METHOD_NAME && method.HasModifier(Modifiers.Static) && !method.HasModifier(Modifiers.Abstract) && Helpers.IsEntryPointCandidate(this.Emitter, method)) { if (isGenericType || isGenericMethod) { LogAutoStartupWarning(method); } } } } if (hasReadyAttribute) { this.HasEntryPoint = true; } } } return list; } private void HandleAttributes(List<string> list, KeyValuePair<string, List<MethodDeclaration>> methodGroup, MethodDeclaration method, out bool hasReadyAttribute) { hasReadyAttribute = false; var isGenericType = this.IsGenericType(); var isGenericMethod = this.IsGenericMethod(method); foreach (var attrSection in method.Attributes) { foreach (var attr in attrSection.Attributes) { var resolveResult = this.Emitter.Resolver.ResolveNode(attr, this.Emitter) as InvocationResolveResult; if (resolveResult != null) { if (resolveResult.Type.FullName == CS.Attributes.READY_ATTRIBUTE_NAME) { hasReadyAttribute = true; if (isGenericType || isGenericMethod) { LogAutoStartupWarning(method); continue; } } var baseTypes = resolveResult.Type.GetAllBaseTypes().ToArray(); if (baseTypes.Any(t => t.FullName == "Bridge.AdapterAttribute")) { if (methodGroup.Value.Count > 1) { throw new EmitterException(attr, "Overloaded method cannot be event handler"); } var staticFlagField = resolveResult.Type.GetFields(f => f.Name == "StaticOnly"); if (staticFlagField.Count() > 0) { var staticValue = staticFlagField.First().ConstantValue; if (staticValue is bool && ((bool)staticValue) && !method.HasModifier(Modifiers.Static)) { throw new EmitterException(attr, resolveResult.Type.FullName + " can be applied for static methods only"); } } string eventName = methodGroup.Key; var eventField = resolveResult.Type.GetFields(f => f.Name == "Event"); if (eventField.Count() > 0) { eventName = eventField.First().ConstantValue.ToString(); } string format = null; string formatName = this.StaticBlock ? "Format" : "FormatScope"; var formatField = resolveResult.Type.GetFields(f => f.Name == formatName, GetMemberOptions.IgnoreInheritedMembers); if (formatField.Count() > 0) { format = formatField.First().ConstantValue.ToString(); } else { for (int i = baseTypes.Length - 1; i >= 0; i--) { formatField = baseTypes[i].GetFields(f => f.Name == formatName); if (formatField.Count() > 0) { format = formatField.First().ConstantValue.ToString(); break; } } } bool isCommon = false; var commonField = resolveResult.Type.GetFields(f => f.Name == "IsCommonEvent"); if (commonField.Count() > 0) { isCommon = Convert.ToBoolean(commonField.First().ConstantValue); } if (isCommon) { var eventArg = attr.Arguments.First(); var primitiveArg = eventArg as ICSharpCode.NRefactory.CSharp.PrimitiveExpression; if (primitiveArg != null) { eventName = primitiveArg.Value.ToString(); } else { var memberArg = eventArg as MemberReferenceExpression; if (memberArg != null) { var memberResolveResult = this.Emitter.Resolver.ResolveNode(memberArg, this.Emitter) as MemberResolveResult; if (memberResolveResult != null) { eventName = this.Emitter.GetEntityName(memberResolveResult.Member); } } } } int selectorIndex = isCommon ? 1 : 0; string selector = null; if (attr.Arguments.Count > selectorIndex) { selector = ((ICSharpCode.NRefactory.CSharp.PrimitiveExpression)(attr.Arguments.ElementAt(selectorIndex))).Value.ToString(); } else { var resolvedmethod = resolveResult.Member as IMethod; if (resolvedmethod.Parameters.Count > selectorIndex) { selector = resolvedmethod.Parameters[selectorIndex].ConstantValue.ToString(); } } if (attr.Arguments.Count > (selectorIndex + 1)) { var memberResolveResult = this.Emitter.Resolver.ResolveNode(attr.Arguments.ElementAt(selectorIndex + 1), this.Emitter) as MemberResolveResult; if (memberResolveResult != null && memberResolveResult.Member.Attributes.Count > 0) { var template = this.Emitter.Validator.GetAttribute(memberResolveResult.Member.Attributes, "Bridge.TemplateAttribute"); if (template != null) { selector = string.Format(template.PositionalArguments.First().ConstantValue.ToString(), selector); } } } else { var resolvedmethod = resolveResult.Member as IMethod; if (resolvedmethod.Parameters.Count > (selectorIndex + 1)) { var templateType = resolvedmethod.Parameters[selectorIndex + 1].Type; var templateValue = Convert.ToInt32(resolvedmethod.Parameters[selectorIndex + 1].ConstantValue); var fields = templateType.GetFields(f => { var field = f as DefaultResolvedField; if (field != null && field.ConstantValue != null && Convert.ToInt32(field.ConstantValue.ToString()) == templateValue) { return true; } var field1 = f as DefaultUnresolvedField; if (field1 != null && field1.ConstantValue != null && Convert.ToInt32(field1.ConstantValue.ToString()) == templateValue) { return true; } return false; }, GetMemberOptions.IgnoreInheritedMembers); if (fields.Count() > 0) { var template = this.Emitter.Validator.GetAttribute(fields.First().Attributes, "Bridge.TemplateAttribute"); if (template != null) { selector = string.Format(template.PositionalArguments.First().ConstantValue.ToString(), selector); } } } } list.Add(string.Format(format, eventName, selector, this.Emitter.GetEntityName(method))); } } } } } private void LogWarning(string message) { var logger = this.Emitter.Log as Bridge.Translator.Logging.Logger; bool? wrappingValue = null; if (logger != null && logger.UseTimeStamp) { wrappingValue = logger.UseTimeStamp; logger.UseTimeStamp = false; } this.Emitter.Log.Warn(message); if (wrappingValue.HasValue) { logger.UseTimeStamp = wrappingValue.Value; } } private void LogAutoStartupWarning(MethodDeclaration method) { this.LogWarning(string.Format("'{0}.{1}': an entry point cannot be generic or in a generic type", this.TypeInfo.Type.ReflectionName, method.Name)); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Net30Extension.cs" company="Xsd2Code"> // N/A // </copyright> // <summary> // Implements code generation extension for .Net Framework 3.0 // </summary> // <remarks> // Updated 2010-01-20 Deerwood McCord Jr. Cleaned CodeSnippetStatements by replacing with specific CodeDom Expressions // </remarks> // -------------------------------------------------------------------------------------------------------------------- namespace Xsd2Code.Library.Extensions { using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Xml.Schema; using Helpers; /// <summary> /// Implements code generation extension for .Net Framework 3.0 /// </summary> [CodeExtension(TargetFramework.Net30)] public class Net30Extension : CodeExtension { #region Private Fields /// <summary> /// List the properties that will change to auto properties /// </summary> private readonly List<CodeMemberProperty> autoPropertyListField = new List<CodeMemberProperty>(); /// <summary> /// List the fields to be deleted /// </summary> private readonly List<CodeMemberField> fieldListToRemoveField = new List<CodeMemberField>(); /// <summary> /// List fields that require an initialization in the constructor /// </summary> private readonly List<string> fieldWithAssignementInCtorListField = new List<string>(); #endregion #region Protected methods /// <summary> /// Processes the class. /// </summary> /// <param name="codeNamespace">The code namespace.</param> /// <param name="schema">The input XSD schema.</param> /// <param name="type">Represents a type declaration for a class, structure, interface, or enumeration</param> protected override void ProcessClass(CodeNamespace codeNamespace, XmlSchema schema, CodeTypeDeclaration type) { this.autoPropertyListField.Clear(); this.fieldListToRemoveField.Clear(); this.fieldWithAssignementInCtorListField.Clear(); // looks for properties that can not become automatic property CodeConstructor ctor = null; foreach (CodeTypeMember member in type.Members) { if (member is CodeConstructor) ctor = member as CodeConstructor; } if (ctor != null) { foreach (var statement in ctor.Statements) { var codeAssignStatement = statement as CodeAssignStatement; if (codeAssignStatement == null) continue; var code = codeAssignStatement.Left as CodeFieldReferenceExpression; if (code != null) { this.fieldWithAssignementInCtorListField.Add(code.FieldName); } } } base.ProcessClass(codeNamespace, schema, type); // generate automatic properties this.GenerateAutomaticProperties(type); } /// <summary> /// Create data contract attribute /// </summary> /// <param name="type">Code type declaration</param> /// <param name="schema">XML schema</param> protected override void CreateDataContractAttribute(CodeTypeDeclaration type, XmlSchema schema) { base.CreateDataContractAttribute(type, schema); if (GeneratorContext.GeneratorParams.GenerateDataContracts) { var attributeType = new CodeTypeReference("System.Runtime.Serialization.DataContractAttribute"); var codeAttributeArgument = new List<CodeAttributeArgument>(); //var typeName = string.Concat('"', type.Name, '"'); //codeAttributeArgument.Add(new CodeAttributeArgument("Name", new CodeSnippetExpression(typeName))); codeAttributeArgument.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(type.Name))); if (!string.IsNullOrEmpty(schema.TargetNamespace)) { //var targetNamespace = string.Concat('\"', schema.TargetNamespace, '\"'); //codeAttributeArgument.Add(new CodeAttributeArgument("Namespace", new CodeSnippetExpression(targetNamespace))); codeAttributeArgument.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(schema.TargetNamespace))); } type.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType, codeAttributeArgument.ToArray())); } } /// <summary> /// Creates the data member attribute. /// </summary> /// <param name="prop">Represents a declaration for a property of a type.</param> protected override void CreateDataMemberAttribute(CodeMemberProperty prop) { base.CreateDataMemberAttribute(prop); if (GeneratorContext.GeneratorParams.GenerateDataContracts) { var attrib = new CodeTypeReference("System.Runtime.Serialization.DataMemberAttribute"); prop.CustomAttributes.Add(new CodeAttributeDeclaration(attrib)); } } /// <summary> /// Import namespaces /// </summary> /// <param name="code">Code namespace</param> protected override void ImportNamespaces(CodeNamespace code) { base.ImportNamespaces(code); if (GeneratorContext.GeneratorParams.GenerateDataContracts) code.Imports.Add(new CodeNamespaceImport("System.Runtime.Serialization")); } /// <summary> /// Property process /// </summary> /// <param name="type">Represents a type declaration for a class, structure, interface, or enumeration</param> /// <param name="ns">The namespace</param> /// <param name="member">Type members include fields, methods, properties, constructors and nested types</param> /// <param name="xmlElement">Represent the root element in schema</param> /// <param name="schema">XML Schema</param> protected override void ProcessProperty(CodeTypeDeclaration type, CodeNamespace ns, CodeTypeMember member, XmlSchemaAnnotated xmlAnnotated, XmlSchema schema) { // Get now if property is array before base.ProcessProperty call. var prop = (CodeMemberProperty)member; base.ProcessProperty(type, ns, member, xmlAnnotated, schema); // Generate automatic properties. if (GeneratorContext.GeneratorParams.Language == GenerationLanguage.CSharp) { if (GeneratorContext.GeneratorParams.PropertyParams.AutomaticProperties) { bool excludeType = false; // Exclude collection type if (CollectionTypesFields.IndexOf(prop.Name) == -1) { // Get private fieldName var propReturnStatment = prop.GetStatements[0] as CodeMethodReturnStatement; if (propReturnStatment != null) { var field = propReturnStatment.Expression as CodeFieldReferenceExpression; if (field != null) { // Check if private field don't need initialization in constructor (default value). if (this.fieldWithAssignementInCtorListField.FindIndex(p => p == field.FieldName) == -1) { this.autoPropertyListField.Add(member as CodeMemberProperty); } } } } } } } /// <summary> /// process Fields. /// </summary> /// <param name="member">CodeTypeMember member</param> /// <param name="ctor">CodeMemberMethod constructor</param> /// <param name="ns">CodeNamespace XSD</param> /// <param name="addedToConstructor">Indicates if create a new constructor</param> protected override void ProcessFields(CodeTypeMember member, CodeMemberMethod ctor, CodeNamespace ns, XmlSchemaAnnotated xmlType, ref bool addedToConstructor) { // Get now if filed is array before base.ProcessProperty call. var field = (CodeMemberField)member; bool isArray = field.Type.ArrayElementType != null; base.ProcessFields(member, ctor, ns, xmlType, ref addedToConstructor); // Generate automatic properties. if (GeneratorContext.GeneratorParams.Language == GenerationLanguage.CSharp) { if (GeneratorContext.GeneratorParams.PropertyParams.AutomaticProperties) { if (!isArray) { bool found; if (!this.IsComplexType(field.Type, ns, out found)) { if (found) { // If this field is not assigned in constructor, add it in remove list. // with automatic property, don't need to keep private field. if (this.fieldWithAssignementInCtorListField.FindIndex(p => p == field.Name) == -1) { this.fieldListToRemoveField.Add(field); } } } } } } } #endregion #region static methods /// <summary> /// Outputs the attribute argument. /// </summary> /// <param name="arg">Represents an argument used in a metadata attribute declaration.</param> /// <returns>transform attribute into srting</returns> private static string AttributeArgumentToString(CodeAttributeArgument arg) { var strWriter = new StringWriter(); var provider = CodeDomProviderFactory.GetProvider(GeneratorContext.GeneratorParams.Language); if (!string.IsNullOrEmpty(arg.Name)) { strWriter.Write(arg.Name); strWriter.Write("="); } provider.GenerateCodeFromExpression(arg.Value, strWriter, new CodeGeneratorOptions()); var strrdr = new StringReader(strWriter.ToString()); return strrdr.ReadToEnd(); } #endregion /// <summary> /// Outputs the attribute argument. /// </summary> /// <param name="arg">Represents an argument used in a metadata attribute declaration.</param> /// <returns>transform attribute into string</returns> private static string ExpressionToString(CodeExpression arg) { var strWriter = new StringWriter(); var provider = CodeDomProviderFactory.GetProvider(GeneratorContext.GeneratorParams.Language); provider.GenerateCodeFromExpression(arg, strWriter, new CodeGeneratorOptions()); var strrdr = new StringReader(strWriter.ToString()); return strrdr.ReadToEnd(); } #region Private methods /// <summary> /// Generates the automatic properties. /// </summary> /// <param name="type">Represents a type declaration for a class, structure, interface, or enumeration.</param> private void GenerateAutomaticProperties(CodeTypeDeclaration type) { if (Equals(GeneratorContext.GeneratorParams.Language, GenerationLanguage.CSharp)) { // If databinding is disable, use automatic property if (GeneratorContext.GeneratorParams.PropertyParams.AutomaticProperties) { foreach (var item in this.autoPropertyListField) { var cm = new CodeSnippetTypeMember(); bool transformToAutomaticproperty = true; var attributesString = new List<string>(); foreach (var attribute in item.CustomAttributes) { var attrib = attribute as CodeAttributeDeclaration; if (attrib != null) { // Don't transform property with default value. if (attrib.Name == "System.ComponentModel.DefaultValueAttribute") { transformToAutomaticproperty = false; } else { string attributesArguments = string.Empty; foreach (var arg in attrib.Arguments) { var argument = arg as CodeAttributeArgument; if (argument != null) { attributesArguments += AttributeArgumentToString(argument) + ","; } } // Remove last "," if (attributesArguments.Length > 0) attributesArguments = attributesArguments.Remove(attributesArguments.Length - 1); attributesString.Add(string.Format("[{0}({1})]", attrib.Name, attributesArguments)); } } } if (transformToAutomaticproperty) { foreach (var attribute in attributesString) { cm.Text += " " + attribute + "\n"; } var ct = new CodeTypeReferenceExpression(item.Type); var prop = ExpressionToString(ct); var text = string.Format(" public {0} {1} ", prop, item.Name); cm.Text += string.Concat(text, "{get; set;}\n"); cm.Comments.AddRange(item.Comments); type.Members.Add(cm); type.Members.Remove(item); } } // Now remove all private fields foreach (var item in this.fieldListToRemoveField) { if (item.Name == "mailClassField" && type.Name == "uspsSummaryType") { ; } type.Members.Remove(item); } } } } #endregion } }
// // Authors: // Miguel de Icaza // // Copyright 2011 Xamarin Inc. // Copyright 2009-2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using Mono.Options; #if !MONOMAC using MonoTouch.ObjCRuntime; #endif class BindingTouch { #if MONOMAC static string baselibdll = "MonoMac.dll"; static string RootNS = "MonoMac"; static Type CoreObject = typeof (MonoMac.Foundation.NSObject); static string tool_name = "bmac"; static string compiler = "gmcs"; #else static string baselibdll = "/Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll"; static string RootNS = "MonoTouch"; static Type CoreObject = typeof (MonoTouch.Foundation.NSObject); static string tool_name = "btouch"; static string compiler = "/Developer/MonoTouch/usr/bin/smcs"; #endif static void ShowHelp (OptionSet os) { Console.WriteLine ("{0} - Mono Objective-C API binder", tool_name); Console.WriteLine ("Usage is:\n {0} [options] apifile1.cs [apifileN] [-s=core1.cs [-s=core2.cs]] [-x=extra1.cs [-x=extra2.cs]]", tool_name); os.WriteOptionDescriptions (Console.Out); } static int Main (string [] args) { bool show_help = false; bool alpha = false; string basedir = null; string tmpdir = null; string ns = null; string outfile = null; bool delete_temp = true, debug = false; bool verbose = false; bool unsafef = false; bool external = false; bool pmode = true; List<string> sources; var resources = new List<string> (); #if !MONOMAC var linkwith = new List<string> (); #endif var references = new List<string> (); var libs = new List<string> (); var core_sources = new List<string> (); var extra_sources = new List<string> (); var defines = new List<string> (); bool binding_third_party = true; string generate_file_list = null; var os = new OptionSet () { { "h|?|help", "Displays the help", v => show_help = true }, { "a", "Include alpha bindings", v => alpha = true }, { "outdir=", "Sets the output directory for the temporary binding files", v => { basedir = v; }}, { "o|out=", "Sets the name of the output library", v => outfile = v }, { "tmpdir=", "Sets the working directory for temp files", v => { tmpdir = v; delete_temp = false; }}, { "debug", "Generates a debugging build of the binding", v => debug = true }, { "sourceonly=", "Only generates the source", v => generate_file_list = v }, { "ns=", "Sets the namespace for storing helper classes", v => ns = v }, { "unsafe", "Sets the unsafe flag for the build", v=> unsafef = true }, #if MONOMAC { "core", "Use this to build monomac.dll", v => binding_third_party = false }, #else { "core", "Use this to build monotouch.dll", v => binding_third_party = false }, #endif { "r=", "Adds a reference", v => references.Add (v) }, { "lib=", "Adds the directory to the search path for the compiler", v => libs.Add (v) }, { "d=", "Defines a symbol", v => defines.Add (v) }, { "s=", "Adds a source file required to build the API", v => core_sources.Add (v) }, { "v", "Sets verbose mode", v => verbose = true }, { "x=", "Adds the specified file to the build, used after the core files are compiled", v => extra_sources.Add (v) }, { "e", "Sets external mode", v => external = true }, { "p", "Sets private mode", v => pmode = false }, { "baselib=", "Sets the base library", v => baselibdll = v }, #if !MONOMAC { "link-with=,", "Link with a native library {0:FILE} to the binding, embedded as a resource named {1:ID}", (path, id) => { if (path == null || path.Length == 0) throw new Exception ("-link-with=FILE,ID requires a filename."); if (id == null || id.Length == 0) throw new Exception ("-link-with=FILE,ID requires a resource id."); if (linkwith.Contains (id)) throw new Exception ("-link-with=FILE,ID cannot assign the same resource id to multiple libraries."); resources.Add (string.Format ("-res:{0},{1}", path, id)); linkwith.Add (id); } }, #endif }; try { sources = os.Parse (args); } catch (Exception e){ Console.Error.WriteLine ("{0}: {1}", tool_name, e.Message); Console.Error.WriteLine ("see {0} --help for more information", tool_name); return 1; } if (show_help || sources.Count == 0){ Console.WriteLine ("Error: no api file provided"); ShowHelp (os); return 0; } if (alpha) defines.Add ("ALPHA"); if (tmpdir == null) tmpdir = GetWorkDir (); if (outfile == null) outfile = Path.GetFileNameWithoutExtension (sources [0]) + ".dll"; string refs = (references.Count > 0 ? "-r:" + String.Join (" -r:", references.ToArray ()) : ""); string paths = (libs.Count > 0 ? "-lib:" + String.Join (" -lib:", libs.ToArray ()) : ""); try { var api_file = sources [0]; var tmpass = Path.Combine (tmpdir, "temp.dll"); // -nowarn:436 is to avoid conflicts in definitions between core.dll and the sources var cargs = String.Format ("-unsafe -target:library {0} -nowarn:436 -out:{1} -r:{2} {3} {4} {5} -r:{6} {7} {8}", string.Join (" ", sources.ToArray ()), tmpass, Environment.GetCommandLineArgs ()[0], string.Join (" ", core_sources.ToArray ()), refs, unsafef ? "-unsafe" : "", baselibdll, string.Join (" ", defines.Select (x=> "-define:" + x).ToArray ()), paths); var si = new ProcessStartInfo (compiler, cargs) { UseShellExecute = false, }; if (verbose) Console.WriteLine ("{0} {1}", si.FileName, si.Arguments); var p = Process.Start (si); p.WaitForExit (); if (p.ExitCode != 0){ Console.WriteLine ("{0}: API binding contains errors.", tool_name); return 1; } Assembly api; try { api = Assembly.LoadFrom (tmpass); } catch (Exception e) { if (verbose) Console.WriteLine (e); Console.Error.WriteLine ("Error loading API definition from {0}", tmpass); return 1; } Assembly baselib; try { baselib = Assembly.LoadFrom (baselibdll); } catch (Exception e){ if (verbose) Console.WriteLine (e); Console.Error.WriteLine ("Error loading base library {0}", baselibdll); return 1; } #if !MONOMAC foreach (object attr in api.GetCustomAttributes (typeof (LinkWithAttribute), true)) { LinkWithAttribute linkWith = (LinkWithAttribute) attr; if (!linkwith.Contains (linkWith.LibraryName)) { Console.Error.WriteLine ("Missing native library {0}, please use `--link-with' to specify the path to this library.", linkWith.LibraryName); return 1; } } #endif var types = new List<Type> (); foreach (var t in api.GetTypes ()){ if (t.GetCustomAttributes (typeof (BaseTypeAttribute), true).Length > 0) types.Add (t); } var g = new Generator (pmode, external, debug, types.ToArray ()){ MessagingNS = ns == null ? Path.GetFileNameWithoutExtension (api_file) : ns, CoreMessagingNS = RootNS + ".ObjCRuntime", BindThirdPartyLibrary = binding_third_party, CoreNSObject = CoreObject, BaseDir = basedir != null ? basedir : tmpdir, #if MONOMAC OnlyX86 = true, #endif Alpha = alpha }; foreach (var mi in baselib.GetType (RootNS + ".ObjCRuntime.Messaging").GetMethods ()){ if (mi.Name.IndexOf ("_objc_msgSend") != -1) g.RegisterMethodName (mi.Name); } g.Go (); if (generate_file_list != null){ using (var f = File.CreateText (generate_file_list)){ g.GeneratedFiles.ForEach (x => f.WriteLine (x)); } return 0; } cargs = String.Format ("-unsafe -target:library -out:{0} {1} -r:{7} {2} {3} {4} {5} {6} -r:{7} {8} {9}", outfile, string.Join (" ", defines.Select (x=> "-define:" + x).ToArray ()), String.Join (" ", g.GeneratedFiles.ToArray ()), String.Join (" ", core_sources.ToArray ()), String.Join (" ", sources.Skip (1).ToArray ()), refs, unsafef ? "-unsafe" : "", baselibdll, String.Join (" ", resources.ToArray ()), String.Join (" ", extra_sources.ToArray ()) ); si = new ProcessStartInfo (compiler, cargs) { UseShellExecute = false, }; if (verbose) Console.WriteLine ("{0} {1}", si.FileName, si.Arguments); p = Process.Start (si); p.WaitForExit (); if (p.ExitCode != 0){ Console.WriteLine ("{0}: API binding contains errors.", tool_name); return 1; } } finally { if (delete_temp) Directory.Delete (tmpdir, true); } return 0; } static string GetWorkDir () { while (true){ string p = Path.Combine (Path.GetTempPath(), Path.GetRandomFileName()); if (Directory.Exists (p)) continue; var di = Directory.CreateDirectory (p); return di.FullName; } } }
// ------------------------------------------------------------------------------ // 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. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt 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 ThumbnailRequest. /// </summary> public partial class ThumbnailRequest : BaseRequest, IThumbnailRequest { /// <summary> /// Constructs a new ThumbnailRequest. /// </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 ThumbnailRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Thumbnail using POST. /// </summary> /// <param name="thumbnailToCreate">The Thumbnail to create.</param> /// <returns>The created Thumbnail.</returns> public System.Threading.Tasks.Task<Thumbnail> CreateAsync(Thumbnail thumbnailToCreate) { return this.CreateAsync(thumbnailToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Thumbnail using POST. /// </summary> /// <param name="thumbnailToCreate">The Thumbnail to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Thumbnail.</returns> public async System.Threading.Tasks.Task<Thumbnail> CreateAsync(Thumbnail thumbnailToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Thumbnail>(thumbnailToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Thumbnail. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Thumbnail. /// </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<Thumbnail>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Thumbnail. /// </summary> /// <returns>The Thumbnail.</returns> public System.Threading.Tasks.Task<Thumbnail> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Thumbnail. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Thumbnail.</returns> public async System.Threading.Tasks.Task<Thumbnail> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Thumbnail>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Thumbnail using PATCH. /// </summary> /// <param name="thumbnailToUpdate">The Thumbnail to update.</param> /// <returns>The updated Thumbnail.</returns> public System.Threading.Tasks.Task<Thumbnail> UpdateAsync(Thumbnail thumbnailToUpdate) { return this.UpdateAsync(thumbnailToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Thumbnail using PATCH. /// </summary> /// <param name="thumbnailToUpdate">The Thumbnail to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Thumbnail.</returns> public async System.Threading.Tasks.Task<Thumbnail> UpdateAsync(Thumbnail thumbnailToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Thumbnail>(thumbnailToUpdate, 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 IThumbnailRequest 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 IThumbnailRequest Expand(Expression<Func<Thumbnail, 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 IThumbnailRequest 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 IThumbnailRequest Select(Expression<Func<Thumbnail, 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="thumbnailToInitialize">The <see cref="Thumbnail"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Thumbnail thumbnailToInitialize) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace Projac.Tests { [TestFixture] public class ProjectionHandlerEnumeratorTests { [Test] public void HandlersCanNotBeNull() { Assert.Throws<ArgumentNullException>( () => new ProjectionHandlerEnumerator<object>(null)); } [Test] public void DisposeDoesNotThrow() { Assert.DoesNotThrow(() => new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0])); } [TestCaseSource("MoveNextCases")] public void MoveNextReturnsExpectedResult( ProjectionHandlerEnumerator<object> sut, bool expected) { var result = sut.MoveNext(); Assert.That(result, Is.EqualTo(expected)); } private static IEnumerable<TestCaseData> MoveNextCases() { //No handlers var enumerator1 = new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0]); yield return new TestCaseData(enumerator1, false); yield return new TestCaseData(enumerator1, false); //idempotency check //1 handler var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator2, true); yield return new TestCaseData(enumerator2, false); yield return new TestCaseData(enumerator2, false); //idempotency check //2 handlers var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()), HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator3, true); yield return new TestCaseData(enumerator3, true); yield return new TestCaseData(enumerator3, false); yield return new TestCaseData(enumerator3, false); //idempotency check } [TestCaseSource("MoveNextAfterResetCases")] public void MoveNextAfterResetReturnsExpectedResult( ProjectionHandlerEnumerator<object> sut, bool expected) { sut.Reset(); var result = sut.MoveNext(); Assert.That(result, Is.EqualTo(expected)); } private static IEnumerable<TestCaseData> MoveNextAfterResetCases() { //No handlers var enumerator1 = new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0]); yield return new TestCaseData(enumerator1, false); yield return new TestCaseData(enumerator1, false); //1 handler var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator2, true); yield return new TestCaseData(enumerator2, true); //2 handlers var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()), HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator3, true); yield return new TestCaseData(enumerator3, true); } [TestCaseSource("ResetCases")] public void ResetDoesNotThrow(ProjectionHandlerEnumerator<object> sut) { Assert.DoesNotThrow(sut.Reset); } private static IEnumerable<TestCaseData> ResetCases() { //No handlers var enumerator1 = new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0]); yield return new TestCaseData(enumerator1); //1 handler var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator2); //2 handlers var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()), HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator3); } [TestCaseSource("CurrentNotStartedCases")] public void CurrentReturnsExpectedResultWhenNotStarted( ProjectionHandlerEnumerator<object> sut) { Assert.Throws<InvalidOperationException>( () => { var _ = sut.Current; }); } [TestCaseSource("CurrentNotStartedCases")] public void EnumeratorCurrentReturnsExpectedResultWhenNotStarted( IEnumerator sut) { Assert.Throws<InvalidOperationException>( () => { var _ = sut.Current; }); } private static IEnumerable<TestCaseData> CurrentNotStartedCases() { //No handlers var enumerator1 = new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0]); yield return new TestCaseData(enumerator1); //1 handler var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator2); //2 handlers var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()), HandlerFactory(TaskFactory()) }); yield return new TestCaseData(enumerator3); } [TestCaseSource("CurrentCompletedCases")] public void CurrentReturnsExpectedResultWhenCompleted( ProjectionHandlerEnumerator<object> sut) { Assert.Throws<InvalidOperationException>( () => { var _ = sut.Current; }); } [TestCaseSource("CurrentCompletedCases")] public void EnumeratorCurrentReturnsExpectedResultWhenCompleted( IEnumerator sut) { Assert.Throws<InvalidOperationException>( () => { var _ = sut.Current; }); } private static IEnumerable<TestCaseData> CurrentCompletedCases() { //No handlers var enumerator1 = new ProjectionHandlerEnumerator<object>(new ProjectionHandler<object>[0]); while (enumerator1.MoveNext()) { } yield return new TestCaseData(enumerator1); //1 handler var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()) }); while (enumerator2.MoveNext()) { } yield return new TestCaseData(enumerator2); //2 handlers var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(TaskFactory()), HandlerFactory(TaskFactory()) }); while (enumerator3.MoveNext()) { } yield return new TestCaseData(enumerator3); } [TestCaseSource("CurrentStartedCases")] public void CurrentReturnsExpectedResultWhenStarted( ProjectionHandlerEnumerator<object> sut, Task expected) { sut.MoveNext(); var result = sut.Current.Handler(null, null, CancellationToken.None); Assert.That(result, Is.EqualTo(expected)); } [TestCaseSource("CurrentStartedCases")] public void EnumeratorCurrentReturnsExpectedResultWhenStarted( IEnumerator sut, Task expected) { sut.MoveNext(); var result = ((ProjectionHandler<object>)sut.Current).Handler(null, null, CancellationToken.None); Assert.That(result, Is.EqualTo(expected)); } private static IEnumerable<TestCaseData> CurrentStartedCases() { //No handlers - not applicable //1 handler var task1 = TaskFactory(); var enumerator2 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(task1) }); yield return new TestCaseData(enumerator2, task1); //2 handlers var task2 = TaskFactory(); var task3 = TaskFactory(); var enumerator3 = new ProjectionHandlerEnumerator<object>(new[] { HandlerFactory(task2), HandlerFactory(task3) }); yield return new TestCaseData(enumerator3, task2); yield return new TestCaseData(enumerator3, task3); } private static ProjectionHandler<object> HandlerFactory(Task task) { return new ProjectionHandler<object>( typeof(object), (_, __, ___) => task); } private static Task TaskFactory() { return Task.FromResult<object>(null); } } }
//#define ASTARDEBUG using UnityEngine; using System.Collections; namespace Pathfinding.Voxels { /** \astarpro */ public class Utility { public static Color[] colors = new Color[7] {Color.green,Color.blue,Color.red,Color.yellow,Color.cyan, Color.white, Color.black}; public static Color GetColor (int i) { while (i >= colors.Length) { i -= colors.Length; } while (i < 0) { i += colors.Length; } return colors[i]; } public static int Bit (int a, int b) { return (a & (1 << b)) >> b; } public static Color IntToColor (int i, float a) { int r = Bit(i, 1) + Bit(i, 3) * 2 + 1; int g = Bit(i, 2) + Bit(i, 4) * 2 + 1; int b = Bit(i, 0) + Bit(i, 5) * 2 + 1; return new Color (r*0.25F,g*0.25F,b*0.25F,a); } //For the real value, divide by 2 public static float TriangleArea2 (Vector3 a, Vector3 b, Vector3 c) { return Mathf.Abs (a.x*b.z+b.x*c.z+c.x*a.z-a.x*c.z-c.x*b.z-b.x*a.z); } //public static float TriangleArea (Vector2 a, Vector2 b, Vector2 c) { // return Mathf.Abs (a.x*b.y+b.x*c.y+c.x*a.y-a.x*c.y-c.x*b.y-b.x*a.y); //} public static float TriangleArea (Vector3 a, Vector3 b, Vector3 c) { return (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z); } //Derived from the above function //public static float TriangleArea (Vector2 p, Vector3 a, Vector3 b, Vector3 c) { //} public static float Min (float a, float b, float c) { a = a < b ? a : b; return a < c ? a : c; } public static float Max (float a, float b, float c) { a = a > b ? a : b; return a > c ? a : c; } public static int Max (int a, int b, int c, int d) { a = a > b ? a : b; a = a > c ? a : c; return a > d ? a : d; } public static int Min (int a, int b, int c, int d) { a = a < b ? a : b; a = a < c ? a : c; return a < d ? a : d; } public static float Max (float a, float b, float c, float d) { a = a > b ? a : b; a = a > c ? a : c; return a > d ? a : d; } public static float Min (float a, float b, float c, float d) { a = a < b ? a : b; a = a < c ? a : c; return a < d ? a : d; } public static string ToMillis (float v) { return (v*1000).ToString ("0"); } public static float lastStartTime; public static void StartTimer () { lastStartTime = Time.realtimeSinceStartup; } public static void EndTimer (string label) { Debug.Log (label+", process took "+ToMillis(Time.realtimeSinceStartup-lastStartTime)+"ms to complete"); } public static float lastAdditiveTimerStart; public static float additiveTimer; public static void StartTimerAdditive (bool reset) { if (reset) { additiveTimer = 0; } lastAdditiveTimerStart = Time.realtimeSinceStartup; } public static void EndTimerAdditive (string label, bool log) { additiveTimer += Time.realtimeSinceStartup-lastAdditiveTimerStart; if (log) { Debug.Log (label+", process took "+ToMillis(additiveTimer)+"ms to complete"); } lastAdditiveTimerStart = Time.realtimeSinceStartup; } public static void CopyVector (float[] a, int i, Vector3 v) { a[i] = v.x; a[i+1] = v.y; a[i+2] = v.z; } private static float[] clipPolygonCache = new float[7*3]; private static int[] clipPolygonIntCache = new int[7*3]; public static int ClipPoly(float[] vIn, int n, float[] vOut, float pnx, float pnz, float pd) { float[] d = clipPolygonCache; for (int i = 0; i < n; ++i) d[i] = pnx*vIn[i*3+0] + pnz*vIn[i*3+2] + pd; int m = 0; for (int i = 0, j = n-1; i < n; j=i, ++i) { bool ina = d[j] >= 0; bool inb = d[i] >= 0; if (ina != inb) { float s = d[j] / (d[j] - d[i]); vOut[m*3+0] = vIn[j*3+0] + (vIn[i*3+0] - vIn[j*3+0])*s; vOut[m*3+1] = vIn[j*3+1] + (vIn[i*3+1] - vIn[j*3+1])*s; vOut[m*3+2] = vIn[j*3+2] + (vIn[i*3+2] - vIn[j*3+2])*s; m++; } if (inb) { vOut[m*3+0] = vIn[i*3+0]; vOut[m*3+1] = vIn[i*3+1]; vOut[m*3+2] = vIn[i*3+2]; m++; } } return m; } public static int ClipPolygon (float[] vIn, int n, float[] vOut, float multi, float offset, int axis) { float[] d = clipPolygonCache; for (int i=0;i<n;i++) { d[i] = multi*vIn[i*3+axis]+offset; } //Number of resulting vertices int m = 0; for (int i=0, j = n-1; i < n; j=i, i++) { bool prev = d[j] >= 0; bool curr = d[i] >= 0; if (prev != curr) { int m3 = m*3; int i3 = i*3; int j3 = j*3; float s = d[j] / (d[j] - d[i]); vOut[m3+0] = vIn[j3+0] + (vIn[i3+0]-vIn[j3+0])*s; vOut[m3+1] = vIn[j3+1] + (vIn[i3+1]-vIn[j3+1])*s; vOut[m3+2] = vIn[j3+2] + (vIn[i3+2]-vIn[j3+2])*s; //vOut[m*3+0] = vIn[j*3+0] + (vIn[i*3+0]-vIn[j*3+0])*s; //vOut[m*3+1] = vIn[j*3+1] + (vIn[i*3+1]-vIn[j*3+1])*s; //vOut[m*3+2] = vIn[j*3+2] + (vIn[i*3+2]-vIn[j*3+2])*s; m++; } if (curr) { int m3 = m*3; int i3 = i*3; vOut[m3+0] = vIn[i3+0]; vOut[m3+1] = vIn[i3+1]; vOut[m3+2] = vIn[i3+2]; m++; } } return m; } public static int ClipPolygonY (float[] vIn, int n, float[] vOut, float multi, float offset, int axis) { float[] d = clipPolygonCache; for (int i=0;i<n;i++) { d[i] = multi*vIn[i*3+axis]+offset; } //Number of resulting vertices int m = 0; for (int i=0, j = n-1; i < n; j=i, i++) { bool prev = d[j] >= 0; bool curr = d[i] >= 0; if (prev != curr) { vOut[m*3+1] = vIn[j*3+1] + (vIn[i*3+1]-vIn[j*3+1]) * (d[j] / (d[j] - d[i])); m++; } if (curr) { vOut[m*3+1] = vIn[i*3+1]; m++; } } return m; } public static int ClipPolygon (Vector3[] vIn, int n, Vector3[] vOut, float multi, float offset, int axis) { float[] d = clipPolygonCache; for (int i=0;i<n;i++) { d[i] = multi*vIn[i][axis]+offset; } //Number of resulting vertices int m = 0; for (int i=0, j = n-1; i < n; j=i, i++) { bool prev = d[j] >= 0; bool curr = d[i] >= 0; if (prev != curr) { float s = d[j] / (d[j] - d[i]); vOut[m] = vIn[j] + (vIn[i]-vIn[j])*s; m++; } if (curr) { vOut[m] = vIn[i]; m++; } } return m; } public static int ClipPolygon (Int3[] vIn, int n, Int3[] vOut, int multi, int offset, int axis) { int[] d = clipPolygonIntCache; for (int i=0;i<n;i++) { d[i] = multi*vIn[i][axis]+offset; } //Number of resulting vertices int m = 0; for (int i=0, j = n-1; i < n; j=i, i++) { bool prev = d[j] >= 0; bool curr = d[i] >= 0; if (prev != curr) { double s = (double)d[j] / (d[j] - d[i]); vOut[m] = vIn[j] + (vIn[i]-vIn[j])*s; m++; } if (curr) { vOut[m] = vIn[i]; m++; } } return m; } public static bool IntersectXAxis (out Vector3 intersection,Vector3 start1,Vector3 dir1,float x) { float den = dir1.x; if (den == 0) { intersection = Vector3.zero; return false; } float nom = x-start1.x; float u = nom/den; u = Mathf.Clamp01 (u); intersection = start1 + dir1*u; return true; } public static bool IntersectZAxis (out Vector3 intersection,Vector3 start1,Vector3 dir1,float z) { float den = -dir1.z; if (den == 0) { intersection = Vector3.zero; return false; } float nom = start1.z-z; float u = nom/den; u = Mathf.Clamp01 (u); intersection = start1 + dir1*u; return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.PowerShell; using Dbg = System.Diagnostics.Debug; using System.Management.Automation.Language; namespace System.Management.Automation { /// <summary> /// This class represents the compiled metadata for a parameter set. /// </summary> public sealed class ParameterSetMetadata { #region Private Data private bool _isMandatory; private int _position; private bool _valueFromPipeline; private bool _valueFromPipelineByPropertyName; private bool _valueFromRemainingArguments; private string _helpMessage; private string _helpMessageBaseName; private string _helpMessageResourceId; #endregion #region Constructor /// <summary> /// </summary> /// <param name="psMD"></param> internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD) { Dbg.Assert(psMD != null, "ParameterSetSpecificMetadata cannot be null"); Initialize(psMD); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterSetMetadata object. /// </summary> /// <param name="other">Object to copy.</param> internal ParameterSetMetadata(ParameterSetMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } _helpMessage = other._helpMessage; _helpMessageBaseName = other._helpMessageBaseName; _helpMessageResourceId = other._helpMessageResourceId; _isMandatory = other._isMandatory; _position = other._position; _valueFromPipeline = other._valueFromPipeline; _valueFromPipelineByPropertyName = other._valueFromPipelineByPropertyName; _valueFromRemainingArguments = other._valueFromRemainingArguments; } #endregion #region Public Properties /// <summary> /// Returns true if the parameter is mandatory for this parameterset, false otherwise. /// </summary> /// <value></value> public bool IsMandatory { get { return _isMandatory; } set { _isMandatory = value; } } /// <summary> /// If the parameter is allowed to be positional for this parameter set, this returns /// the position it is allowed to be in. If it is not positional, this returns int.MinValue. /// </summary> /// <value></value> public int Position { get { return _position; } set { _position = value; } } /// <summary> /// Specifies that this parameter can take values from the incoming pipeline object. /// </summary> public bool ValueFromPipeline { get { return _valueFromPipeline; } set { _valueFromPipeline = value; } } /// <summary> /// Specifies that this parameter can take values from a property from the incoming /// pipeline object with the same name as the parameter. /// </summary> public bool ValueFromPipelineByPropertyName { get { return _valueFromPipelineByPropertyName; } set { _valueFromPipelineByPropertyName = value; } } /// <summary> /// Specifies if this parameter takes all the remaining unbound /// arguments that were specified. /// </summary> /// <value></value> public bool ValueFromRemainingArguments { get { return _valueFromRemainingArguments; } set { _valueFromRemainingArguments = value; } } /// <summary> /// A short description for this parameter, suitable for presentation as a tool tip. /// </summary> public string HelpMessage { get { return _helpMessage; } set { _helpMessage = value; } } /// <summary> /// The base name of the resource for a help message. /// </summary> public string HelpMessageBaseName { get { return _helpMessageBaseName; } set { _helpMessageBaseName = value; } } /// <summary> /// The Id of the resource for a help message. /// </summary> public string HelpMessageResourceId { get { return _helpMessageResourceId; } set { _helpMessageResourceId = value; } } #endregion #region Private / Internal Methods & Properties /// <summary> /// </summary> /// <param name="psMD"></param> internal void Initialize(ParameterSetSpecificMetadata psMD) { _isMandatory = psMD.IsMandatory; _position = psMD.Position; _valueFromPipeline = psMD.ValueFromPipeline; _valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName; _valueFromRemainingArguments = psMD.ValueFromRemainingArguments; _helpMessage = psMD.HelpMessage; _helpMessageBaseName = psMD.HelpMessageBaseName; _helpMessageResourceId = psMD.HelpMessageResourceId; } /// <summary> /// Compares this instance with the supplied <paramref name="second"/>. /// </summary> /// <param name="second"> /// An object to compare this instance with /// </param> /// <returns> /// true if the metadata is same. false otherwise. /// </returns> internal bool Equals(ParameterSetMetadata second) { if ((_isMandatory != second._isMandatory) || (_position != second._position) || (_valueFromPipeline != second._valueFromPipeline) || (_valueFromPipelineByPropertyName != second._valueFromPipelineByPropertyName) || (_valueFromRemainingArguments != second._valueFromRemainingArguments) || (_helpMessage != second._helpMessage) || (_helpMessageBaseName != second._helpMessageBaseName) || (_helpMessageResourceId != second._helpMessageResourceId)) { return false; } return true; } #endregion #region Efficient serialization + rehydration logic [Flags] internal enum ParameterFlags : uint { Mandatory = 0x01, ValueFromPipeline = 0x02, ValueFromPipelineByPropertyName = 0x04, ValueFromRemainingArguments = 0x08, } internal ParameterFlags Flags { get { ParameterFlags flags = 0; if (IsMandatory) { flags = flags | ParameterFlags.Mandatory; } if (ValueFromPipeline) { flags = flags | ParameterFlags.ValueFromPipeline; } if (ValueFromPipelineByPropertyName) { flags = flags | ParameterFlags.ValueFromPipelineByPropertyName; } if (ValueFromRemainingArguments) { flags = flags | ParameterFlags.ValueFromRemainingArguments; } return flags; } set { this.IsMandatory = (ParameterFlags.Mandatory == (value & ParameterFlags.Mandatory)); this.ValueFromPipeline = (ParameterFlags.ValueFromPipeline == (value & ParameterFlags.ValueFromPipeline)); this.ValueFromPipelineByPropertyName = (ParameterFlags.ValueFromPipelineByPropertyName == (value & ParameterFlags.ValueFromPipelineByPropertyName)); this.ValueFromRemainingArguments = (ParameterFlags.ValueFromRemainingArguments == (value & ParameterFlags.ValueFromRemainingArguments)); } } /// <summary> /// Constructor used by rehydration. /// </summary> internal ParameterSetMetadata( int position, ParameterFlags flags, string helpMessage) { this.Position = position; this.Flags = flags; this.HelpMessage = helpMessage; } #endregion #region Proxy Parameter Generation private const string MandatoryFormat = @"{0}Mandatory=$true"; private const string PositionFormat = @"{0}Position={1}"; private const string ValueFromPipelineFormat = @"{0}ValueFromPipeline=$true"; private const string ValueFromPipelineByPropertyNameFormat = @"{0}ValueFromPipelineByPropertyName=$true"; private const string ValueFromRemainingArgumentsFormat = @"{0}ValueFromRemainingArguments=$true"; private const string HelpMessageFormat = @"{0}HelpMessage='{1}'"; /// <summary> /// </summary> /// <returns></returns> internal string GetProxyParameterData() { Text.StringBuilder result = new System.Text.StringBuilder(); string prefix = string.Empty; if (_isMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, MandatoryFormat, prefix); prefix = ", "; } if (_position != Int32.MinValue) { result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, _position); prefix = ", "; } if (_valueFromPipeline) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineFormat, prefix); prefix = ", "; } if (_valueFromPipelineByPropertyName) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineByPropertyNameFormat, prefix); prefix = ", "; } if (_valueFromRemainingArguments) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromRemainingArgumentsFormat, prefix); prefix = ", "; } if (!string.IsNullOrEmpty(_helpMessage)) { result.AppendFormat( CultureInfo.InvariantCulture, HelpMessageFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(_helpMessage)); prefix = ", "; } return result.ToString(); } #endregion } /// <summary> /// This class represents the compiled metadata for a parameter. /// </summary> public sealed class ParameterMetadata { #region Private Data private string _name; private Type _parameterType; private bool _isDynamic; private Dictionary<string, ParameterSetMetadata> _parameterSets; private Collection<string> _aliases; private Collection<Attribute> _attributes; #endregion #region Constructor /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name) : this(name, null) { } /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <param name="parameterType"> /// Type of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name, Type parameterType) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentNullException("name"); } _name = name; _parameterType = parameterType; _attributes = new Collection<Attribute>(); _aliases = new Collection<string>(); _parameterSets = new Dictionary<string, ParameterSetMetadata>(); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterMetadata object. /// Instances of Attribute and Type classes are copied by reference. /// </summary> /// <param name="other">Object to copy.</param> public ParameterMetadata(ParameterMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } _isDynamic = other._isDynamic; _name = other._name; _parameterType = other._parameterType; // deep copy _aliases = new Collection<string>(new List<string>(other._aliases.Count)); foreach (string alias in other._aliases) { _aliases.Add(alias); } // deep copy of the collection, collection items (Attributes) copied by reference if (other._attributes == null) { _attributes = null; } else { _attributes = new Collection<Attribute>(new List<Attribute>(other._attributes.Count)); foreach (Attribute attribute in other._attributes) { _attributes.Add(attribute); } } // deep copy _parameterSets = null; if (other._parameterSets == null) { _parameterSets = null; } else { _parameterSets = new Dictionary<string, ParameterSetMetadata>(other._parameterSets.Count); foreach (KeyValuePair<string, ParameterSetMetadata> entry in other._parameterSets) { _parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value)); } } } /// <summary> /// An internal constructor which constructs a ParameterMetadata object /// from compiled command parameter metadata. ParameterMetadata /// is a proxy written on top of CompiledCommandParameter. /// </summary> /// <param name="cmdParameterMD"> /// Internal CompiledCommandParameter metadata /// </param> internal ParameterMetadata(CompiledCommandParameter cmdParameterMD) { Dbg.Assert(cmdParameterMD != null, "CompiledCommandParameter cannot be null"); Initialize(cmdParameterMD); } /// <summary> /// Constructor used by implicit remoting. /// </summary> internal ParameterMetadata( Collection<string> aliases, bool isDynamic, string name, Dictionary<string, ParameterSetMetadata> parameterSets, Type parameterType) { _aliases = aliases; _isDynamic = isDynamic; _name = name; _parameterSets = parameterSets; _parameterType = parameterType; _attributes = new Collection<Attribute>(); } #endregion #region Public Methods/Properties /// <summary> /// Gets the name of the parameter. /// </summary> public string Name { get { return _name; } set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentNullException("Name"); } _name = value; } } /// <summary> /// Gets the Type information of the Parameter. /// </summary> public Type ParameterType { get { return _parameterType; } set { _parameterType = value; } } /// <summary> /// Gets the ParameterSets metadata that this parameter belongs to. /// </summary> public Dictionary<string, ParameterSetMetadata> ParameterSets { get { return _parameterSets; } } /// <summary> /// Specifies if the parameter is Dynamic. /// </summary> public bool IsDynamic { get { return _isDynamic; } set { _isDynamic = value; } } /// <summary> /// Specifies the alias names for this parameter. /// </summary> public Collection<string> Aliases { get { return _aliases; } } /// <summary> /// A collection of the attributes found on the member. /// </summary> public Collection<Attribute> Attributes { get { return _attributes; } } /// <summary> /// Specifies if the parameter is a SwitchParameter. /// </summary> public bool SwitchParameter { get { if (_parameterType != null) { return _parameterType.Equals(typeof(SwitchParameter)); } return false; } } /// <summary> /// Gets a dictionary of parameter metadata for the supplied <paramref name="type"/>. /// </summary> /// <param name="type"> /// CLR Type for which the parameter metadata is constructed. /// </param> /// <returns> /// A Dictionary of ParameterMetadata keyed by parameter name. /// null if no parameter metadata is found. /// </returns> /// <exception cref="ArgumentNullException"> /// type is null. /// </exception> public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type) { if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } CommandMetadata cmdMetaData = new CommandMetadata(type); Dictionary<string, ParameterMetadata> result = cmdMetaData.Parameters; // early GC. cmdMetaData = null; return result; } #endregion #region Internal Methods/Properties /// <summary> /// </summary> /// <param name="compiledParameterMD"></param> internal void Initialize(CompiledCommandParameter compiledParameterMD) { _name = compiledParameterMD.Name; _parameterType = compiledParameterMD.Type; _isDynamic = compiledParameterMD.IsDynamic; // Create parameter set metadata _parameterSets = new Dictionary<string, ParameterSetMetadata>(StringComparer.OrdinalIgnoreCase); foreach (string key in compiledParameterMD.ParameterSetData.Keys) { ParameterSetSpecificMetadata pMD = compiledParameterMD.ParameterSetData[key]; _parameterSets.Add(key, new ParameterSetMetadata(pMD)); } // Create aliases for this parameter _aliases = new Collection<string>(); foreach (string alias in compiledParameterMD.Aliases) { _aliases.Add(alias); } // Create attributes for this parameter _attributes = new Collection<Attribute>(); foreach (var attrib in compiledParameterMD.CompiledAttributes) { _attributes.Add(attrib); } } /// <summary> /// </summary> /// <param name="cmdParameterMetadata"></param> /// <returns></returns> internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { Dbg.Assert(cmdParameterMetadata != null, "cmdParameterMetadata cannot be null"); Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (var keyValuePair in cmdParameterMetadata.BindableParameters) { var key = keyValuePair.Key; var mergedCompiledPMD = keyValuePair.Value; ParameterMetadata parameterMetaData = new ParameterMetadata(mergedCompiledPMD.Parameter); result.Add(key, parameterMetaData); } return result; } internal bool IsMatchingType(PSTypeName psTypeName) { Type dotNetType = psTypeName.Type; if (dotNetType != null) { // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. bool parameterAcceptsObjects = ((int)(LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank)) >= (int)(ConversionRank.AssignableS2A); if (dotNetType.Equals(typeof(object))) { return parameterAcceptsObjects; } if (parameterAcceptsObjects) { return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); } // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. var conversionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType); if (conversionData != null) { if ((int)(conversionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A)) { return true; } } return false; } var wildcardPattern = WildcardPattern.Get( "*" + (psTypeName.Name ?? string.Empty), WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); if (wildcardPattern.IsMatch(this.ParameterType.FullName)) { return true; } if (this.ParameterType.IsArray && wildcardPattern.IsMatch((this.ParameterType.GetElementType().FullName))) { return true; } if (this.Attributes != null) { PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType<PSTypeNameAttribute>().FirstOrDefault(); if (typeNameAttribute != null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName)) { return true; } } return false; } #endregion #region Proxy Parameter generation // The formats are prefixed with {0} to enable easy formatting. private const string ParameterNameFormat = @"{0}${{{1}}}"; private const string ParameterTypeFormat = @"{0}[{1}]"; private const string ParameterSetNameFormat = "ParameterSetName='{0}'"; private const string AliasesFormat = @"{0}[Alias({1})]"; private const string ValidateLengthFormat = @"{0}[ValidateLength({1}, {2})]"; private const string ValidateRangeFloatFormat = @"{0}[ValidateRange({1:R}, {2:R})]"; private const string ValidateRangeFormat = @"{0}[ValidateRange({1}, {2})]"; private const string ValidatePatternFormat = "{0}[ValidatePattern('{1}')]"; private const string ValidateScriptFormat = @"{0}[ValidateScript({{ {1} }})]"; private const string ValidateCountFormat = @"{0}[ValidateCount({1}, {2})]"; private const string ValidateSetFormat = @"{0}[ValidateSet({1})]"; private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]"; private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]"; private const string AllowNullFormat = @"{0}[AllowNull()]"; private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]"; private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]"; private const string PSTypeNameFormat = @"{0}[PSTypeName('{1}')]"; private const string ObsoleteFormat = @"{0}[Obsolete({1})]"; private const string CredentialAttributeFormat = @"{0}[System.Management.Automation.CredentialAttribute()]"; /// <summary> /// </summary> /// <param name="prefix"> /// prefix that is added to every new-line. Used for tabbing content. /// </param> /// <param name="paramNameOverride"> /// The paramNameOverride is used as the parameter name if it is not null or empty. /// </param> /// <param name="isProxyForCmdlet"> /// The parameter is for a cmdlet and requires a Parameter attribute. /// </param> /// <returns></returns> internal string GetProxyParameterData(string prefix, string paramNameOverride, bool isProxyForCmdlet) { Text.StringBuilder result = new System.Text.StringBuilder(); if (_parameterSets != null && isProxyForCmdlet) { foreach (var pair in _parameterSets) { string parameterSetName = pair.Key; ParameterSetMetadata parameterSet = pair.Value; string paramSetData = parameterSet.GetProxyParameterData(); if (!string.IsNullOrEmpty(paramSetData) || !parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { string separator = string.Empty; result.Append(prefix); result.Append("[Parameter("); if (!parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { result.AppendFormat( CultureInfo.InvariantCulture, ParameterSetNameFormat, CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); separator = ", "; } if (!string.IsNullOrEmpty(paramSetData)) { result.Append(separator); result.Append(paramSetData); } result.Append(")]"); } } } if ((_aliases != null) && (_aliases.Count > 0)) { Text.StringBuilder aliasesData = new System.Text.StringBuilder(); string comma = string.Empty; // comma is not need for the first element foreach (string alias in _aliases) { aliasesData.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(alias)); comma = ","; } result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString()); } if ((_attributes != null) && (_attributes.Count > 0)) { foreach (Attribute attrib in _attributes) { string attribData = GetProxyAttributeData(attrib, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } } if (SwitchParameter) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch"); } else if (_parameterType != null) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType)); } /* 1. CredentialAttribute needs to go after the type * 2. To avoid risk, I don't want to move other attributes to go here / after the type */ CredentialAttribute credentialAttrib = _attributes.OfType<CredentialAttribute>().FirstOrDefault(); if (credentialAttrib != null) { string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } result.AppendFormat( CultureInfo.InvariantCulture, ParameterNameFormat, prefix, CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? _name : paramNameOverride)); return result.ToString(); } /// <summary> /// Generates proxy data for attributes like ValidateLength, ValidateRange etc. /// </summary> /// <param name="attrib"> /// Attribute to process. /// </param> /// <param name="prefix"> /// Prefix string to add. /// </param> /// <returns> /// Attribute's proxy string. /// </returns> private string GetProxyAttributeData(Attribute attrib, string prefix) { string result; ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute; if (validLengthAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateLengthFormat, prefix, validLengthAttrib.MinLength, validLengthAttrib.MaxLength); return result; } ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute; if (validRangeAttrib != null) { Type rangeType = validRangeAttrib.MinRange.GetType(); string format; if (rangeType == typeof(float) || rangeType == typeof(double)) { format = ValidateRangeFloatFormat; } else { format = ValidateRangeFormat; } result = string.Format(CultureInfo.InvariantCulture, format, prefix, validRangeAttrib.MinRange, validRangeAttrib.MaxRange); return result; } AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute; if (allowNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowNullFormat, prefix); return result; } AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute; if (allowEmptyStringAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyStringFormat, prefix); return result; } AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute; if (allowEmptyColAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyCollectionFormat, prefix); return result; } ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute; if (patternAttrib != null) { /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); string or = string.Empty; string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); foreach(string regexOption in regexOptionEnumValues) { System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse( typeof(System.Text.RegularExpressions.RegexOptions), regexOption, true); if ((option & patternAttrib.Options) == option) { tracer.WriteLine("Regex option {0} found", regexOption); regexOps.AppendFormat(CultureInfo.InvariantCulture, "{0}[System.Text.RegularExpressions.RegexOptions]::{1}", or, option.ToString() ); or = "|"; } }*/ result = string.Format(CultureInfo.InvariantCulture, ValidatePatternFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(patternAttrib.RegexPattern) /*,regexOps.ToString()*/); return result; } ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute; if (countAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength); return result; } ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute; if (notNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullFormat, prefix); return result; } ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute; if (notNullEmptyAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullOrEmptyFormat, prefix); return result; } ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; if (setAttrib != null) { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = string.Empty; foreach (string validValue in setAttrib.ValidValues) { values.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(validValue)); comma = ","; } result = string.Format(CultureInfo.InvariantCulture, ValidateSetFormat, prefix, values.ToString()/*, setAttrib.IgnoreCase*/); return result; } ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute; if (scriptAttrib != null) { // Talked with others and I think it is okay to use *unescaped* value from sb.ToString() // 1. implicit remoting is not bringing validation scripts across // 2. other places in code also assume that contents of a script block can be parsed // without escaping result = string.Format(CultureInfo.InvariantCulture, ValidateScriptFormat, prefix, scriptAttrib.ScriptBlock.ToString()); return result; } PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute; if (psTypeNameAttrib != null) { result = string.Format( CultureInfo.InvariantCulture, PSTypeNameFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(psTypeNameAttrib.PSTypeName)); return result; } ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute; if (obsoleteAttrib != null) { string parameters = string.Empty; if (obsoleteAttrib.IsError) { string message = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; parameters = message + ", $true"; } else if (obsoleteAttrib.Message != null) { parameters = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; } result = string.Format( CultureInfo.InvariantCulture, ObsoleteFormat, prefix, parameters); return result; } return null; } #endregion } /// <summary> /// The metadata associated with a bindable type. /// </summary> internal class InternalParameterMetadata { #region ctor /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified runtime-defined parameters. /// </summary> /// <param name="runtimeDefinedParameters"> /// The runtime-defined parameter collection that describes the parameters and their metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check for reserved parameter names. /// </param> /// <returns> /// An instance of the TypeMetadata for the specified runtime-defined parameters. The metadata /// is always constructed on demand and never cached. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); } return new InternalParameterMetadata(runtimeDefinedParameters, processingDynamicParameters, checkNames); } /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified type. /// </summary> /// <param name="type"> /// The type to get the metadata for. /// </param> /// <param name="context"> /// The current engine context. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <returns> /// An instance of the TypeMetadata for the specified type. The metadata may get /// constructed on-demand or may be retrieved from the cache. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal static InternalParameterMetadata Get(Type type, ExecutionContext context, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } InternalParameterMetadata result; if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) { result = new InternalParameterMetadata(type, processingDynamicParameters); if (context != null) { s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } } return result; } // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the metadata in the /// runtime-defined parameter collection. /// </summary> /// <param name="runtimeDefinedParameters"> /// The collection of runtime-defined parameters that declare the parameters and their /// metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameters"); } ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames); } // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the reflection information retrieved /// from the enclosing bindable object type. /// </summary> /// <param name="type"> /// The type information for the bindable object /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal InternalParameterMetadata(Type type, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } _type = type; TypeName = type.Name; ConstructCompiledParametersUsingReflection(processingDynamicParameters); } #endregion ctor /// <summary> /// Gets the type name of the bindable type. /// </summary> internal string TypeName { get; } = string.Empty; /// <summary> /// Gets a dictionary of the compiled parameter metadata for this Type. /// The dictionary keys are the names of the parameters (or aliases) and /// the values are the compiled parameter metadata. /// </summary> internal Dictionary<string, CompiledCommandParameter> BindableParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets a dictionary of the parameters that have been aliased to other names. The key is /// the alias name and the value is the CompiledCommandParameter metadata. /// </summary> internal Dictionary<string, CompiledCommandParameter> AliasedParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The type information for the class that implements the bindable object. /// This member is null in all cases except when constructed with using reflection /// against the Type. /// </summary> private Type _type; /// <summary> /// The flags used when reflecting against the object to create the metadata. /// </summary> internal static readonly BindingFlags metaDataBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); #region helper methods /// <summary> /// Fills in the data for an instance of this class using the specified runtime-defined parameters. /// </summary> /// <param name="runtimeDefinedParameters"> /// A description of the parameters and their metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> private void ConstructCompiledParametersUsingRuntimeDefinedParameters( RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { Diagnostics.Assert( runtimeDefinedParameters != null, "This method should only be called when constructed with a valid runtime-defined parameter collection"); foreach (RuntimeDefinedParameter parameterDefinition in runtimeDefinedParameters.Values) { // Create the compiled parameter and add it to the bindable parameters collection if (processingDynamicParameters) { // When processing dynamic parameters, parameter definitions come from the user, // Invalid data could be passed in, or the parameter could be actually disabled. if (parameterDefinition == null || parameterDefinition.IsDisabled()) { continue; } } CompiledCommandParameter parameter = new CompiledCommandParameter(parameterDefinition, processingDynamicParameters); AddParameter(parameter, checkNames); } } /// <summary> /// Compiles the parameter using reflection against the CLR type. /// </summary> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters) { Diagnostics.Assert( _type != null, "This method should only be called when constructed with the Type"); // Get the property and field info PropertyInfo[] properties = _type.GetProperties(metaDataBindingFlags); FieldInfo[] fields = _type.GetFields(metaDataBindingFlags); foreach (PropertyInfo property in properties) { // Check whether the property is a parameter if (!IsMemberAParameter(property)) { continue; } AddParameter(property, processingDynamicParameters); } foreach (FieldInfo field in fields) { // Check whether the field is a parameter if (!IsMemberAParameter(field)) { continue; } AddParameter(field, processingDynamicParameters); } } private void CheckForReservedParameter(string name) { if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase) || name.Equals("SelectObject", StringComparison.OrdinalIgnoreCase)) { throw new MetadataException( "ReservedParameterName", null, DiscoveryExceptions.ReservedParameterName, name); } } // This call verifies that the parameter is unique or // can be deemed unique. If not, an exception is thrown. // If it is unique (or deemed unique), then it is added // to the bindableParameters collection // private void AddParameter(MemberInfo member, bool processingDynamicParameters) { bool error = false; bool useExisting = false; CheckForReservedParameter(member.Name); do // false loop { CompiledCommandParameter existingParameter; if (!BindableParameters.TryGetValue(member.Name, out existingParameter)) { break; } Type existingParamDeclaringType = existingParameter.DeclaringType; if (existingParamDeclaringType == null) { error = true; break; } if (existingParamDeclaringType.IsSubclassOf(member.DeclaringType)) { useExisting = true; break; } if (member.DeclaringType.IsSubclassOf(existingParamDeclaringType)) { // Need to swap out the new member for the parameter definition // that is already defined. RemoveParameter(existingParameter); break; } error = true; } while (false); if (error) { // A duplicate parameter was found and could not be deemed unique // through inheritance. throw new MetadataException( "DuplicateParameterDefinition", null, ParameterBinderStrings.DuplicateParameterDefinition, member.Name); } if (!useExisting) { CompiledCommandParameter parameter = new CompiledCommandParameter(member, processingDynamicParameters); AddParameter(parameter, true); } } private void AddParameter(CompiledCommandParameter parameter, bool checkNames) { if (checkNames) { CheckForReservedParameter(parameter.Name); } BindableParameters.Add(parameter.Name, parameter); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { if (AliasedParameters.ContainsKey(alias)) { throw new MetadataException( "AliasDeclaredMultipleTimes", null, DiscoveryExceptions.AliasDeclaredMultipleTimes, alias); } AliasedParameters.Add(alias, parameter); } } private void RemoveParameter(CompiledCommandParameter parameter) { BindableParameters.Remove(parameter.Name); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { AliasedParameters.Remove(alias); } } /// <summary> /// Determines if the specified member represents a parameter based on its attributes. /// </summary> /// <param name="member"> /// The member to check to see if it is a parameter. /// </param> /// <returns> /// True if at least one ParameterAttribute is declared on the member, or false otherwise. /// </returns> /// <exception cref="MetadataException"> /// If GetCustomAttributes fails on <paramref name="member"/>. /// </exception> private static bool IsMemberAParameter(MemberInfo member) { try { var expAttribute = member.GetCustomAttributes<ExperimentalAttribute>(inherit: false).FirstOrDefault(); if (expAttribute != null && expAttribute.ToHide) { return false; } var hasAnyVisibleParamAttributes = false; var paramAttributes = member.GetCustomAttributes<ParameterAttribute>(inherit: false); foreach (var paramAttribute in paramAttributes) { if (!paramAttribute.ToHide) { hasAnyVisibleParamAttributes = true; break; } } return hasAnyVisibleParamAttributes; } catch (MetadataException metadataException) { throw new MetadataException( "GetCustomAttributesMetadataException", metadataException, Metadata.MetadataMemberInitialization, member.Name, metadataException.Message); } catch (ArgumentException argumentException) { throw new MetadataException( "GetCustomAttributesArgumentException", argumentException, Metadata.MetadataMemberInitialization, member.Name, argumentException.Message); } } #endregion helper methods #region Metadata cache /// <summary> /// The cache of the type metadata. The key for the cache is the Type.FullName. /// Note, this is a case-sensitive dictionary because Type names are case sensitive. /// </summary> private static System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata> s_parameterMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata>(StringComparer.Ordinal); #endregion Metadata cache } }
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. using UnityEditor; using UnityEngine; using HutongGames.PlayMaker; using System.Collections.Generic; namespace HutongGames.PlayMakerEditor { /// <summary> /// Custom inspector for PlayMakerFSM /// </summary> [CustomEditor(typeof(PlayMakerFSM))] public class FsmComponentInspector : UnityEditor.Editor { private static GUIContent restartOnEnableLabel = new GUIContent(Strings.Label_Reset_On_Disable, Strings.Tooltip_Reset_On_Disable); private static GUIContent showStateLabelLabel = new GUIContent(Strings.Label_Show_State_Label, Strings.Tooltip_Show_State_Label); private static GUIContent enableDebugFlowLabel = new GUIContent(Strings.FsmEditorSettings_Enable_DebugFlow, Strings.FsmEditorSettings_Enable_DebugFlow_Tooltip); //private static GUIContent quickLoadLabel = new GUIContent("Quick Load", "Skip data validation when loading FSM. Faster, but can fail if actions have changed since FSM was saved."); // Inspector targets private PlayMakerFSM fsmComponent; // Inspector target private FsmTemplate fsmTemplate; // template used by fsmComponent // Inspector foldout states private bool showControls = true; private bool showInfo; private bool showStates; private bool showEvents; private bool showVariables; // Collect easily editable references to fsmComponent.Fsm.Variables List<FsmVariable> fsmVariables = new List<FsmVariable>(); public void OnEnable() { fsmComponent = target as PlayMakerFSM; if (fsmComponent == null) return; // shouldn't happen fsmTemplate = fsmComponent.FsmTemplate; RefreshTemplate(); BuildFsmVariableList(); } public override void OnInspectorGUI() { if (fsmComponent == null) return; // shouldn't happen FsmEditorStyles.Init(); var fsm = fsmComponent.Fsm; // grab Fsm for convenience if (fsm.States.Length > 100) // a little arbitrary, but better than nothing! { EditorGUILayout.HelpBox("NOTE: Collapse this inspector for better editor performance with large FSMs.", MessageType.None); } // Edit FSM name EditorGUILayout.BeginHorizontal(); fsm.Name = EditorGUILayout.TextField(fsm.Name); if (GUILayout.Button(new GUIContent(Strings.Label_Edit, Strings.Tooltip_Edit_in_the_PlayMaker_Editor), GUILayout.MaxWidth(45))) { OpenInEditor(fsmComponent); GUIUtility.ExitGUI(); } EditorGUILayout.EndHorizontal(); // Edit FSM Template EditorGUILayout.BeginHorizontal(); var template = (FsmTemplate) EditorGUILayout.ObjectField(new GUIContent(Strings.Label_Use_Template, Strings.Tooltip_Use_Template), fsmComponent.FsmTemplate, typeof(FsmTemplate), false); if (template != fsmComponent.FsmTemplate) { SelectTemplate(template); } if (GUILayout.Button(new GUIContent(Strings.Label_Browse, Strings.Tooltip_Browse_Templates), GUILayout.MaxWidth(45))) { DoSelectTemplateMenu(); } EditorGUILayout.EndHorizontal(); // Disable GUI that can't be edited if referencing a template if (!Application.isPlaying && fsmComponent.FsmTemplate != null) { template = fsmComponent.FsmTemplate; fsm = template.fsm; GUI.enabled = false; } // Resave warning /* if (fsm.needsResave) { EditorGUI.BeginDisabledGroup(false); EditorGUILayout.HelpBox("NOTE: Action data has changed since FSM was saved. Please resave FSM to update actions.", MessageType.Warning); EditorGUI.EndDisabledGroup(); }*/ // Edit Description fsm.Description = FsmEditorGUILayout.TextAreaWithHint(fsm.Description, Strings.Label_Description___, GUILayout.MinHeight(60)); // Edit Help Url (lets the user link to documentation for the FSM) EditorGUILayout.BeginHorizontal(); fsm.DocUrl = FsmEditorGUILayout.TextFieldWithHint(fsm.DocUrl, Strings.Tooltip_Documentation_Url); var guiEnabled = GUI.enabled; GUI.enabled = !string.IsNullOrEmpty(fsm.DocUrl); if (FsmEditorGUILayout.HelpButton()) { Application.OpenURL(fsm.DocUrl); } EditorGUILayout.EndHorizontal(); GUI.enabled = guiEnabled; // Edit FSM Settings fsm.RestartOnEnable = GUILayout.Toggle(fsm.RestartOnEnable, restartOnEnableLabel); fsm.ShowStateLabel = GUILayout.Toggle(fsm.ShowStateLabel, showStateLabelLabel); fsm.EnableDebugFlow = GUILayout.Toggle(fsm.EnableDebugFlow, enableDebugFlowLabel); //fsm.QuickLoad = GUILayout.Toggle(fsm.QuickLoad, quickLoadLabel); // The rest of the GUI is readonly so we can check for changes here if (GUI.changed) { EditorUtility.SetDirty(fsmComponent); } // Controls Section GUI.enabled = true; // Show FSM variables with Inspector option checked FsmEditorGUILayout.LightDivider(); showControls = EditorGUILayout.Foldout(showControls, new GUIContent(Strings.Label_Controls, Strings.Tooltip_Controls), FsmEditorStyles.CategoryFoldout); if (showControls) { //EditorGUIUtility.LookLikeInspector(); BuildFsmVariableList(); foreach (var fsmVar in fsmVariables) { if (fsmVar.ShowInInspector) { EditorGUI.BeginChangeCheck(); fsmVar.DoValueGUI(new GUIContent(fsmVar.Name, fsmVar.Name + (!string.IsNullOrEmpty(fsmVar.Tooltip) ? ":\n" + fsmVar.Tooltip : ""))); if (EditorGUI.EndChangeCheck()) { fsmVar.UpdateVariableValue(); } } } if (GUI.changed) { FsmEditor.RepaintAll(); } } // Show events with Inspector option checked // These become buttons that the user can press to send the events if (showControls) { foreach (var fsmEvent in fsm.ExposedEvents) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(fsmEvent.Name); if (GUILayout.Button(fsmEvent.Name)) { fsm.Event(fsmEvent); FsmEditor.RepaintAll(); } GUILayout.EndHorizontal(); } } // Show general info about the FSM EditorGUI.indentLevel = 0; FsmEditorGUILayout.LightDivider(); showInfo = EditorGUILayout.Foldout(showInfo, Strings.Label_Info, FsmEditorStyles.CategoryFoldout); if (showInfo) { EditorGUI.indentLevel = 1; showStates = EditorGUILayout.Foldout(showStates, string.Format(Strings.Label_States_Count, fsm.States.Length)); if (showStates) { string states = ""; if (fsm.States.Length > 0) { foreach (var state in fsm.States) { states += FsmEditorStyles.tab2 + state.Name + FsmEditorStyles.newline; } states = states.Substring(0, states.Length - 1); } else { states = FsmEditorStyles.tab2 + Strings.Label_None_In_Table; } GUILayout.Label(states); } showEvents = EditorGUILayout.Foldout(showEvents, string.Format(Strings.Label_Events_Count, fsm.Events.Length)); if (showEvents) { var events = ""; if (fsm.Events.Length > 0) { foreach (var fsmEvent in fsm.Events) { events += FsmEditorStyles.tab2 + fsmEvent.Name + FsmEditorStyles.newline; } events = events.Substring(0, events.Length - 1); } else { events = FsmEditorStyles.tab2 + Strings.Label_None_In_Table; } GUILayout.Label(events); } showVariables = EditorGUILayout.Foldout(showVariables, string.Format(Strings.Label_Variables_Count, fsmVariables.Count)); if (showVariables) { var variables = ""; if (fsmVariables.Count > 0) { foreach (var fsmVar in fsmVariables) { variables += FsmEditorStyles.tab2 + fsmVar.Name + FsmEditorStyles.newline; } variables = variables.Substring(0, variables.Length - 1); } else { variables = FsmEditorStyles.tab2 + Strings.Label_None_In_Table; } GUILayout.Label(variables); } } // Manual refresh if template has been edited if (fsmTemplate != null) { if (GUILayout.Button(new GUIContent("Refresh Template", "Use this if you've updated the template but don't see the changes here."))) { RefreshTemplate(); } } } /// <summary> /// Open the specified FSM in the Playmaker Editor /// </summary> public static void OpenInEditor(PlayMakerFSM fsmComponent) { if (FsmEditor.Instance == null) { FsmEditorWindow.OpenWindow(fsmComponent); } else { FsmEditor.SelectFsm(fsmComponent.FsmTemplate == null ? fsmComponent.Fsm : fsmComponent.FsmTemplate.fsm); } } /// <summary> /// Open the specified FSM in the Playmaker Editor /// </summary> public static void OpenInEditor(Fsm fsm) { if (fsm.Owner != null) { OpenInEditor(fsm.Owner as PlayMakerFSM); } } /// <summary> /// Open the first PlayMakerFSM on a GameObject in the Playmaker Editor /// </summary> public static void OpenInEditor(GameObject go) { if (go != null) { OpenInEditor(FsmEditorUtility.FindFsmOnGameObject(go)); } } /// <summary> /// The fsmVariables list contains easily editable references to FSM variables /// (Similar in concept to SerializedProperty) /// </summary> void BuildFsmVariableList() { fsmVariables = FsmVariable.GetFsmVariableList(fsmComponent.Fsm.Variables, target); fsmVariables.Sort(); } #region Templates void SelectTemplate(object userdata) { SelectTemplate(userdata as FsmTemplate); } void SelectTemplate(FsmTemplate template) { if (template == fsmComponent.FsmTemplate) { return; // don't want to lose overridden variables } fsmComponent.SetFsmTemplate(template); fsmTemplate = template; BuildFsmVariableList(); EditorUtility.SetDirty(fsmComponent); FsmEditor.RefreshInspector(); // Keep Playmaker Editor in sync } void ClearTemplate() { fsmComponent.Reset(); fsmTemplate = null; BuildFsmVariableList(); // If we were editing the template in the Playmaker editor // handle this gracefully by reselecting the base FSM if (FsmEditor.SelectedFsmComponent == fsmComponent) { FsmEditor.SelectFsm(fsmComponent.Fsm); } } /// <summary> /// A template can change since it was selected. /// This method refreshes the UI to reflect any changes /// while keeping any variable overrides that the use has made /// </summary> void RefreshTemplate() { if (fsmTemplate == null || Application.isPlaying) { return; } // we want to keep the existing overrides // so we copy the current FsmVariables var currentValues = new FsmVariables(fsmComponent.Fsm.Variables); // then we update the template fsmComponent.SetFsmTemplate(fsmTemplate); // finally we apply the original overrides back to the new FsmVariables fsmComponent.Fsm.Variables.OverrideVariableValues(currentValues); // and refresh the UI BuildFsmVariableList(); FsmEditor.RefreshInspector(); } void DoSelectTemplateMenu() { var menu = new GenericMenu(); var templates = (FsmTemplate[])Resources.FindObjectsOfTypeAll(typeof(FsmTemplate)); menu.AddItem(new GUIContent(Strings.Menu_None), false, ClearTemplate); foreach (var template in templates) { const string submenu = "/"; menu.AddItem(new GUIContent(template.Category + submenu + template.name), fsmComponent.FsmTemplate == template, SelectTemplate, template); } menu.ShowAsContext(); } #endregion /// <summary> /// Actions can use OnSceneGUI to display interactive gizmos /// </summary> public void OnSceneGUI() { FsmEditor.OnSceneGUI(); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Data.Services; using System.Linq; using System.Linq.Expressions; using System.Security; using System.ServiceModel; using System.Web; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Client.Metadata; using Microsoft.Xrm.Client.Security; using Microsoft.Xrm.Portal.Cms; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Microsoft.Xrm.Portal.Web.Data.Services { public class CmsDataServiceProvider : ICmsDataServiceProvider // MSBug #120015: Won't seal, inheritance is used extension point. { private static readonly Dictionary<string, EntitySetRights> _entitySetRightsByLogicalName = new Dictionary<string, EntitySetRights> { { "adx_contentsnippet", EntitySetRights.AllRead | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace }, { "adx_pagetemplate", EntitySetRights.AllRead }, { "adx_webfile", EntitySetRights.AllRead | EntitySetRights.WriteAppend | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace }, { "adx_weblink", EntitySetRights.AllRead | EntitySetRights.WriteAppend | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace }, { "adx_weblinkset", EntitySetRights.AllRead | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace }, { "adx_webpage", EntitySetRights.AllRead | EntitySetRights.WriteAppend | EntitySetRights.WriteMerge | EntitySetRights.WriteReplace }, }; public string PortalName { get; private set; } public CmsDataServiceProvider(string portalName) { PortalName = portalName; } public virtual void InitializeService<TDataContext>(IDataServiceConfiguration config) where TDataContext : OrganizationServiceContext { config.UseVerboseErrors = true; foreach (var entitySet in GetEntitySetsWithRights<TDataContext>()) { config.SetEntitySetAccessRule(entitySet.Key, entitySet.Value); } } public virtual void AttachFilesToEntity(OrganizationServiceContext context, string entitySet, Guid entityID, IEnumerable<HttpPostedFile> files) { var entity = GetServiceOperationEntityByID(context, entitySet, entityID); AssertCrmEntityChangeAccess(context, entity); var fileAttachmentProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityFileAttachmentProvider>(); if (fileAttachmentProvider == null) { throw new DataServiceException(500, "Unable to retrieve configured ICrmEntityFileAttachmentProvider dependency."); } foreach (var file in files) { fileAttachmentProvider.AttachFile(context, entity, file); } } /// <summary> /// Service operation to soft-delete an entity. ("Soft" in that it may not actually delete the entity, /// but may instead change it to a different state, archive it, etc.) /// </summary> public virtual void DeleteEntity(OrganizationServiceContext context, string entitySet, Guid entityID) { var entity = GetServiceOperationEntityByID(context, entitySet, entityID); AssertCrmEntityChangeAccess(context, entity); CrmEntityInactiveInfo inactiveInfo; if (!CrmEntityInactiveInfo.TryGetInfo(entity.LogicalName, out inactiveInfo)) { throw new DataServiceException(403, "This operation cannot be performed entities of type {0}.".FormatWith(entity.LogicalName)); } context.SetState(inactiveInfo.InactiveState, inactiveInfo.InactiveStatus, entity); } public virtual string GetEntityUrl(OrganizationServiceContext context, string entitySet, Guid entityID) { var entity = GetServiceOperationEntityByID(context, entitySet, entityID); var url = context.GetUrl(entity); if (url == null) { throw new DataServiceException(404, "URL for entity not found."); } return url; } public virtual IEnumerable<SiteMapChildInfo> GetSiteMapChildren(OrganizationServiceContext context, string siteMapProvider, string startingNodeUrl, string cmsServiceBaseUri) { if (string.IsNullOrEmpty(siteMapProvider)) { throw new DataServiceException(400, "siteMapProvider cannot be null or empty"); } if (startingNodeUrl == null) { throw new DataServiceException(400, "startingNodeUrl cannot be null"); } var provider = SiteMap.Providers[siteMapProvider]; if (provider == null) { throw new DataServiceException(404, @"Site map provider with name ""{0}"" not found.".FormatWith(siteMapProvider)); } var startingNode = provider.FindSiteMapNode(startingNodeUrl); if (startingNode == null) { throw new DataServiceException(404, @"Starting site map node with URL ""{0}"" not found.".FormatWith(startingNodeUrl)); } var childInfos = new List<SiteMapChildInfo>(); foreach (SiteMapNode childNode in startingNode.ChildNodes) { var crmNode = childNode as CrmSiteMapNode; if (crmNode == null || crmNode.Entity == null) { continue; } var entity = context.MergeClone(crmNode.Entity); var info = new SiteMapChildInfo { Title = crmNode.Title, EntityUri = string.IsNullOrEmpty(cmsServiceBaseUri) ? entity.GetDataServiceUri() : entity.GetDataServiceUri(cmsServiceBaseUri), HasPermission = TryAssertCrmEntityRight(context, entity, CrmEntityRight.Change) }; EntitySetInfo entitySetInfo; AttributeInfo propertyInfo; if (!OrganizationServiceContextInfo.TryGet(context, entity, out entitySetInfo) || !entitySetInfo.Entity.AttributesByLogicalName.TryGetValue("adx_displayorder", out propertyInfo) || propertyInfo.Property.PropertyType != typeof(int?)) { continue; } info.DisplayOrder = (int?)propertyInfo.GetValue(entity); info.DisplayOrderPropertyName = propertyInfo.Property.Name; childInfos.Add(info); } return childInfos; } public virtual void InterceptChange<TEntity>(OrganizationServiceContext context, TEntity entity, UpdateOperations operations) where TEntity : Entity { var entityName = entity.LogicalName; try { switch (entityName) { case "adx_contentsnippet": InterceptContentSnippetUpdate(context, entity, operations); break; case "adx_webfile": InterceptWebFileUpdate(context, entity, operations); break; case "adx_weblink": InterceptWebLinkUpdate(context, entity, operations); break; case "adx_weblinkset": InterceptWebLinkSetUpdate(context, entity, operations); break; case "adx_webpage": InterceptWebPageUpdate(context, entity, operations); break; default: // Let other change interceptors worry about other entity types. break; } } catch (SecurityException) { throw new DataServiceException(403, "Write permission on entity type {0} is denied.".FormatWith(entity.GetType().FullName)); } } public virtual Expression<Func<TEntity, bool>> InterceptQuery<TEntity>(OrganizationServiceContext context) where TEntity : Entity { return entity => TryAssertCrmEntityRight(context, entity, CrmEntityRight.Read); } protected virtual void AssertCrmEntityRight(OrganizationServiceContext context, Entity entity, CrmEntityRight right) { var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName); securityProvider.Assert(context, entity, right); } protected virtual IEnumerable<KeyValuePair<string, EntitySetRights>> GetEntitySetsWithRights<TDataContext>() where TDataContext : OrganizationServiceContext { return GetEntitySetsWithRights<TDataContext>(_entitySetRightsByLogicalName); } protected virtual void InterceptContentSnippetUpdate(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { AssertCrmEntityChangeAccess(context, entity); SetUpdateTrackingAttributes(entity); } protected virtual void InterceptWebFileUpdate(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { if (operations == UpdateOperations.Add) { // Ensure parent page link is being added. var websiteID = GetWebsiteIDFromParentLinkForEntityInPendingChanges(context, entity, "adx_webpage"); EnsureAssociationWithWebsite(entity, websiteID); SetCreateTrackingAttributes(entity); } else { AssertCrmEntityChangeAccess(context, entity); } SetUpdateTrackingAttributes(entity); if (string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_partialurl"))) { throw new DataServiceException(403, "Web files cannot have an empty partial URL property."); } } protected virtual void InterceptWebLinkUpdate(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { if (operations == UpdateOperations.Add) { EntityReference websiteID; if (!TryGetWebsiteIDFromParentLinkForEntityInPendingChanges(context, entity, "adx_weblinkset", out websiteID)) { throw new DataServiceException(403, "Change operation on type {0} requires AddLink to entity of type {1} to be present in pending changes.".FormatWith(entity.GetType().FullName, "adx_weblinkset")); } SetCreateTrackingAttributes(entity); } else { AssertCrmEntityChangeAccess(context, entity); } SetUpdateTrackingAttributes(entity); if (string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_name"))) { throw new DataServiceException(403, "Web links cannot have an empty name property."); } } protected virtual void InterceptWebLinkSetUpdate(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { AssertCrmEntityChangeAccess(context, entity); } protected virtual void InterceptWebPageUpdate(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { if (operations == UpdateOperations.Add) { // Ensure parent page link is being added. var websiteID = GetWebsiteIDFromParentLinkForEntityInPendingChanges(context, entity, "adx_webpage"); EnsureAssociationWithWebsite(entity, websiteID); // Make the current user the author of the new web page, if the author ID is not yet set. if (entity.GetAttributeValue<Guid?>("adx_authorid") == null) { var currentContact = GetUser(context); if (currentContact != null) { entity.SetAttributeValue("adx_authorid", currentContact.ToEntityReference()); } } SetCreateTrackingAttributes(entity); } else { AssertCrmEntityChangeAccess(context, entity); } SetUpdateTrackingAttributes(entity); if (string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_name"))) { throw new DataServiceException(403, "Web pages cannot have an empty name property."); } if (string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_partialurl"))) { throw new DataServiceException(403, "Web pages cannot have an empty partial URL property."); } if (entity.GetAttributeValue<Guid?>("adx_pagetemplateid") == null) { throw new DataServiceException(403, "Web pages must have a page template ID."); } } protected virtual bool TryAssertCrmEntityRight(OrganizationServiceContext context, Entity entity, CrmEntityRight right) { var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName); return securityProvider.TryAssert(context, entity, right); } private void AssertCrmEntityChangeAccess(OrganizationServiceContext context, Entity entity) { AssertCrmEntityRight(context, entity, CrmEntityRight.Change); } protected static void EnsureAssociationWithWebsite(Entity entity, EntityReference websiteID) { // If we're changing an entity, make sure it is associated with the given website. if (entity.GetAttributeValue<EntityReference>("adx_websiteid") != websiteID) { entity.SetAttributeValue("adx_websiteid", websiteID); } } /// <summary> /// Gets mappings of <see cref="IQueryable{T}"/> entity set names exposed by TDataContext and /// the <see cref="EntitySetRights"/> to assign to those sets at service initialization. /// </summary> protected static IEnumerable<KeyValuePair<string, EntitySetRights>> GetEntitySetsWithRights<TDataContext>(Dictionary<string, EntitySetRights> entitySetRightsByLogicalName) where TDataContext : OrganizationServiceContext { return (typeof(TDataContext)).GetEntitySetProperties().Select(property => { // Get the first generic type argument of the generic. This is potentially our CRM entity // mapping class. var genericArgumentType = property.PropertyType.GetGenericArguments().FirstOrDefault(); if (genericArgumentType == null) { return null; } var entityName = genericArgumentType.GetEntityLogicalName(); EntitySetRights rights; // If the properties generic type CRM entity name is not in our dictionary of relevant // entities, discard it. if (!entitySetRightsByLogicalName.TryGetValue(entityName, out rights)) { return null; } return new { property.Name, Rights = rights }; }).Where(set => set != null).Select(set => new KeyValuePair<string, EntitySetRights>(set.Name, set.Rights)); } protected static Entity GetServiceOperationEntityByID(OrganizationServiceContext context, string entitySet, Guid entityID) { OrganizationServiceContextInfo contextInfo; EntitySetInfo entitySetInfo; if (!OrganizationServiceContextInfo.TryGet(context.GetType(), out contextInfo) || !contextInfo.EntitySetsByPropertyName.TryGetValue(entitySet, out entitySetInfo)) { throw new DataServiceException(404, @"Entity set ""{0}"" is not exposed by this service.".FormatWith(entitySet)); } var entityType = entitySetInfo.Entity.EntityType; if (entityType == null) { throw new DataServiceException(404, @"Unable to retrieve data type for entity set ""{0}"".".FormatWith(entitySet)); } var entityName = entitySetInfo.Entity.EntityLogicalName.LogicalName; var entityPrimaryKeyName = entitySetInfo.Entity.PrimaryKeyProperty.CrmPropertyAttribute.LogicalName; var dynamicEntityWrapper = context.CreateQuery(entityName) .Where(e => e.GetAttributeValue<Guid>(entityPrimaryKeyName) == entityID) .FirstOrDefault(); if (dynamicEntityWrapper == null) { throw new DataServiceException(404, @"Entity with ID ""{0}"" not found in entity set ""{1}"".".FormatWith(entityID, entitySet)); } var entity = dynamicEntityWrapper; if (entity == null) { throw new DataServiceException(404, @"Entity with ID ""{0}"" not found in entity set ""{1}"".".FormatWith(entityID, entitySet)); } return entity; } protected static EntityReference GetWebsiteIDFromParentLinkForEntityInPendingChanges( OrganizationServiceContext context, Entity entity, string sourceEntityName) { EntityReference websiteID; if (!TryGetWebsiteIDFromParentLinkForEntityInPendingChanges(context, entity, sourceEntityName, out websiteID)) { throw new SecurityException("Change operation on type {0} requires AddLink to entity of type {1} to be present in pending changes.".FormatWith(entity.GetType().FullName, sourceEntityName)); } return websiteID; } protected static void SetCreateTrackingAttributes(Entity entity) { entity.SetAttributeValue("adx_createdbyusername", GetCurrentIdentity()); // entity.SetAttributeValue("adx_createdbyipaddress", HttpContext.Current.Request.UserHostAddress); } protected static void SetUpdateTrackingAttributes(Entity entity) { entity.SetAttributeValue("adx_modifiedbyusername", GetCurrentIdentity()); // entity.SetAttributeValue("adx_modifiedbyipaddress", HttpContext.Current.Request.UserHostAddress); } protected static bool TryGetWebsiteIDFromParentLinkForEntityInPendingChanges(OrganizationServiceContext context, Entity entity, string sourceEntityName, out EntityReference websiteID) { return OrganizationServiceContextUtility.TryGetWebsiteIDFromParentLinkForEntityInPendingChanges(context, entity, sourceEntityName, out websiteID); } private static string GetCurrentIdentity() { if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null) { return HttpContext.Current.User.Identity.Name; } if (ServiceSecurityContext.Current != null && ServiceSecurityContext.Current.PrimaryIdentity != null) { return ServiceSecurityContext.Current.PrimaryIdentity.Name; } throw new DataServiceException(403, "Unable to determine identity from current context."); } private Entity GetUser(OrganizationServiceContext context) { // retrieve the username attribute from the portal configuration var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName) as IUserResolutionSettings; var attributeMapUsername = (portal != null ? portal.AttributeMapUsername : null) ?? "adx_username"; var memberEntityName = (portal != null ? portal.MemberEntityName : null) ?? "contact"; var username = GetCurrentIdentity(); var findContact = from c in context.CreateQuery(memberEntityName) where c.GetAttributeValue<string>(attributeMapUsername) == username select c; return findContact.FirstOrDefault(); } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class MediaController : android.widget.FrameLayout { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static MediaController() { InitJNI(); } protected MediaController(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.MediaController.MediaPlayerControl_))] public interface MediaPlayerControl : global::MonoJavaBridge.IJavaObject { void start(); int getDuration(); void pause(); bool isPlaying(); void seekTo(int arg0); int getCurrentPosition(); int getBufferPercentage(); bool canPause(); bool canSeekBackward(); bool canSeekForward(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.MediaController.MediaPlayerControl))] public sealed partial class MediaPlayerControl_ : java.lang.Object, MediaPlayerControl { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static MediaPlayerControl_() { InitJNI(); } internal MediaPlayerControl_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _start11583; void android.widget.MediaController.MediaPlayerControl.start() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._start11583); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._start11583); } internal static global::MonoJavaBridge.MethodId _getDuration11584; int android.widget.MediaController.MediaPlayerControl.getDuration() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._getDuration11584); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._getDuration11584); } internal static global::MonoJavaBridge.MethodId _pause11585; void android.widget.MediaController.MediaPlayerControl.pause() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._pause11585); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._pause11585); } internal static global::MonoJavaBridge.MethodId _isPlaying11586; bool android.widget.MediaController.MediaPlayerControl.isPlaying() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._isPlaying11586); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._isPlaying11586); } internal static global::MonoJavaBridge.MethodId _seekTo11587; void android.widget.MediaController.MediaPlayerControl.seekTo(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._seekTo11587, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._seekTo11587, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCurrentPosition11588; int android.widget.MediaController.MediaPlayerControl.getCurrentPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._getCurrentPosition11588); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._getCurrentPosition11588); } internal static global::MonoJavaBridge.MethodId _getBufferPercentage11589; int android.widget.MediaController.MediaPlayerControl.getBufferPercentage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._getBufferPercentage11589); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._getBufferPercentage11589); } internal static global::MonoJavaBridge.MethodId _canPause11590; bool android.widget.MediaController.MediaPlayerControl.canPause() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._canPause11590); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._canPause11590); } internal static global::MonoJavaBridge.MethodId _canSeekBackward11591; bool android.widget.MediaController.MediaPlayerControl.canSeekBackward() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._canSeekBackward11591); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._canSeekBackward11591); } internal static global::MonoJavaBridge.MethodId _canSeekForward11592; bool android.widget.MediaController.MediaPlayerControl.canSeekForward() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_._canSeekForward11592); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.MediaPlayerControl_.staticClass, global::android.widget.MediaController.MediaPlayerControl_._canSeekForward11592); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.MediaController.MediaPlayerControl_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MediaController$MediaPlayerControl")); global::android.widget.MediaController.MediaPlayerControl_._start11583 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "start", "()V"); global::android.widget.MediaController.MediaPlayerControl_._getDuration11584 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getDuration", "()I"); global::android.widget.MediaController.MediaPlayerControl_._pause11585 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "pause", "()V"); global::android.widget.MediaController.MediaPlayerControl_._isPlaying11586 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "isPlaying", "()Z"); global::android.widget.MediaController.MediaPlayerControl_._seekTo11587 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "seekTo", "(I)V"); global::android.widget.MediaController.MediaPlayerControl_._getCurrentPosition11588 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getCurrentPosition", "()I"); global::android.widget.MediaController.MediaPlayerControl_._getBufferPercentage11589 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getBufferPercentage", "()I"); global::android.widget.MediaController.MediaPlayerControl_._canPause11590 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canPause", "()Z"); global::android.widget.MediaController.MediaPlayerControl_._canSeekBackward11591 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canSeekBackward", "()Z"); global::android.widget.MediaController.MediaPlayerControl_._canSeekForward11592 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canSeekForward", "()Z"); } } internal static global::MonoJavaBridge.MethodId _setEnabled11593; public override void setEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._setEnabled11593, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._setEnabled11593, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onTouchEvent11594; public override bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController._onTouchEvent11594, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._onTouchEvent11594, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onTrackballEvent11595; public override bool onTrackballEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController._onTrackballEvent11595, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._onTrackballEvent11595, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchKeyEvent11596; public override bool dispatchKeyEvent(android.view.KeyEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController._dispatchKeyEvent11596, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._dispatchKeyEvent11596, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onFinishInflate11597; public virtual new void onFinishInflate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._onFinishInflate11597); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._onFinishInflate11597); } internal static global::MonoJavaBridge.MethodId _isShowing11598; public virtual bool isShowing() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.MediaController._isShowing11598); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._isShowing11598); } internal static global::MonoJavaBridge.MethodId _show11599; public virtual void show(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._show11599, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._show11599, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _show11600; public virtual void show() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._show11600); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._show11600); } internal static global::MonoJavaBridge.MethodId _hide11601; public virtual void hide() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._hide11601); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._hide11601); } internal static global::MonoJavaBridge.MethodId _setMediaPlayer11602; public virtual void setMediaPlayer(android.widget.MediaController.MediaPlayerControl arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._setMediaPlayer11602, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._setMediaPlayer11602, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setAnchorView11603; public virtual void setAnchorView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._setAnchorView11603, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._setAnchorView11603, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setPrevNextListeners11604; public virtual void setPrevNextListeners(android.view.View.OnClickListener arg0, android.view.View.OnClickListener arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.MediaController._setPrevNextListeners11604, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.MediaController.staticClass, global::android.widget.MediaController._setPrevNextListeners11604, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _MediaController11605; public MediaController(android.content.Context arg0, bool arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._MediaController11605, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _MediaController11606; public MediaController(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._MediaController11606, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _MediaController11607; public MediaController(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._MediaController11607, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.MediaController.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MediaController")); global::android.widget.MediaController._setEnabled11593 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "setEnabled", "(Z)V"); global::android.widget.MediaController._onTouchEvent11594 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.widget.MediaController._onTrackballEvent11595 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z"); global::android.widget.MediaController._dispatchKeyEvent11596 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z"); global::android.widget.MediaController._onFinishInflate11597 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "onFinishInflate", "()V"); global::android.widget.MediaController._isShowing11598 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "isShowing", "()Z"); global::android.widget.MediaController._show11599 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "show", "(I)V"); global::android.widget.MediaController._show11600 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "show", "()V"); global::android.widget.MediaController._hide11601 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "hide", "()V"); global::android.widget.MediaController._setMediaPlayer11602 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "setMediaPlayer", "(Landroid/widget/MediaController$MediaPlayerControl;)V"); global::android.widget.MediaController._setAnchorView11603 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "setAnchorView", "(Landroid/view/View;)V"); global::android.widget.MediaController._setPrevNextListeners11604 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "setPrevNextListeners", "(Landroid/view/View$OnClickListener;Landroid/view/View$OnClickListener;)V"); global::android.widget.MediaController._MediaController11605 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;Z)V"); global::android.widget.MediaController._MediaController11606 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.widget.MediaController._MediaController11607 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); } } }
using Facebook.Yoga; using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager.Annotations; using System; using static System.FormattableString; namespace ReactNative.UIManager { /// <summary> /// Shadow node subclass that supplies setters for base view layout /// properties such as width, height, flex properties, borders, etc. /// </summary> public class LayoutShadowNode : ReactShadowNode { /// <summary> /// Instantiates a <see cref="LayoutShadowNode"/>. /// </summary> public LayoutShadowNode() { } /// <summary> /// Instantiates a <see cref="LayoutShadowNode"/>. /// </summary> /// <param name="isVirtual"> /// <code>true</code> if the node is virtual, otherwise <code>false</code>. /// </param> public LayoutShadowNode(bool isVirtual) : base(isVirtual) { } /// <summary> /// Set the width of the shadow node. /// </summary> /// <param name="width">The width.</param> [ReactProp(ViewProps.Width, DefaultSingle = YogaConstants.Undefined)] public void SetWidth(JValue width) { if (IsVirtual) { return; } StyleWidth = ToYogaValue(width); } /// <summary> /// Sets the minimum width of the shadow node. /// </summary> /// <param name="minWidth">The minimum width.</param> [ReactProp(ViewProps.MinWidth, DefaultSingle = YogaConstants.Undefined)] public void SetMinWidth(JValue minWidth) { if (IsVirtual) { return; } StyleMinWidth = ToYogaValue(minWidth); } /// <summary> /// Sets the maximum width of the shadow node. /// </summary> /// <param name="maxWidth">The maximum width.</param> [ReactProp(ViewProps.MaxWidth, DefaultSingle = YogaConstants.Undefined)] public void SetMaxWidth(JValue maxWidth) { if (IsVirtual) { return; } StyleMaxWidth = ToYogaValue(maxWidth); } /// <summary> /// Set the heigth of the shadow node. /// </summary> /// <param name="height">The height.</param> [ReactProp(ViewProps.Height, DefaultSingle = YogaConstants.Undefined)] public void SetHeight(JValue height) { if (IsVirtual) { return; } StyleHeight = ToYogaValue(height); } /// <summary> /// Sets the minimum height of the shadow node. /// </summary> /// <param name="minHeight">The minimum height.</param> [ReactProp(ViewProps.MinHeight, DefaultSingle = YogaConstants.Undefined)] public void SetMinHeight(JValue minHeight) { if (IsVirtual) { return; } StyleMinHeight = ToYogaValue(minHeight); } /// <summary> /// Sets the maximum height of the shadow node. /// </summary> /// <param name="maxHeight">The maximum height.</param> [ReactProp(ViewProps.MaxHeight, DefaultSingle = YogaConstants.Undefined)] public virtual void SetMaxHeight(JValue maxHeight) { if (IsVirtual) { return; } StyleMaxHeight = ToYogaValue(maxHeight); } /// <summary> /// Sets the flex of the shadow node. /// </summary> /// <param name="flex">The flex value.</param> [ReactProp(ViewProps.Flex, DefaultSingle = 0f)] public void SetFlex(float flex) { if (IsVirtual) { return; } Flex = flex; } /// <summary> /// Sets the flex grow of the shadow node. /// </summary> /// <param name="flexGrow">The flex grow value.</param> [ReactProp(ViewProps.FlexGrow, DefaultSingle = 0f)] public void SetFlexGrow(float flexGrow) { if (IsVirtual) { return; } FlexGrow = flexGrow; } /// <summary> /// Sets the flex shrink of the shadow node. /// </summary> /// <param name="flexShrink">The flex shrink value.</param> [ReactProp(ViewProps.FlexShrink, DefaultSingle = 0f)] public void SetFlexShrink(float flexShrink) { if (IsVirtual) { return; } FlexShrink = flexShrink; } /// <summary> /// Sets the flex basis of the shadow node. /// </summary> /// <param name="flexBasis">The flex basis value.</param> [ReactProp(ViewProps.FlexBasis, DefaultSingle = 0f)] public void SetFlexBasis(float flexBasis) { if (IsVirtual) { return; } FlexBasis = flexBasis; } /// <summary> /// Sets the aspect ratio of the shadow node. /// </summary> /// <param name="aspectRatio">The aspect ratio.</param> [ReactProp(ViewProps.AspectRatio, DefaultSingle = YogaConstants.Undefined)] public void SetAspectRatio(float aspectRatio) { StyleAspectRatio = aspectRatio; } /// <summary> /// Sets the flex direction of the shadow node. /// </summary> /// <param name="flexDirection">The flex direction.</param> [ReactProp(ViewProps.FlexDirection)] public void SetFlexDirection(string flexDirection) { if (IsVirtual) { return; } FlexDirection = EnumHelpers.ParseNullable<YogaFlexDirection>(flexDirection) ?? YogaFlexDirection.Column; } /// <summary> /// Sets the wrap property on the shadow node. /// </summary> /// <param name="flexWrap">The wrap.</param> [ReactProp(ViewProps.FlexWrap)] public void SetFlexWrap(string flexWrap) { if (IsVirtual) { return; } FlexWrap = EnumHelpers.ParseNullable<YogaWrap>(flexWrap) ?? YogaWrap.NoWrap; } /// <summary> /// Sets the self alignment of the shadow node. /// </summary> /// <param name="alignSelf">The align self property.</param> [ReactProp(ViewProps.AlignSelf)] public void SetAlignSelf(string alignSelf) { if (IsVirtual) { return; } AlignSelf = EnumHelpers.ParseNullable<YogaAlign>(alignSelf) ?? YogaAlign.Auto; } /// <summary> /// Sets the item alignment for the shadow node. /// </summary> /// <param name="alignItems">The item alignment.</param> [ReactProp(ViewProps.AlignItems)] public void SetAlignItems(string alignItems) { if (IsVirtual) { return; } AlignItems = EnumHelpers.ParseNullable<YogaAlign>(alignItems) ?? YogaAlign.Stretch; } /// <summary> /// Sets the content alignment. /// </summary> /// <param name="alignContent">The content alignment.</param> [ReactProp(ViewProps.AlignContent)] public void SetAlignContent(string alignContent) { if (IsVirtual) { return; } AlignContent = EnumHelpers.ParseNullable<YogaAlign>(alignContent) ?? YogaAlign.FlexStart; } /// <summary> /// Sets the content justification. /// </summary> /// <param name="justifyContent">The content justification.</param> [ReactProp(ViewProps.JustifyContent)] public void SetJustifyContent(string justifyContent) { if (IsVirtual) { return; } JustifyContent = EnumHelpers.ParseNullable<YogaJustify>(justifyContent) ?? YogaJustify.FlexStart; } /// <summary> /// Sets the overflow of the shadow node. /// </summary> /// <param name="overflow">The overflow</param> [ReactProp(ViewProps.Overflow)] public void SetOverflow(string overflow) { if (IsVirtual) { return; } Overflow = EnumHelpers.ParseNullable<YogaOverflow>(overflow) ?? YogaOverflow.Visible; } /// <summary> /// Sets the display mode. /// </summary> /// <param name="display">The display mode.</param> [ReactProp(ViewProps.Display)] public void SetDisplay(string display) { if (IsVirtual) { return; } Display = EnumHelpers.ParseNullable<YogaDisplay>(display) ?? YogaDisplay.Flex; } /// <summary> /// Sets the margins of the shadow node. /// </summary> /// <param name="index">The spacing type index.</param> /// <param name="margin">The margin value.</param> [ReactPropGroup( ViewProps.Margin, ViewProps.MarginVertical, ViewProps.MarginHorizontal, ViewProps.MarginLeft, ViewProps.MarginRight, ViewProps.MarginTop, ViewProps.MarginBottom, DefaultSingle = YogaConstants.Undefined)] public void SetMargins(int index, JValue margin) { if (IsVirtual) { return; } SetMargin(ViewProps.PaddingMarginSpacingTypes[index], ToYogaValue(margin)); } /// <summary> /// Sets the paddings of the shadow node. /// </summary> /// <param name="index">The spacing type index.</param> /// <param name="padding">The padding value.</param> [ReactPropGroup( ViewProps.Padding, ViewProps.PaddingVertical, ViewProps.PaddingHorizontal, ViewProps.PaddingLeft, ViewProps.PaddingRight, ViewProps.PaddingTop, ViewProps.PaddingBottom, DefaultSingle = YogaConstants.Undefined)] public virtual void SetPaddings(int index, JValue padding) { SetPadding(ViewProps.PaddingMarginSpacingTypes[index], ToYogaValue(padding)); } /// <summary> /// Sets the border width properties for the shadow node. /// </summary> /// <param name="index">The border spacing type index.</param> /// <param name="borderWidth">The border width.</param> [ReactPropGroup( ViewProps.BorderWidth, ViewProps.BorderLeftWidth, ViewProps.BorderRightWidth, ViewProps.BorderTopWidth, ViewProps.BorderBottomWidth, DefaultSingle = YogaConstants.Undefined)] public void SetBorderWidth(int index, float borderWidth) { SetBorder(ViewProps.BorderSpacingTypes[index], borderWidth); } /// <summary> /// Sets the position of the shadow node. /// </summary> /// <param name="index">The spacing type index.</param> /// <param name="position">The position value.</param> [ReactPropGroup( ViewProps.Left, ViewProps.Right, ViewProps.Top, ViewProps.Bottom, DefaultSingle = YogaConstants.Undefined)] public void SetPositionValues(int index, JValue position) { if (IsVirtual) { return; } SetPosition(ViewProps.PositionSpacingTypes[index], ToYogaValue(position)); } /// <summary> /// Sets the position of the shadow node. /// </summary> /// <param name="position">The position.</param> [ReactProp(ViewProps.Position)] public void SetPosition(string position) { PositionType = EnumHelpers.ParseNullable<YogaPositionType>(position) ?? YogaPositionType.Relative; } /// <summary> /// Sets if the view should send an event on layout. /// </summary> /// <param name="shouldNotifyOnLayout"> /// The flag signaling if the view should sent an event on layout. /// </param> [ReactProp("onLayout")] public void SetShouldNotifyOnLayout(bool shouldNotifyOnLayout) { ShouldNotifyOnLayout = shouldNotifyOnLayout; } private static YogaValue ToYogaValue(JValue value) { if (value == null || value.Type == JTokenType.Null || value.Type == JTokenType.Undefined) { return YogaValue.Undefined(); } if (value.Type == JTokenType.String) { var s = value.Value<string>(); if (s == "auto") { return YogaValue.Auto(); } if (s.EndsWith("%")) { return YogaValue.Percent(float.Parse(s.Substring(0, s.Length - 1))); } throw new InvalidOperationException( Invariant($"Unknown value: '{s}'")); } return YogaValue.Point(value.Value<float>()); } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Threading { public static class __Volatile { public static IObservable<Tuple<System.Boolean, System.Boolean>> Read(IObservable<System.Boolean> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.SByte, System.SByte>> Read(IObservable<System.SByte> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Byte, System.Byte>> Read(IObservable<System.Byte> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int16, System.Int16>> Read(IObservable<System.Int16> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.UInt16, System.UInt16>> Read(IObservable<System.UInt16> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int32, System.Int32>> Read(IObservable<System.Int32> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.UInt32, System.UInt32>> Read(IObservable<System.UInt32> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Read(IObservable<System.Int64> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.UInt64, System.UInt64>> Read(IObservable<System.UInt64> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.IntPtr, System.IntPtr>> Read(IObservable<System.IntPtr> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.UIntPtr, System.UIntPtr>> Read(IObservable<System.UIntPtr> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Single, System.Single>> Read(IObservable<System.Single> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Double, System.Double>> Read(IObservable<System.Double> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<T, T>> Read<T>(IObservable<T> location) where T : class { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Volatile.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<System.Boolean> Write(IObservable<System.Boolean> location, IObservable<System.Boolean> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.SByte> Write(IObservable<System.SByte> location, IObservable<System.SByte> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Byte> Write(IObservable<System.Byte> location, IObservable<System.Byte> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Int16> Write(IObservable<System.Int16> location, IObservable<System.Int16> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.UInt16> Write(IObservable<System.UInt16> location, IObservable<System.UInt16> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Int32> Write(IObservable<System.Int32> location, IObservable<System.Int32> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.UInt32> Write(IObservable<System.UInt32> location, IObservable<System.UInt32> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Int64> Write(IObservable<System.Int64> location, IObservable<System.Int64> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.UInt64> Write(IObservable<System.UInt64> location, IObservable<System.UInt64> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.IntPtr> Write(IObservable<System.IntPtr> location, IObservable<System.IntPtr> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.UIntPtr> Write(IObservable<System.UIntPtr> location, IObservable<System.UIntPtr> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Single> Write(IObservable<System.Single> location, IObservable<System.Single> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<System.Double> Write(IObservable<System.Double> location, IObservable<System.Double> value) { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } public static IObservable<T> Write<T>(IObservable<T> location, IObservable<T> value) where T : class { return Observable.Zip(location, value, (locationLambda, valueLambda) => { System.Threading.Volatile.Write(ref locationLambda, valueLambda); return locationLambda; }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Runtime; using Internal.Metadata.NativeFormat; using Internal.Runtime.Augments; using Internal.TypeSystem; using Internal.Reflection.Execution; using Internal.Reflection.Core; using Internal.Runtime.TypeLoader; using AssemblyFlags = Internal.Metadata.NativeFormat.AssemblyFlags; namespace Internal.TypeSystem.NativeFormat { /// <summary> /// Represent a NativeFormat metadata file. These files can contain multiple logical ECMA metadata style assemblies. /// </summary> public sealed class NativeFormatMetadataUnit { private NativeFormatModuleInfo _module; private MetadataReader _metadataReader; private TypeSystemContext _context; internal interface IHandleObject { Handle Handle { get; } NativeFormatType Container { get; } } private sealed class NativeFormatObjectLookupWrapper : IHandleObject { private Handle _handle; private object _obj; private NativeFormatType _container; public NativeFormatObjectLookupWrapper(Handle handle, object obj, NativeFormatType container) { _obj = obj; _handle = handle; _container = container; } public Handle Handle { get { return _handle; } } public object Object { get { return _obj; } } public NativeFormatType Container { get { return _container; } } } internal struct NativeFormatObjectKey { private Handle _handle; private NativeFormatType _container; public NativeFormatObjectKey(Handle handle, NativeFormatType container) { _handle = handle; _container = container; } public Handle Handle { get { return _handle; } } public NativeFormatType Container { get { return _container; } } } internal class NativeFormatObjectLookupHashtable : LockFreeReaderHashtable<NativeFormatObjectKey, IHandleObject> { private NativeFormatMetadataUnit _metadataUnit; private MetadataReader _metadataReader; public NativeFormatObjectLookupHashtable(NativeFormatMetadataUnit metadataUnit, MetadataReader metadataReader) { _metadataUnit = metadataUnit; _metadataReader = metadataReader; } protected override int GetKeyHashCode(NativeFormatObjectKey key) { int hashcode = key.Handle.GetHashCode(); if (key.Container != null) { // Todo: Use a better hash combining function hashcode ^= key.Container.GetHashCode(); } return hashcode; } protected override int GetValueHashCode(IHandleObject value) { int hashcode = value.Handle.GetHashCode(); if (value.Container != null) { // Todo: Use a better hash combining function hashcode ^= value.Container.GetHashCode(); } return hashcode; } protected override bool CompareKeyToValue(NativeFormatObjectKey key, IHandleObject value) { return key.Handle.Equals(value.Handle) && Object.ReferenceEquals(key.Container, value.Container); } protected override bool CompareValueToValue(IHandleObject value1, IHandleObject value2) { if (Object.ReferenceEquals(value1, value2)) return true; else return value1.Handle.Equals(value2.Handle) && Object.ReferenceEquals(value1.Container, value2.Container); } protected override IHandleObject CreateValueFromKey(NativeFormatObjectKey key) { Handle handle = key.Handle; NativeFormatType container = key.Container; object item; switch (handle.HandleType) { case HandleType.TypeDefinition: item = new NativeFormatType(_metadataUnit, handle.ToTypeDefinitionHandle(_metadataReader)); break; case HandleType.Method: item = new NativeFormatMethod(container, handle.ToMethodHandle(_metadataReader)); break; case HandleType.Field: item = new NativeFormatField(container, handle.ToFieldHandle(_metadataReader)); break; case HandleType.TypeReference: item = _metadataUnit.ResolveTypeReference(handle.ToTypeReferenceHandle(_metadataReader)); break; case HandleType.MemberReference: item = _metadataUnit.ResolveMemberReference(handle.ToMemberReferenceHandle(_metadataReader)); break; case HandleType.QualifiedMethod: item = _metadataUnit.ResolveQualifiedMethod(handle.ToQualifiedMethodHandle(_metadataReader)); break; case HandleType.QualifiedField: item = _metadataUnit.ResolveQualifiedField(handle.ToQualifiedFieldHandle(_metadataReader)); break; case HandleType.ScopeReference: item = _metadataUnit.ResolveAssemblyReference(handle.ToScopeReferenceHandle(_metadataReader)); break; case HandleType.ScopeDefinition: { ScopeDefinition scope = handle.ToScopeDefinitionHandle(_metadataReader).GetScopeDefinition(_metadataReader); item = _metadataUnit.GetModuleFromAssemblyName(scope.Name.GetConstantStringValue(_metadataReader).Value); } break; case HandleType.TypeSpecification: case HandleType.TypeInstantiationSignature: case HandleType.SZArraySignature: case HandleType.ArraySignature: case HandleType.PointerSignature: case HandleType.ByReferenceSignature: case HandleType.TypeVariableSignature: case HandleType.MethodTypeVariableSignature: { NativeFormatSignatureParser parser = new NativeFormatSignatureParser(_metadataUnit, handle, _metadataReader); item = parser.ParseTypeSignature(); } break; case HandleType.MethodInstantiation: item = _metadataUnit.ResolveMethodInstantiation(handle.ToMethodInstantiationHandle(_metadataReader)); break; // TODO: Resolve other tokens default: throw new BadImageFormatException("Unknown metadata token type: " + handle.HandleType); } switch (handle.HandleType) { case HandleType.TypeDefinition: case HandleType.Field: case HandleType.Method: // type/method/field definitions directly correspond to their target item. return (IHandleObject)item; default: // Everything else is some form of reference which cannot be self-describing return new NativeFormatObjectLookupWrapper(handle, item, container); } } } private NativeFormatObjectLookupHashtable _resolvedTokens; public NativeFormatMetadataUnit(TypeSystemContext context, NativeFormatModuleInfo module, MetadataReader metadataReader) { _module = module; _metadataReader = metadataReader; _context = context; _resolvedTokens = new NativeFormatObjectLookupHashtable(this, _metadataReader); } public MetadataReader MetadataReader { get { return _metadataReader; } } public TypeSystemContext Context { get { return _context; } } public TypeManagerHandle RuntimeModule { get { return _module.Handle; } } public NativeFormatModuleInfo RuntimeModuleInfo { get { return _module; } } public TypeDesc GetType(Handle handle) { TypeDesc type = GetObject(handle, null) as TypeDesc; if (type == null) throw new BadImageFormatException("Type expected"); return type; } public MethodDesc GetMethod(Handle handle, NativeFormatType type) { MethodDesc method = GetObject(handle, type) as MethodDesc; if (method == null) throw new BadImageFormatException("Method expected"); return method; } public FieldDesc GetField(Handle handle, NativeFormatType type) { FieldDesc field = GetObject(handle, type) as FieldDesc; if (field == null) throw new BadImageFormatException("Field expected"); return field; } public ModuleDesc GetModule(ScopeReferenceHandle scopeHandle) { return (ModuleDesc)GetObject(scopeHandle, null); } public NativeFormatModule GetModule(ScopeDefinitionHandle scopeHandle) { return (NativeFormatModule)GetObject(scopeHandle, null); } public Object GetObject(Handle handle, NativeFormatType type) { IHandleObject obj = _resolvedTokens.GetOrCreateValue(new NativeFormatObjectKey(handle, type)); if (obj is NativeFormatObjectLookupWrapper) { return ((NativeFormatObjectLookupWrapper)obj).Object; } else { return obj; } } private Object ResolveMethodInstantiation(MethodInstantiationHandle handle) { MethodInstantiation methodInstantiation = _metadataReader.GetMethodInstantiation(handle); MethodDesc genericMethodDef = (MethodDesc)GetObject(methodInstantiation.Method, null); ArrayBuilder<TypeDesc> instantiation = new ArrayBuilder<TypeDesc>(); foreach (Handle genericArgHandle in methodInstantiation.GenericTypeArguments) { instantiation.Add(GetType(genericArgHandle)); } return Context.GetInstantiatedMethod(genericMethodDef, new Instantiation(instantiation.ToArray())); } private Object ResolveQualifiedMethod(QualifiedMethodHandle handle) { QualifiedMethod qualifiedMethod = _metadataReader.GetQualifiedMethod(handle); NativeFormatType enclosingType = (NativeFormatType)GetType(qualifiedMethod.EnclosingType); return GetMethod(qualifiedMethod.Method, enclosingType); } private Object ResolveQualifiedField(QualifiedFieldHandle handle) { QualifiedField qualifiedField = _metadataReader.GetQualifiedField(handle); NativeFormatType enclosingType = (NativeFormatType)GetType(qualifiedField.EnclosingType); return GetField(qualifiedField.Field, enclosingType); } private Object ResolveMemberReference(MemberReferenceHandle handle) { MemberReference memberReference = _metadataReader.GetMemberReference(handle); TypeDesc parent = GetType(memberReference.Parent); TypeDesc parentTypeDesc = parent as TypeDesc; if (parentTypeDesc != null) { NativeFormatSignatureParser parser = new NativeFormatSignatureParser(this, memberReference.Signature, _metadataReader); string name = _metadataReader.GetString(memberReference.Name); if (parser.IsFieldSignature) { FieldDesc field = parentTypeDesc.GetField(name); if (field != null) return field; // TODO: Better error message throw new MissingMemberException("Field not found " + parent.ToString() + "." + name); } else { MethodSignature sig = parser.ParseMethodSignature(); TypeDesc typeDescToInspect = parentTypeDesc; // Try to resolve the name and signature in the current type, or any of the base types. do { // TODO: handle substitutions MethodDesc method = typeDescToInspect.GetMethod(name, sig); if (method != null) { // If this resolved to one of the base types, make sure it's not a constructor. // Instance constructors are not inherited. if (typeDescToInspect != parentTypeDesc && method.IsConstructor) break; return method; } typeDescToInspect = typeDescToInspect.BaseType; } while (typeDescToInspect != null); // TODO: Better error message throw new MissingMemberException("Method not found " + parent.ToString() + "." + name); } } throw new BadImageFormatException(); } private DefType ResolveTypeReference(TypeReferenceHandle handle) { TypeReference typeReference = _metadataReader.GetTypeReference(handle); if (typeReference.ParentNamespaceOrType.HandleType == HandleType.TypeReference) { // Nested type case MetadataType containingType = (MetadataType)ResolveTypeReference(typeReference.ParentNamespaceOrType.ToTypeReferenceHandle(_metadataReader)); return containingType.GetNestedType(_metadataReader.GetString(typeReference.TypeName)); } else { // Cross-assembly reference // Get remote module, and then lookup by namespace/name ScopeReferenceHandle scopeReferenceHandle = default(ScopeReferenceHandle); NamespaceReferenceHandle initialNamespaceReferenceHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(_metadataReader); NamespaceReferenceHandle namespaceReferenceHandle = initialNamespaceReferenceHandle; do { NamespaceReference namespaceReference = _metadataReader.GetNamespaceReference(namespaceReferenceHandle); if (namespaceReference.ParentScopeOrNamespace.HandleType == HandleType.ScopeReference) { scopeReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToScopeReferenceHandle(_metadataReader); } else { namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(_metadataReader); } } while (scopeReferenceHandle.IsNull(_metadataReader)); ModuleDesc remoteModule = GetModule(scopeReferenceHandle); string namespaceName = _metadataReader.GetNamespaceName(initialNamespaceReferenceHandle); string typeName = _metadataReader.GetString(typeReference.TypeName); MetadataType resolvedType = remoteModule.GetType(namespaceName, typeName, throwIfNotFound: false); if (resolvedType != null) { return resolvedType; } // Special handling for the magic __Canon types cannot be currently put into // NativeFormatModule because GetType returns a MetadataType. if (remoteModule == _context.SystemModule) { string qualifiedTypeName = namespaceName + "." + typeName; if (qualifiedTypeName == CanonType.FullName) { return _context.CanonType; } if (qualifiedTypeName == UniversalCanonType.FullName) { return _context.UniversalCanonType; } } throw new NotImplementedException(); } } private Object ResolveAssemblyReference(ScopeReferenceHandle handle) { ScopeReference assemblyReference = _metadataReader.GetScopeReference(handle); AssemblyName an = new AssemblyName(); an.Name = _metadataReader.GetString(assemblyReference.Name); an.Version = new Version(assemblyReference.MajorVersion, assemblyReference.MinorVersion, assemblyReference.BuildNumber, assemblyReference.RevisionNumber); an.CultureName = _metadataReader.GetString(assemblyReference.Culture) ?? ""; var publicKeyOrToken = assemblyReference.PublicKeyOrToken.ConvertByteCollectionToArray(); if ((assemblyReference.Flags & AssemblyFlags.PublicKey) != 0) { an.SetPublicKey(publicKeyOrToken); } else { an.SetPublicKeyToken(publicKeyOrToken); } // TODO: ContentType - depends on newer version of the System.Reflection contract return Context.ResolveAssembly(an); } public NativeFormatModule GetModuleFromNamespaceDefinition(NamespaceDefinitionHandle handle) { while (true) { NamespaceDefinition namespaceDef = _metadataReader.GetNamespaceDefinition(handle); Handle parentScopeOrDefinitionHandle = namespaceDef.ParentScopeOrNamespace; if (parentScopeOrDefinitionHandle.HandleType == HandleType.ScopeDefinition) { return (NativeFormatModule)GetObject(parentScopeOrDefinitionHandle, null); } else { handle = parentScopeOrDefinitionHandle.ToNamespaceDefinitionHandle(_metadataReader); } } } public NativeFormatModule GetModuleFromAssemblyName(string assemblyNameString) { AssemblyBindResult bindResult; RuntimeAssemblyName assemblyName = AssemblyNameParser.Parse(assemblyNameString); Exception failureException; if (!AssemblyBinderImplementation.Instance.Bind(assemblyName, out bindResult, out failureException)) { throw failureException; } var moduleList = Internal.Runtime.TypeLoader.ModuleList.Instance; NativeFormatModuleInfo primaryModule = moduleList.GetModuleInfoForMetadataReader(bindResult.Reader); // If this isn't the primary module, defer to that module to load the MetadataUnit if (primaryModule != _module) { return Context.ResolveMetadataUnit(primaryModule).GetModule(bindResult.ScopeDefinitionHandle); } // Setup arguments and allocate the NativeFormatModule ArrayBuilder<NativeFormatModule.QualifiedScopeDefinition> qualifiedScopes = new ArrayBuilder<NativeFormatModule.QualifiedScopeDefinition>(); qualifiedScopes.Add(new NativeFormatModule.QualifiedScopeDefinition(this, bindResult.ScopeDefinitionHandle)); foreach (QScopeDefinition scope in bindResult.OverflowScopes) { NativeFormatModuleInfo module = moduleList.GetModuleInfoForMetadataReader(scope.Reader); ScopeDefinitionHandle scopeHandle = scope.Handle; NativeFormatMetadataUnit metadataUnit = Context.ResolveMetadataUnit(module); qualifiedScopes.Add(new NativeFormatModule.QualifiedScopeDefinition(metadataUnit, scopeHandle)); } return new NativeFormatModule(Context, qualifiedScopes.ToArray()); } } }
/* * Copyright (C) 2004 Bruno Fernandez-Ruiz <[email protected]> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace Caffeine.Caffeinator { using System; using System.Collections; using System.IO; using System.Text; public class ClassFile { ConstantPool[] constantPool; ushort accessFlags; ushort thisClass; ushort superClass; ushort[] interfaces; FieldInfo[] fields; MethodInfo[] methods; AttributeInfo[] attributes; public ClassFile(Stream s) { BigEndianBinaryReader reader = new BigEndianBinaryReader(s); /* ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_info fields[fields_count]; u2 methods_count; method_info methods[methods_count]; u2 attributes_count; attribute_info attributes[attributes_count]; } */ uint magic = reader.ReadUInt32(); if (magic != 0xCAFEBABE) { throw new ApplicationException("Bad magic in class: " + magic); } ushort minorVersion = reader.ReadUInt16(); ushort majorVersion = reader.ReadUInt16(); if (majorVersion < 45 || majorVersion > 48) { throw new ApplicationException("Unsupported class version (" + majorVersion + '.' + minorVersion + ")"); } constantPool = ReadConstantPool(reader); accessFlags = reader.ReadUInt16(); thisClass = reader.ReadUInt16(); superClass = reader.ReadUInt16(); interfaces = ReadInterfaces(reader); fields = ReadFields(reader); methods = ReadMethods(reader); attributes = ReadAttributes(reader); } public string Name { get { return GetClassName(thisClass); } } public void BuildClass(Class c, ClassFactory factory) { // accessFlags c.AccessFlags = (Class.AccessFlag) accessFlags; // thisClass c.InternalName = GetClassName(thisClass); // superClass c.AddBaseType(factory.LoadClass(GetClassName(superClass))); // interfaces foreach (ushort iface in interfaces) { c.AddBaseType(factory.LoadClass(GetClassName(iface))); } // fields foreach (FieldInfo info in fields) { Field f = new Field(c); f.AccessFlags = (Field.AccessFlag) info.AccessFlags; f.Name = GetUtf8(info.NameIndex); f.Signature = GetUtf8(info.DescriptorIndex); f.Descriptor = ProcessDescriptor(f.Signature, factory); c.AddField(f); } // methods foreach (MethodInfo info in methods) { Method m = new Method(c); m.AccessFlags = (Method.AccessFlag) info.AccessFlags; m.Name = GetUtf8(info.NameIndex); m.Signature = GetUtf8(info.DescriptorIndex); ProcessMethodDescriptorString(m, m.Signature, factory); c.AddMethod(m); } } void ProcessMethodDescriptorString(Method m, string value, ClassFactory factory) { string args = value.Substring(1, value.IndexOf(')') - 1); int index = 0; while (index < args.Length) { string arg = args.Substring(index); Descriptor d = ProcessDescriptor (arg, factory); if (d.IsBasicType) { index++; } else if (d.IsObjectType) { index += d.Class.InternalName.Length + 2; // Ljava/util/List; } else { index++; // [ Descriptor componentType = d; while ((componentType = componentType.Component).IsArrayType) { index++; // [ } if (componentType.IsBasicType) { index++; // [B } else { index += componentType.Class.InternalName.Length + 2; // Ljava/util/List; } } m.AddArgument(d); } m.Return = ProcessDescriptor(value.Substring(value.IndexOf(')') + 1), factory); } const string OBJECT_TYPE = "ObjectType"; const string ARRAY_TYPE = "ArrayType"; static Hashtable baseTypes; static ClassFile() { baseTypes = new Hashtable(); baseTypes['B'] = "byte"; baseTypes['C'] = "char"; baseTypes['D'] = "double"; baseTypes['F'] = "float"; baseTypes['I'] = "int"; baseTypes['J'] = "long"; baseTypes['L'] = OBJECT_TYPE; baseTypes['S'] = "short"; baseTypes['Z'] = "bool"; baseTypes['['] = ARRAY_TYPE; baseTypes['V'] = "void"; } static string GetTypeForDescriptor(string descriptor) { if (descriptor.Equals(String.Empty)) { return ""; } return (string) baseTypes[descriptor[0]]; } static string GetTypeForObjectType(string type) { // Ljava/lang/Object; return type.Substring(1, type.IndexOf(';') - 1); } static Descriptor ProcessDescriptor(string value, ClassFactory factory) { Descriptor descriptor = new Descriptor(); string t = GetTypeForDescriptor(value); if (ARRAY_TYPE.Equals(t)) { descriptor.Component = ProcessDescriptor(value.Substring(1), factory); descriptor.IsArrayType = true; } else if (OBJECT_TYPE.Equals(t)) { string des = GetTypeForObjectType(value); descriptor.Class = factory.LoadClass(des); descriptor.IsObjectType = true; } else { descriptor.Class = factory.LoadClass(t); descriptor.IsBasicType = true; } return descriptor; } string GetClassName(ushort index) { ConstantPool item = constantPool[index]; if (item == null) { return null; // this is the case for java/lang/Object } if (item.ConstantType != ConstantType.Class) { throw new ApplicationException("Wrong class format"); } return GetUtf8(item.NameIndex); } string GetUtf8(ushort index) { ConstantPool item = constantPool[index]; if (item.ConstantType != ConstantType.Utf8) { throw new ApplicationException("Wrong class format"); } return item.String; } ushort[] ReadInterfaces(BigEndianBinaryReader reader) { ushort interfacesCount = reader.ReadUInt16(); ushort[] interfaces = new ushort[interfacesCount]; if (interfacesCount == 0) { return interfaces; } for (ushort i = 0; i < interfacesCount; i++) { interfaces[i] = reader.ReadUInt16(); } return interfaces; } MethodInfo[] ReadMethods(BigEndianBinaryReader reader) { ushort methodsCount = reader.ReadUInt16(); MethodInfo[] methods = new MethodInfo[methodsCount]; if (methodsCount == 0) { return methods; } for (ushort i = 0; i < methodsCount; i++) { /* method_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } */ MethodInfo method; method.AccessFlags = reader.ReadUInt16(); method.NameIndex = reader.ReadUInt16(); method.DescriptorIndex = reader.ReadUInt16(); method.Attributes = ReadAttributes(reader); methods[i] = method; } return methods; } FieldInfo[] ReadFields(BigEndianBinaryReader reader) { ushort fieldsCount = reader.ReadUInt16(); FieldInfo[] fields = new FieldInfo[fieldsCount]; if (fieldsCount == 0) { return fields; } for (ushort i = 0; i < fieldsCount; i++) { /* field_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } */ FieldInfo field; field.AccessFlags = reader.ReadUInt16(); field.NameIndex = reader.ReadUInt16(); field.DescriptorIndex = reader.ReadUInt16(); field.Attributes = ReadAttributes(reader); fields[i] = field; } return fields; } AttributeInfo[] ReadAttributes(BigEndianBinaryReader reader) { /* u2 attributes_count; attribute_info attributes[attributes_count]; */ ushort attributesCount = reader.ReadUInt16(); AttributeInfo[] attributes = new AttributeInfo[attributesCount]; if (attributesCount == 0) { return attributes; } for (ushort i = 0; i < attributesCount; i++) { /* attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } */ AttributeInfo attr; attr.AttributeNameIndex = reader.ReadUInt16(); attr.Bytes = reader.ReadBytes(reader.ReadUInt32()); attributes[i] = attr; } return attributes; } ConstantPool[] ReadConstantPool(BigEndianBinaryReader reader) { ushort constantPoolCount = reader.ReadUInt16(); ConstantPool[] constantPool = new ConstantPool[constantPoolCount]; //Console.WriteLine("Reading {0} ConstantPool items", constantPoolCount); // JVM Spec 4.1. // The value of the constant_pool_count item is equal to the number // of entries in the constant_pool table plus one. A constant_pool // index is considered valid if it is greater than zero and less // than constant_pool_count, with the exception for constants of // type long and double noted in 4.4.5. for (ushort i = 1; i < constantPoolCount; i++) { ConstantType tag = (ConstantType) reader.ReadByte(); ConstantPool item = new ConstantPool(); constantPool[i] = item; switch (tag) { case ConstantType.Class: /* CONSTANT_Class_info { u1 tag; u2 name_index; } */ item.ConstantType = ConstantType.Class; item.NameIndex = reader.ReadUInt16(); break; case ConstantType.Fieldref: /* CONSTANT_Fieldref_info { u1 tag; u2 class_index; u2 name_and_type_index; } */ item.ConstantType = ConstantType.Fieldref; item.ClassIndex = reader.ReadUInt16(); item.NameAndTypeIndex = reader.ReadUInt16(); break; case ConstantType.Methodref: /* CONSTANT_Methodref_info { u1 tag; u2 class_index; u2 name_and_type_index; } */ item.ConstantType = ConstantType.Methodref; item.ClassIndex = reader.ReadUInt16(); item.NameAndTypeIndex = reader.ReadUInt16(); break; case ConstantType.InterfaceMethodref: /* CONSTANT_InterfaceMethodref_info { u1 tag; u2 class_index; u2 name_and_type_index; } */ item.ConstantType = ConstantType.InterfaceMethodref; item.ClassIndex = reader.ReadUInt16(); item.NameAndTypeIndex = reader.ReadUInt16(); break; case ConstantType.String: /* CONSTANT_String_info { u1 tag; u2 string_index; } */ item.ConstantType = ConstantType.String; item.StringIndex = reader.ReadUInt16(); break; case ConstantType.Integer: /* CONSTANT_Integer_info { u1 tag; u4 bytes; } */ item.ConstantType = ConstantType.Integer; item.Integer = reader.ReadInt32(); break; case ConstantType.Float: /* CONSTANT_Float_info { u1 tag; u4 bytes; } */ item.ConstantType = ConstantType.Float; item.Float = reader.ReadSingle(); break; case ConstantType.Long: /* CONSTANT_Long_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ item.ConstantType = ConstantType.Long; item.Long = reader.ReadInt64(); // JVM Spec. 4.4.5. // All 8-byte constants take up two entries in the // constant_pool table of the class file. If a // CONSTANT_Long_info or CONSTANT_Double_info structure // is the item in the constant_pool table at index n, // then the next usable item in the pool is located at // index n+2. The constant_pool index n+1 must be valid // but is considered unusable.2 // 2 In retrospect, making 8-byte constants take two // constant pool entries was a poor choice. ++i; break; case ConstantType.Double: /* CONSTANT_Double_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ item.ConstantType = ConstantType.Double; item.Double = reader.ReadDouble(); // JVM Spec. 4.4.5. // All 8-byte constants take up two entries in the // constant_pool table of the class file. If a // CONSTANT_Long_info or CONSTANT_Double_info structure // is the item in the constant_pool table at index n, // then the next usable item in the pool is located at // index n+2. The constant_pool index n+1 must be valid // but is considered unusable.2 // 2 In retrospect, making 8-byte constants take two // constant pool entries was a poor choice. ++i; break; case ConstantType.NameAndType: /* CONSTANT_NameAndType_info { u1 tag; u2 name_index; u2 descriptor_index; } */ item.ConstantType = ConstantType.NameAndType; item.NameIndex = reader.ReadUInt16(); item.DescriptorIndex = reader.ReadUInt16(); break; case ConstantType.Utf8: /* CONSTANT_Utf8_info { u1 tag; u2 length; u1 bytes[length]; } */ item.ConstantType = ConstantType.Utf8; item.String = reader.ReadString(reader.ReadUInt16()); break; default: throw new ApplicationException("Wrong ConstantType: " + tag); } } return constantPool; } enum ConstantType : byte { Class = 7, Fieldref = 9, Methodref = 10, InterfaceMethodref = 11, String = 8, Integer = 3, Float = 4, Long = 5, Double = 6, NameAndType = 12, Utf8 = 1 } // we use the class ConstantPool as a C "union" class ConstantPool { public ConstantType ConstantType; public ushort NameIndex; public ushort ClassIndex; public ushort NameAndTypeIndex; public ushort StringIndex; public int Integer; public float Float; public long Long; public double Double; public ushort DescriptorIndex; public string String; public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("ConstantType").Append(ConstantType) .Append(" NameIndex ").Append(NameIndex) .Append(" ClassIndex ").Append(ClassIndex) .Append(" NameAndTypeIndex ").Append(NameAndTypeIndex) .Append(" StringIndex ").Append(StringIndex) .Append(" Integer ").Append(Integer) .Append(" Float ").Append(Float) .Append(" Long ").Append(Long) .Append(" Double ").Append(Double) .Append(" DescriptorIndex ").Append(DescriptorIndex) .Append(" String ").Append(String); return builder.ToString(); } } struct FieldInfo { public ushort AccessFlags; public ushort NameIndex; public ushort DescriptorIndex; public AttributeInfo[] Attributes; } struct AttributeInfo { public ushort AttributeNameIndex; public byte[] Bytes; } struct MethodInfo { public ushort AccessFlags; public ushort NameIndex; public ushort DescriptorIndex; public AttributeInfo[] Attributes; } class BigEndianBinaryReader { Stream s; public BigEndianBinaryReader(Stream s) { this.s = s; } public uint ReadUInt32() { byte[] bytes = new byte[4]; bytes[3] = (byte) s.ReadByte(); bytes[2] = (byte) s.ReadByte(); bytes[1] = (byte) s.ReadByte(); bytes[0] = (byte) s.ReadByte(); return BitConverter.ToUInt32(bytes, 0); } public ushort ReadUInt16() { byte[] bytes = new byte[2]; bytes[1] = (byte) s.ReadByte(); bytes[0] = (byte) s.ReadByte(); return BitConverter.ToUInt16(bytes, 0); } public long ReadInt64() { uint lowBits = ReadUInt32(); uint highBits = ReadUInt32(); return (long) (lowBits << 32) + highBits; } public double ReadDouble() { return BitConverter.Int64BitsToDouble(ReadInt64()); } public int ReadInt32() { byte[] bytes = new byte[4]; bytes[3] = (byte) s.ReadByte(); bytes[2] = (byte) s.ReadByte(); bytes[1] = (byte) s.ReadByte(); bytes[0] = (byte) s.ReadByte(); return BitConverter.ToInt32(bytes, 0); } public float ReadSingle() { byte[] bytes = new byte[4]; bytes[3] = (byte) s.ReadByte(); bytes[2] = (byte) s.ReadByte(); bytes[1] = (byte) s.ReadByte(); bytes[0] = (byte) s.ReadByte(); return BitConverter.ToSingle(bytes, 0); } public byte ReadByte() { return (byte) s.ReadByte(); } public byte[] ReadBytes(uint length) { byte[] bytes = new byte[length]; for (uint i = 0; i < length; i++) { bytes[i] = (byte) s.ReadByte(); } return bytes; } public string ReadString(ushort length) { byte[] utf8 = ReadBytes(length); // TODO implement UTF8, right now only ASCII supported return System.Text.ASCIIEncoding.ASCII.GetString(utf8, 0, length); //return BitConverter.ToString(utf8); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // The RegexInterpreter executes a block of regular expression codes // while consuming input. using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexInterpreter : RegexRunner { private readonly RegexCode _code; private readonly CultureInfo _culture; private int _operator; private int _codepos; private bool _rightToLeft; private bool _caseInsensitive; private const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. public RegexInterpreter(RegexCode code, CultureInfo culture) { Debug.Assert(code != null, "code cannot be null."); Debug.Assert(culture != null, "culture cannot be null."); _code = code; _culture = culture; } protected override void InitTrackCount() { runtrackcount = _code.TrackCount; } private void Advance(int i) { _codepos += (i + 1); SetOperator(_code.Codes[_codepos]); } private void Goto(int newpos) { // when branching backward, ensure storage if (newpos < _codepos) EnsureStorage(); SetOperator(_code.Codes[newpos]); _codepos = newpos; } private void Textto(int newpos) { runtextpos = newpos; } private void Trackto(int newpos) { runtrackpos = runtrack.Length - newpos; } private int Textstart() { return runtextstart; } private int Textpos() { return runtextpos; } // push onto the backtracking stack private int Trackpos() { return runtrack.Length - runtrackpos; } private void TrackPush() { runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1, int I2) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1, int I2, int I3) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = I3; runtrack[--runtrackpos] = _codepos; } private void TrackPush2(int I1) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = -_codepos; } private void TrackPush2(int I1, int I2) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = -_codepos; } private void Backtrack() { int newpos = runtrack[runtrackpos++]; #if DEBUG if (runmatch.Debug) { if (newpos < 0) Debug.WriteLine(" Backtracking (back2) to code position " + (-newpos)); else Debug.WriteLine(" Backtracking to code position " + newpos); } #endif if (newpos < 0) { newpos = -newpos; SetOperator(_code.Codes[newpos] | RegexCode.Back2); } else { SetOperator(_code.Codes[newpos] | RegexCode.Back); } // When branching backward, ensure storage if (newpos < _codepos) EnsureStorage(); _codepos = newpos; } private void SetOperator(int op) { _caseInsensitive = (0 != (op & RegexCode.Ci)); _rightToLeft = (0 != (op & RegexCode.Rtl)); _operator = op & ~(RegexCode.Rtl | RegexCode.Ci); } private void TrackPop() { runtrackpos++; } // pop framesize items from the backtracking stack private void TrackPop(int framesize) { runtrackpos += framesize; } // Technically we are actually peeking at items already popped. So if you want to // get and pop the top item from the stack, you do // TrackPop(); // TrackPeek(); private int TrackPeek() { return runtrack[runtrackpos - 1]; } // get the ith element down on the backtracking stack private int TrackPeek(int i) { return runtrack[runtrackpos - i - 1]; } // Push onto the grouping stack private void StackPush(int I1) { runstack[--runstackpos] = I1; } private void StackPush(int I1, int I2) { runstack[--runstackpos] = I1; runstack[--runstackpos] = I2; } private void StackPop() { runstackpos++; } // pop framesize items from the grouping stack private void StackPop(int framesize) { runstackpos += framesize; } // Technically we are actually peeking at items already popped. So if you want to // get and pop the top item from the stack, you do // StackPop(); // StackPeek(); private int StackPeek() { return runstack[runstackpos - 1]; } // get the ith element down on the grouping stack private int StackPeek(int i) { return runstack[runstackpos - i - 1]; } private int Operator() { return _operator; } private int Operand(int i) { return _code.Codes[_codepos + i + 1]; } private int Leftchars() { return runtextpos - runtextbeg; } private int Rightchars() { return runtextend - runtextpos; } private int Bump() { return _rightToLeft ? -1 : 1; } private int Forwardchars() { return _rightToLeft ? runtextpos - runtextbeg : runtextend - runtextpos; } private char Forwardcharnext() { char ch = (_rightToLeft ? runtext[--runtextpos] : runtext[runtextpos++]); return (_caseInsensitive ? _culture.TextInfo.ToLower(ch) : ch); } private bool Stringmatch(string str) { int c; int pos; if (!_rightToLeft) { if (runtextend - runtextpos < (c = str.Length)) return false; pos = runtextpos + c; } else { if (runtextpos - runtextbeg < (c = str.Length)) return false; pos = runtextpos; } if (!_caseInsensitive) { while (c != 0) if (str[--c] != runtext[--pos]) return false; } else { while (c != 0) if (str[--c] != _culture.TextInfo.ToLower(runtext[--pos])) return false; } if (!_rightToLeft) { pos += str.Length; } runtextpos = pos; return true; } private bool Refmatch(int index, int len) { int c; int pos; int cmpos; if (!_rightToLeft) { if (runtextend - runtextpos < len) return false; pos = runtextpos + len; } else { if (runtextpos - runtextbeg < len) return false; pos = runtextpos; } cmpos = index + len; c = len; if (!_caseInsensitive) { while (c-- != 0) if (runtext[--cmpos] != runtext[--pos]) return false; } else { while (c-- != 0) if (_culture.TextInfo.ToLower(runtext[--cmpos]) != _culture.TextInfo.ToLower(runtext[--pos])) return false; } if (!_rightToLeft) { pos += len; } runtextpos = pos; return true; } private void Backwardnext() { runtextpos += _rightToLeft ? 1 : -1; } private char CharAt(int j) { return runtext[j]; } protected override bool FindFirstChar() { if (0 != (_code.Anchors & (RegexFCD.Beginning | RegexFCD.Start | RegexFCD.EndZ | RegexFCD.End))) { if (!_code.RightToLeft) { if ((0 != (_code.Anchors & RegexFCD.Beginning) && runtextpos > runtextbeg) || (0 != (_code.Anchors & RegexFCD.Start) && runtextpos > runtextstart)) { runtextpos = runtextend; return false; } if (0 != (_code.Anchors & RegexFCD.EndZ) && runtextpos < runtextend - 1) { runtextpos = runtextend - 1; } else if (0 != (_code.Anchors & RegexFCD.End) && runtextpos < runtextend) { runtextpos = runtextend; } } else { if ((0 != (_code.Anchors & RegexFCD.End) && runtextpos < runtextend) || (0 != (_code.Anchors & RegexFCD.EndZ) && (runtextpos < runtextend - 1 || (runtextpos == runtextend - 1 && CharAt(runtextpos) != '\n'))) || (0 != (_code.Anchors & RegexFCD.Start) && runtextpos < runtextstart)) { runtextpos = runtextbeg; return false; } if (0 != (_code.Anchors & RegexFCD.Beginning) && runtextpos > runtextbeg) { runtextpos = runtextbeg; } } if (_code.BMPrefix != null) { return _code.BMPrefix.IsMatch(runtext, runtextpos, runtextbeg, runtextend); } return true; // found a valid start or end anchor } else if (_code.BMPrefix != null) { runtextpos = _code.BMPrefix.Scan(runtext, runtextpos, runtextbeg, runtextend); if (runtextpos == -1) { runtextpos = (_code.RightToLeft ? runtextbeg : runtextend); return false; } return true; } else if (_code.FCPrefix == null) { return true; } _rightToLeft = _code.RightToLeft; _caseInsensitive = _code.FCPrefix.GetValueOrDefault().CaseInsensitive; string set = _code.FCPrefix.GetValueOrDefault().Prefix; if (RegexCharClass.IsSingleton(set)) { char ch = RegexCharClass.SingletonChar(set); for (int i = Forwardchars(); i > 0; i--) { if (ch == Forwardcharnext()) { Backwardnext(); return true; } } } else { for (int i = Forwardchars(); i > 0; i--) { if (RegexCharClass.CharInClass(Forwardcharnext(), set)) { Backwardnext(); return true; } } } return false; } protected override void Go() { Goto(0); int advance = -1; while (true) { if (advance >= 0) { // https://github.com/dotnet/coreclr/pull/14850#issuecomment-342256447 // Single common Advance call to reduce method size; and single method inline point Advance(advance); advance = -1; } #if DEBUG if (runmatch.Debug) { DumpState(); } #endif CheckTimeout(); switch (Operator()) { case RegexCode.Stop: return; case RegexCode.Nothing: break; case RegexCode.Goto: Goto(Operand(0)); continue; case RegexCode.Testref: if (!IsMatched(Operand(0))) break; advance = 1; continue; case RegexCode.Lazybranch: TrackPush(Textpos()); advance = 1; continue; case RegexCode.Lazybranch | RegexCode.Back: TrackPop(); Textto(TrackPeek()); Goto(Operand(0)); continue; case RegexCode.Setmark: StackPush(Textpos()); TrackPush(); advance = 0; continue; case RegexCode.Nullmark: StackPush(-1); TrackPush(); advance = 0; continue; case RegexCode.Setmark | RegexCode.Back: case RegexCode.Nullmark | RegexCode.Back: StackPop(); break; case RegexCode.Getmark: StackPop(); TrackPush(StackPeek()); Textto(StackPeek()); advance = 0; continue; case RegexCode.Getmark | RegexCode.Back: TrackPop(); StackPush(TrackPeek()); break; case RegexCode.Capturemark: if (Operand(1) != -1 && !IsMatched(Operand(1))) break; StackPop(); if (Operand(1) != -1) TransferCapture(Operand(0), Operand(1), StackPeek(), Textpos()); else Capture(Operand(0), StackPeek(), Textpos()); TrackPush(StackPeek()); advance = 2; continue; case RegexCode.Capturemark | RegexCode.Back: TrackPop(); StackPush(TrackPeek()); Uncapture(); if (Operand(0) != -1 && Operand(1) != -1) Uncapture(); break; case RegexCode.Branchmark: { int matched; StackPop(); matched = Textpos() - StackPeek(); if (matched != 0) { // Nonempty match -> loop now TrackPush(StackPeek(), Textpos()); // Save old mark, textpos StackPush(Textpos()); // Make new mark Goto(Operand(0)); // Loop } else { // Empty match -> straight now TrackPush2(StackPeek()); // Save old mark advance = 1; // Straight } continue; } case RegexCode.Branchmark | RegexCode.Back: TrackPop(2); StackPop(); Textto(TrackPeek(1)); // Recall position TrackPush2(TrackPeek()); // Save old mark advance = 1; // Straight continue; case RegexCode.Branchmark | RegexCode.Back2: TrackPop(); StackPush(TrackPeek()); // Recall old mark break; // Backtrack case RegexCode.Lazybranchmark: { // We hit this the first time through a lazy loop and after each // successful match of the inner expression. It simply continues // on and doesn't loop. StackPop(); int oldMarkPos = StackPeek(); if (Textpos() != oldMarkPos) { // Nonempty match -> try to loop again by going to 'back' state if (oldMarkPos != -1) TrackPush(oldMarkPos, Textpos()); // Save old mark, textpos else TrackPush(Textpos(), Textpos()); } else { // The inner expression found an empty match, so we'll go directly to 'back2' if we // backtrack. In this case, we need to push something on the stack, since back2 pops. // However, in the case of ()+? or similar, this empty match may be legitimate, so push the text // position associated with that empty match. StackPush(oldMarkPos); TrackPush2(StackPeek()); // Save old mark } advance = 1; continue; } case RegexCode.Lazybranchmark | RegexCode.Back: { // After the first time, Lazybranchmark | RegexCode.Back occurs // with each iteration of the loop, and therefore with every attempted // match of the inner expression. We'll try to match the inner expression, // then go back to Lazybranchmark if successful. If the inner expression // fails, we go to Lazybranchmark | RegexCode.Back2 int pos; TrackPop(2); pos = TrackPeek(1); TrackPush2(TrackPeek()); // Save old mark StackPush(pos); // Make new mark Textto(pos); // Recall position Goto(Operand(0)); // Loop continue; } case RegexCode.Lazybranchmark | RegexCode.Back2: // The lazy loop has failed. We'll do a true backtrack and // start over before the lazy loop. StackPop(); TrackPop(); StackPush(TrackPeek()); // Recall old mark break; case RegexCode.Setcount: StackPush(Textpos(), Operand(0)); TrackPush(); advance = 1; continue; case RegexCode.Nullcount: StackPush(-1, Operand(0)); TrackPush(); advance = 1; continue; case RegexCode.Setcount | RegexCode.Back: StackPop(2); break; case RegexCode.Nullcount | RegexCode.Back: StackPop(2); break; case RegexCode.Branchcount: // StackPush: // 0: Mark // 1: Count { StackPop(2); int mark = StackPeek(); int count = StackPeek(1); int matched = Textpos() - mark; if (count >= Operand(1) || (matched == 0 && count >= 0)) { // Max loops or empty match -> straight now TrackPush2(mark, count); // Save old mark, count advance = 2; // Straight } else { // Nonempty match -> count+loop now TrackPush(mark); // remember mark StackPush(Textpos(), count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } continue; } case RegexCode.Branchcount | RegexCode.Back: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (= current pos, discarded) // 1: Count TrackPop(); StackPop(2); if (StackPeek(1) > 0) { // Positive -> can go straight Textto(StackPeek()); // Zap to mark TrackPush2(TrackPeek(), StackPeek(1) - 1); // Save old mark, old count advance = 2; // Straight continue; } StackPush(TrackPeek(), StackPeek(1) - 1); // recall old mark, old count break; case RegexCode.Branchcount | RegexCode.Back2: // TrackPush: // 0: Previous mark // 1: Previous count TrackPop(2); StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, old count break; // Backtrack case RegexCode.Lazybranchcount: // StackPush: // 0: Mark // 1: Count { StackPop(2); int mark = StackPeek(); int count = StackPeek(1); if (count < 0) { // Negative count -> loop now TrackPush2(mark); // Save old mark StackPush(Textpos(), count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } else { // Nonneg count -> straight now TrackPush(mark, count, Textpos()); // Save mark, count, position advance = 2; // Straight } continue; } case RegexCode.Lazybranchcount | RegexCode.Back: // TrackPush: // 0: Mark // 1: Count // 2: Textpos { TrackPop(3); int mark = TrackPeek(); int textpos = TrackPeek(2); if (TrackPeek(1) < Operand(1) && textpos != mark) { // Under limit and not empty match -> loop Textto(textpos); // Recall position StackPush(textpos, TrackPeek(1) + 1); // Make new mark, incr count TrackPush2(mark); // Save old mark Goto(Operand(0)); // Loop continue; } else { // Max loops or empty match -> backtrack StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, count break; // backtrack } } case RegexCode.Lazybranchcount | RegexCode.Back2: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (== current pos, discarded) // 1: Count TrackPop(); StackPop(2); StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, count break; // Backtrack case RegexCode.Setjump: StackPush(Trackpos(), Crawlpos()); TrackPush(); advance = 0; continue; case RegexCode.Setjump | RegexCode.Back: StackPop(2); break; case RegexCode.Backjump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); while (Crawlpos() != StackPeek(1)) Uncapture(); break; case RegexCode.Forejump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); TrackPush(StackPeek(1)); advance = 0; continue; case RegexCode.Forejump | RegexCode.Back: // TrackPush: // 0: Crawlpos TrackPop(); while (Crawlpos() != TrackPeek()) Uncapture(); break; case RegexCode.Bol: if (Leftchars() > 0 && CharAt(Textpos() - 1) != '\n') break; advance = 0; continue; case RegexCode.Eol: if (Rightchars() > 0 && CharAt(Textpos()) != '\n') break; advance = 0; continue; case RegexCode.Boundary: if (!IsBoundary(Textpos(), runtextbeg, runtextend)) break; advance = 0; continue; case RegexCode.Nonboundary: if (IsBoundary(Textpos(), runtextbeg, runtextend)) break; advance = 0; continue; case RegexCode.ECMABoundary: if (!IsECMABoundary(Textpos(), runtextbeg, runtextend)) break; advance = 0; continue; case RegexCode.NonECMABoundary: if (IsECMABoundary(Textpos(), runtextbeg, runtextend)) break; advance = 0; continue; case RegexCode.Beginning: if (Leftchars() > 0) break; advance = 0; continue; case RegexCode.Start: if (Textpos() != Textstart()) break; advance = 0; continue; case RegexCode.EndZ: if (Rightchars() > 1 || Rightchars() == 1 && CharAt(Textpos()) != '\n') break; advance = 0; continue; case RegexCode.End: if (Rightchars() > 0) break; advance = 0; continue; case RegexCode.One: if (Forwardchars() < 1 || Forwardcharnext() != (char)Operand(0)) break; advance = 1; continue; case RegexCode.Notone: if (Forwardchars() < 1 || Forwardcharnext() == (char)Operand(0)) break; advance = 1; continue; case RegexCode.Set: if (Forwardchars() < 1 || !RegexCharClass.CharInClass(Forwardcharnext(), _code.Strings[Operand(0)])) break; advance = 1; continue; case RegexCode.Multi: { if (!Stringmatch(_code.Strings[Operand(0)])) break; advance = 1; continue; } case RegexCode.Ref: { int capnum = Operand(0); if (IsMatched(capnum)) { if (!Refmatch(MatchIndex(capnum), MatchLength(capnum))) break; } else { if ((runregex.roptions & RegexOptions.ECMAScript) == 0) break; } advance = 1; continue; } case RegexCode.Onerep: { int c = Operand(1); if (Forwardchars() < c) break; char ch = (char)Operand(0); while (c-- > 0) if (Forwardcharnext() != ch) goto BreakBackward; advance = 2; continue; } case RegexCode.Notonerep: { int c = Operand(1); if (Forwardchars() < c) break; char ch = (char)Operand(0); while (c-- > 0) if (Forwardcharnext() == ch) goto BreakBackward; advance = 2; continue; } case RegexCode.Setrep: { int c = Operand(1); if (Forwardchars() < c) break; string set = _code.Strings[Operand(0)]; while (c-- > 0) { // Check the timeout every 2000th iteration. The additional if check // in every iteration can be neglected as the cost of the CharInClass // check is many times higher. if ((uint)c % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(), set)) goto BreakBackward; } advance = 2; continue; } case RegexCode.Oneloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); char ch = (char)Operand(0); int i; for (i = c; i > 0; i--) { if (Forwardcharnext() != ch) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); advance = 2; continue; } case RegexCode.Notoneloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); char ch = (char)Operand(0); int i; for (i = c; i > 0; i--) { if (Forwardcharnext() == ch) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); advance = 2; continue; } case RegexCode.Setloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); string set = _code.Strings[Operand(0)]; int i; for (i = c; i > 0; i--) { // Check the timeout every 2000th iteration. The additional if check // in every iteration can be neglected as the cost of the CharInClass // check is many times higher. if ((uint)i % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(), set)) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); advance = 2; continue; } case RegexCode.Oneloop | RegexCode.Back: case RegexCode.Notoneloop | RegexCode.Back: { TrackPop(2); int i = TrackPeek(); int pos = TrackPeek(1); Textto(pos); if (i > 0) TrackPush(i - 1, pos - Bump()); advance = 2; continue; } case RegexCode.Setloop | RegexCode.Back: { TrackPop(2); int i = TrackPeek(); int pos = TrackPeek(1); Textto(pos); if (i > 0) TrackPush(i - 1, pos - Bump()); advance = 2; continue; } case RegexCode.Onelazy: case RegexCode.Notonelazy: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); if (c > 0) TrackPush(c - 1, Textpos()); advance = 2; continue; } case RegexCode.Setlazy: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); if (c > 0) TrackPush(c - 1, Textpos()); advance = 2; continue; } case RegexCode.Onelazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (Forwardcharnext() != (char)Operand(0)) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); advance = 2; continue; } case RegexCode.Notonelazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (Forwardcharnext() == (char)Operand(0)) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); advance = 2; continue; } case RegexCode.Setlazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (!RegexCharClass.CharInClass(Forwardcharnext(), _code.Strings[Operand(0)])) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); advance = 2; continue; } default: throw NotImplemented.ByDesignWithMessage(SR.UnimplementedState); } BreakBackward: ; // "break Backward" comes here: Backtrack(); } } #if DEBUG internal override void DumpState() { base.DumpState(); Debug.WriteLine(" " + _code.OpcodeDescription(_codepos) + ((_operator & RegexCode.Back) != 0 ? " Back" : "") + ((_operator & RegexCode.Back2) != 0 ? " Back2" : "")); Debug.WriteLine(""); } #endif } }
/* * Copyright (c) Contributors * 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 OpenSim 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 Mono.Addins; using System; using System.Reflection; using System.Threading; using System.Text; using System.Net; using System.Net.Sockets; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Scripting; using System.Collections.Generic; using System.Text.RegularExpressions; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")] public class JsonStoreScriptModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IConfig m_config = null; private bool m_enabled = false; private Scene m_scene = null; private IScriptModuleComms m_comms; private IJsonStoreModule m_store; private Dictionary<UUID,HashSet<UUID>> m_scriptStores = new Dictionary<UUID,HashSet<UUID>>(); #region Region Module interface // ----------------------------------------------------------------- /// <summary> /// Name of this shared module is it's class name /// </summary> // ----------------------------------------------------------------- public string Name { get { return this.GetType().Name; } } // ----------------------------------------------------------------- /// <summary> /// Initialise this shared module /// </summary> /// <param name="scene">this region is getting initialised</param> /// <param name="source">nini config, we are not using this</param> // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { try { if ((m_config = config.Configs["JsonStore"]) == null) { // There is no configuration, the module is disabled // m_log.InfoFormat("[JsonStoreScripts] no configuration info"); return; } m_enabled = m_config.GetBoolean("Enabled", m_enabled); } catch (Exception e) { m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message); return; } if (m_enabled) m_log.DebugFormat("[JsonStoreScripts]: module is enabled"); } // ----------------------------------------------------------------- /// <summary> /// everything is loaded, perform post load configuration /// </summary> // ----------------------------------------------------------------- public void PostInitialise() { } // ----------------------------------------------------------------- /// <summary> /// Nothing to do on close /// </summary> // ----------------------------------------------------------------- public void Close() { } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void AddRegion(Scene scene) { scene.EventManager.OnScriptReset += HandleScriptReset; scene.EventManager.OnRemoveScript += HandleScriptReset; } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void RemoveRegion(Scene scene) { scene.EventManager.OnScriptReset -= HandleScriptReset; scene.EventManager.OnRemoveScript -= HandleScriptReset; // need to remove all references to the scene in the subscription // list to enable full garbage collection of the scene object } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- private void HandleScriptReset(uint localID, UUID itemID) { HashSet<UUID> stores; lock (m_scriptStores) { if (! m_scriptStores.TryGetValue(itemID, out stores)) return; m_scriptStores.Remove(itemID); } foreach (UUID id in stores) m_store.DestroyStore(id); } // ----------------------------------------------------------------- /// <summary> /// Called when all modules have been added for a region. This is /// where we hook up events /// </summary> // ----------------------------------------------------------------- public void RegionLoaded(Scene scene) { if (m_enabled) { m_scene = scene; m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) { m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined"); m_enabled = false; return; } m_store = m_scene.RequestModuleInterface<IJsonStoreModule>(); if (m_store == null) { m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined"); m_enabled = false; return; } try { m_comms.RegisterScriptInvocations(this); m_comms.RegisterConstants(this); } catch (Exception e) { // See http://opensimulator.org/mantis/view.php?id=5971 for more information m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message); m_enabled = false; } } } /// ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public Type ReplaceableInterface { get { return null; } } #endregion #region ScriptConstantsInterface [ScriptConstant] public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined; [ScriptConstant] public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object; [ScriptConstant] public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array; [ScriptConstant] public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value; [ScriptConstant] public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined; [ScriptConstant] public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean; [ScriptConstant] public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer; [ScriptConstant] public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float; [ScriptConstant] public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String; #endregion #region ScriptInvocationInteface // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID) { UUID uuid = UUID.Zero; if (! m_store.AttachObjectStore(hostID)) GenerateRuntimeError("Failed to create Json store"); return hostID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value) { UUID uuid = UUID.Zero; if (! m_store.CreateStore(value, ref uuid)) GenerateRuntimeError("Failed to create Json store"); lock (m_scriptStores) { if (! m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID] = new HashSet<UUID>(); m_scriptStores[scriptID].Add(uuid); } return uuid; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID) { lock(m_scriptStores) { if (m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID].Remove(storeID); } return m_store.DestroyStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID) { return m_store.TestStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param), null, "JsonStoreScriptModule.DoJsonRezObject"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier), null, "JsonStoreScriptModule.JsonReadNotecard"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonWriteNotecard(reqID,hostID,scriptID,storeID,path,name), null, "JsonStoreScriptModule.DoJsonWriteNotecard"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist) { string ipath = ConvertList2Path(pathlist); string opath; if (JsonStore.CanonicalPathExpression(ipath,out opath)) return opath; // This won't parse if passed to the other routines as opposed to // returning an empty string which is a valid path and would overwrite // the entire store return "**INVALID**"; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetNodeType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetValueType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,false) ? 1 : 0; } [ScriptInvocation] public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,true) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.RemoveValue(storeID,path) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.GetArrayLength(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,false,out value); return value; } [ScriptInvocation] public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,true, out value); return value; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonTakeValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonTakeValue"); return reqID; } [ScriptInvocation] public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonTakeValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonTakeValueJson"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonReadValue"); return reqID; } [ScriptInvocation] public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonReadValueJson"); return reqID; } #endregion // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void GenerateRuntimeError(string msg) { m_log.InfoFormat("[JsonStore] runtime error: {0}",msg); throw new Exception("JsonStore Runtime Error: " + msg); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void DispatchValue(UUID scriptID, UUID reqID, string value) { m_comms.DispatchReply(scriptID,1,value,reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.TakeValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.ReadValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadNotecard( UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID assetID; if (!UUID.TryParse(notecardIdentifier, out assetID)) { SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard); } AssetBase a = m_scene.AssetService.Get(assetID.ToString()); if (a == null) GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID)); if (a.Type != (sbyte)AssetType.Notecard) GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID)); m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID); try { string jsondata = SLUtil.ParseNotecardToString(a.Data); int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0; m_comms.DispatchReply(scriptID, result, "", reqID.ToString()); return; } catch(SLUtil.NotANotecardFormatException e) { m_log.WarnFormat("[JsonStoreScripts]: Notecard parsing failed; assetId {0} at line number {1}", assetID.ToString(), e.lineNumber); } catch (Exception e) { m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message); } GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID)); m_comms.DispatchReply(scriptID, 0, "", reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name) { string data; if (! m_store.GetValue(storeID,path,true, out data)) { m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString()); return; } SceneObjectPart host = m_scene.GetSceneObjectPart(hostID); // Create new asset UUID assetID = UUID.Random(); AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString()); asset.Description = "Json store"; int textLength = data.Length; data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + textLength.ToString() + "\n" + data + "}\n"; asset.Data = Util.UTF8.GetBytes(data); m_scene.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(host.UUID); taskItem.ParentID = host.UUID; taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int)AssetType.Notecard; taskItem.InvType = (int)InventoryType.Notecard; taskItem.OwnerID = host.OwnerID; taskItem.CreatorID = host.OwnerID; taskItem.BasePermissions = (uint)PermissionMask.All; taskItem.CurrentPermissions = (uint)PermissionMask.All; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint)PermissionMask.All; taskItem.GroupID = host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.FullID; host.Inventory.AddInventoryItem(taskItem, false); m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// Convert a list of values that are path components to a single string path /// </summary> // ----------------------------------------------------------------- protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$"); private string ConvertList2Path(object[] pathlist) { string path = ""; for (int i = 0; i < pathlist.Length; i++) { string token = ""; if (pathlist[i] is string) { token = pathlist[i].ToString(); // Check to see if this is a bare number which would not be a valid // identifier otherwise if (m_ArrayPattern.IsMatch(token)) token = '[' + token + ']'; } else if (pathlist[i] is int) { token = "[" + pathlist[i].ToString() + "]"; } else { token = "." + pathlist[i].ToString() + "."; } path += token + "."; } return path; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param) { if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W)) { GenerateRuntimeError("Invalid rez rotation"); return; } SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID); if (host == null) { GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'",hostID)); return; } // hpos = host.RootPart.GetWorldPosition() // float dist = (float)llVecDist(hpos, pos); // if (dist > m_ScriptDistanceFactor * 10.0f) // return; TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name); if (item == null) { GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'",name)); return; } if (item.InvType != (int)InventoryType.Object) { GenerateRuntimeError("Can't create requested object; object is missing from database"); return; } List<SceneObjectGroup> objlist; List<Vector3> veclist; bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist); if (! success) { GenerateRuntimeError("Failed to create object"); return; } int totalPrims = 0; foreach (SceneObjectGroup group in objlist) totalPrims += group.PrimCount; if (! m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos)) { GenerateRuntimeError("Not allowed to create the object"); return; } if (! m_scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) host.RootPart.Inventory.RemoveInventoryItem(item.ItemID); } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup group = objlist[i]; Vector3 curpos = pos + veclist[i]; if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } group.FromPartID = host.RootPart.UUID; m_scene.AddNewSceneObject(group, true, curpos, rot, vel); UUID storeID = group.UUID; if (! m_store.CreateStore(param, ref storeID)) { GenerateRuntimeError("Unable to create jsonstore for new object"); continue; } // We can only call this after adding the scene object, since the scene object references the scene // to find out if scripts should be activated at all. group.RootPart.SetDieAtEdge(true); group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3); group.ResumeScripts(); group.ScheduleGroupForFullUpdate(); // send the reply back to the host object, use the integer param to indicate the number // of remaining objects m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString()); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/snapshot/lodging_snapshot_response_record.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply.Snapshot { /// <summary>Holder for reflection information generated from supply/snapshot/lodging_snapshot_response_record.proto</summary> public static partial class LodgingSnapshotResponseRecordReflection { #region Descriptor /// <summary>File descriptor for supply/snapshot/lodging_snapshot_response_record.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LodgingSnapshotResponseRecordReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjZzdXBwbHkvc25hcHNob3QvbG9kZ2luZ19zbmFwc2hvdF9yZXNwb25zZV9y", "ZWNvcmQucHJvdG8SG2hvbG1zLnR5cGVzLnN1cHBseS5zbmFwc2hvdBodcHJp", "bWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aH3ByaW1pdGl2ZS9tb25ldGFy", "eV9hbW91bnQucHJvdG8aK3N1cHBseS9yb29tX3R5cGVzL3Jvb21fdHlwZV9p", "bmRpY2F0b3IucHJvdG8aL3N1cHBseS9zbmFwc2hvdC9sb2RnaW5nX3NuYXBz", "aG90X3F1YW50aXR5LnByb3RvIsECCh1Mb2RnaW5nU25hcHNob3RSZXNwb25z", "ZVJlY29yZBJDCglyb29tX3R5cGUYASABKAsyMC5ob2xtcy50eXBlcy5zdXBw", "bHkucm9vbV90eXBlcy5Sb29tVHlwZUluZGljYXRvchIwCgRkYXRlGAIgASgL", "MiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBiTG9jYWxEYXRlEjwKDW9mZmVy", "ZWRfcHJpY2UYAyABKAsyJS5ob2xtcy50eXBlcy5wcmltaXRpdmUuTW9uZXRh", "cnlBbW91bnQSSAoKcXVhbnRpdGllcxgEIAEoCzI0LmhvbG1zLnR5cGVzLnN1", "cHBseS5zbmFwc2hvdC5Mb2RnaW5nU25hcHNob3RRdWFudGl0eRIhChlyZXF1", "aXJlZF9yZXNlcnZhdGlvbl90YWdzGAUgAygJQi9aD3N1cHBseS9zbmFwc2hv", "dKoCG0hPTE1TLlR5cGVzLlN1cHBseS5TbmFwc2hvdGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotQuantityReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotResponseRecord), global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotResponseRecord.Parser, new[]{ "RoomType", "Date", "OfferedPrice", "Quantities", "RequiredReservationTags" }, null, null, null) })); } #endregion } #region Messages public sealed partial class LodgingSnapshotResponseRecord : pb::IMessage<LodgingSnapshotResponseRecord> { private static readonly pb::MessageParser<LodgingSnapshotResponseRecord> _parser = new pb::MessageParser<LodgingSnapshotResponseRecord>(() => new LodgingSnapshotResponseRecord()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LodgingSnapshotResponseRecord> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotResponseRecordReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LodgingSnapshotResponseRecord() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LodgingSnapshotResponseRecord(LodgingSnapshotResponseRecord other) : this() { RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; Date = other.date_ != null ? other.Date.Clone() : null; OfferedPrice = other.offeredPrice_ != null ? other.OfferedPrice.Clone() : null; Quantities = other.quantities_ != null ? other.Quantities.Clone() : null; requiredReservationTags_ = other.requiredReservationTags_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LodgingSnapshotResponseRecord Clone() { return new LodgingSnapshotResponseRecord(this); } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 1; private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 2; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } /// <summary>Field number for the "offered_price" field.</summary> public const int OfferedPriceFieldNumber = 3; private global::HOLMS.Types.Primitive.MonetaryAmount offeredPrice_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount OfferedPrice { get { return offeredPrice_; } set { offeredPrice_ = value; } } /// <summary>Field number for the "quantities" field.</summary> public const int QuantitiesFieldNumber = 4; private global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotQuantity quantities_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotQuantity Quantities { get { return quantities_; } set { quantities_ = value; } } /// <summary>Field number for the "required_reservation_tags" field.</summary> public const int RequiredReservationTagsFieldNumber = 5; private static readonly pb::FieldCodec<string> _repeated_requiredReservationTags_codec = pb::FieldCodec.ForString(42); private readonly pbc::RepeatedField<string> requiredReservationTags_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> RequiredReservationTags { get { return requiredReservationTags_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LodgingSnapshotResponseRecord); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LodgingSnapshotResponseRecord other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(RoomType, other.RoomType)) return false; if (!object.Equals(Date, other.Date)) return false; if (!object.Equals(OfferedPrice, other.OfferedPrice)) return false; if (!object.Equals(Quantities, other.Quantities)) return false; if(!requiredReservationTags_.Equals(other.requiredReservationTags_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (roomType_ != null) hash ^= RoomType.GetHashCode(); if (date_ != null) hash ^= Date.GetHashCode(); if (offeredPrice_ != null) hash ^= OfferedPrice.GetHashCode(); if (quantities_ != null) hash ^= Quantities.GetHashCode(); hash ^= requiredReservationTags_.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 (roomType_ != null) { output.WriteRawTag(10); output.WriteMessage(RoomType); } if (date_ != null) { output.WriteRawTag(18); output.WriteMessage(Date); } if (offeredPrice_ != null) { output.WriteRawTag(26); output.WriteMessage(OfferedPrice); } if (quantities_ != null) { output.WriteRawTag(34); output.WriteMessage(Quantities); } requiredReservationTags_.WriteTo(output, _repeated_requiredReservationTags_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } if (offeredPrice_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OfferedPrice); } if (quantities_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Quantities); } size += requiredReservationTags_.CalculateSize(_repeated_requiredReservationTags_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LodgingSnapshotResponseRecord other) { if (other == null) { return; } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } RoomType.MergeFrom(other.RoomType); } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } if (other.offeredPrice_ != null) { if (offeredPrice_ == null) { offeredPrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } OfferedPrice.MergeFrom(other.OfferedPrice); } if (other.quantities_ != null) { if (quantities_ == null) { quantities_ = new global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotQuantity(); } Quantities.MergeFrom(other.Quantities); } requiredReservationTags_.Add(other.requiredReservationTags_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } input.ReadMessage(roomType_); break; } case 18: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } case 26: { if (offeredPrice_ == null) { offeredPrice_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(offeredPrice_); break; } case 34: { if (quantities_ == null) { quantities_ = new global::HOLMS.Types.Supply.Snapshot.LodgingSnapshotQuantity(); } input.ReadMessage(quantities_); break; } case 42: { requiredReservationTags_.AddEntriesFrom(input, _repeated_requiredReservationTags_codec); break; } } } } } #endregion } #endregion Designer generated code
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class SlicerEditor : EditorWindow { private GameObject objectToSlice; private List<SlicerPlane> slicers = new List<SlicerPlane>(); private List<SlicerPlane> randomSlicers = new List<SlicerPlane>(); private SlicerPlane extraSlicer; private bool random; private bool rigidbody; private bool collidable; private bool isConvex; private bool isHallow; private bool isBlended; private int sliceVal = 1; private bool showSlicers; private Material blendedMat = null; [MenuItem("Window/SlicerEditor")] static void ShowWindow() { EditorWindow window = EditorWindow.GetWindow(typeof(SlicerEditor)); window.autoRepaintOnSceneChange = true; window.position = new Rect(400,400,300,600); window.maxSize = new Vector2(300,600); window.minSize = new Vector2(300,600); } static void Init() { EditorWindow window = EditorWindow.GetWindow(typeof(SlicerEditor)); window.autoRepaintOnSceneChange = true; window.position = new Rect(400,400,300,600); window.maxSize = new Vector2(300,600); window.minSize = new Vector2(300,600); } void OnGUI() { GUILayout.BeginArea( new Rect(0, 0, 300, 600)); EditorGUILayout.HelpBox("Object Slicer Framework and Editor \nCreated by David Arayan 2013",MessageType.None); objectToSlice = EditorGUILayout.ObjectField(objectToSlice, typeof(GameObject), true) as GameObject; if (objectToSlice == null) { EditorGUILayout.HelpBox("GameObject is Null \nSelect GameObject to expand further options",MessageType.Info); GUILayout.EndArea(); return; } if (objectToSlice.GetComponent<SlicerStore>() == null) { objectToSlice.AddComponent<SlicerStore>(); } SlicerStore store = objectToSlice.GetComponent<SlicerStore>(); isConvex = store.isConvex; isHallow = store.isHallow; // this is where we set our slice options GUILayout.BeginVertical(); EditorGUILayout.HelpBox("Slice Generator Options",MessageType.None); GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Object Convex",MessageType.None); isConvex = EditorGUILayout.Toggle(isConvex); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Object Hallow",MessageType.None); if (isConvex) { isHallow = EditorGUILayout.Toggle(isHallow); } else { isHallow = EditorGUILayout.Toggle(true); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Material Blend",MessageType.None); isBlended = EditorGUILayout.Toggle(isBlended); GUILayout.EndHorizontal(); if (!isBlended) { EditorGUILayout.HelpBox("Cross Section Material",MessageType.None); blendedMat = EditorGUILayout.ObjectField(blendedMat, typeof(Material), true) as Material; } else { blendedMat = null; } store.isHallow = isHallow; store.isConvex = isConvex; GUILayout.EndVertical(); EditorGUILayout.HelpBox("Instance Options",MessageType.None); random = store.isRandom; collidable = store.isCollidable; rigidbody = store.isRigidbody; GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Randomized Slice",MessageType.None); random = EditorGUILayout.Toggle(random); store.isRandom = random; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Slices Collidable",MessageType.None); if (rigidbody) { collidable = true; } collidable = EditorGUILayout.Toggle(collidable); store.isCollidable = collidable; GUILayout.EndHorizontal(); if (collidable) { GUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("Slices Rigidbody",MessageType.None); rigidbody = EditorGUILayout.Toggle(rigidbody); GUILayout.EndHorizontal(); } store.isRigidbody = rigidbody; store.isRandom = random; if (random) { GUILayout.BeginVertical(); EditorGUILayout.HelpBox("Slice Ammount 1 - 20",MessageType.None); sliceVal = EditorGUILayout.IntSlider(sliceVal,1,20); GUILayout.EndVertical(); if (store.slicedMeshes.Count == 0) { if (GUILayout.Button("Slice Object")) { List<GameObject> obj = new List<GameObject>(); // lets create our temporary GO's for (int i = 0; i < sliceVal; i++) { GameObject tmpObj = new GameObject(); randomSlicers.Add(tmpObj.AddComponent<SlicerPlane>()); tmpObj.transform.position = store.getRandomPosInMesh(); tmpObj.transform.rotation = Random.rotation; obj.Add(tmpObj); } store.slice(randomSlicers, blendedMat); randomSlicers.Clear(); for (int i = 0; i < obj.Count; i++) { DestroyImmediate(obj[i]); } } } else { if (GUILayout.Button("Instantiate Slices")) { store.instantiate(); } if (GUILayout.Button("Clear Prev Slices")) { store.slicedMeshes.Clear(); } } } else { // loop and remove null slicers for (int i = 0; i < slicers.Count; i++) { if (slicers[i] == null) { slicers.RemoveAt(i); } } GUILayout.BeginVertical(); EditorGUILayout.HelpBox("Add a Slicer Plane to the List",MessageType.None); extraSlicer = EditorGUILayout.ObjectField(extraSlicer, typeof(SlicerPlane), true) as SlicerPlane; if (GUILayout.Button("Add Slicer Plane")) { if (extraSlicer != null) { slicers.Add(extraSlicer); extraSlicer = null; } } GUILayout.EndVertical(); GUILayout.BeginVertical(); showSlicers = EditorGUILayout.Foldout(showSlicers, " Slicer Plane List"); if (showSlicers) { for (int i = 0; i < slicers.Count; i++) { slicers[i] = EditorGUILayout.ObjectField(slicers[i], typeof(SlicerPlane), true) as SlicerPlane; } if (slicers.Count > 0) { if (GUILayout.Button("Clear All Slicers")) { slicers.Clear(); } } } if (store.slicedMeshes.Count == 0) { if (slicers.Count > 0) { if (GUILayout.Button("Slice Object")) { store.slice(slicers, blendedMat); } } else { EditorGUILayout.HelpBox("There are no Slicers Available \nAdd some Slicer Planes",MessageType.Info); GUILayout.EndArea(); return; } } else { if (GUILayout.Button("Instantiate Slices")) { store.instantiate(); } if (GUILayout.Button("Clear Prev Slices")) { store.slicedMeshes.Clear(); } } } GUILayout.EndArea(); } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.ComponentModel.Composition; using Sce.Atf.Adaptation; using Sce.Atf.Applications; using Sce.Atf.Dom; using Sce.Sled.Lua.Dom; using Sce.Sled.Lua.Resources; using Sce.Sled.Shared; using Sce.Sled.Shared.Services; namespace Sce.Sled.Lua { [Export(typeof(SledLuaLocalVariableService))] [PartCreationPolicy(CreationPolicy.Shared)] sealed class SledLuaLocalVariableService : SledLuaBaseVariableService<SledLuaVarLocalListType, SledLuaVarLocalType> { #region SledLuaBaseVariableService Overrides protected override void Initialize() { m_luaCallStackService = SledServiceInstance.Get<ISledLuaCallStackService>(); m_luaCallStackService.Clearing += LuaCallStackServiceClearing; m_luaCallStackService.LevelAdding += LuaCallStackServiceLevelAdding; m_luaCallStackService.StackLevelChanging += LuaCallStackServiceStackLevelChanging; m_luaCallStackService.StackLevelChanged += LuaCallStackServiceStackLevelChanged; } protected override string ShortName { get { return Localization.SledLuaLocalsTitleShort; } } protected override string PopupPrefix { get { return "[L]"; } } protected override SledLuaTreeListViewEditor Editor { get { return m_editor; } } protected override DomNodeType NodeType { get { return SledLuaSchema.SledLuaVarLocalType.Type; } } protected override void OnDebugServiceDataReady(object sender, SledDebugServiceEventArgs e) { var typeCode = (Scmp.LuaTypeCodes)e.Scmp.TypeCode; switch (typeCode) { //case Scmp.LuaTypeCodes.LuaVarLocalBegin: // break; case Scmp.LuaTypeCodes.LuaVarLocal: { if (!LuaWatchedVariableService.ReceivingWatchedVariables) { var local = LuaVarScmpService.GetScmpBlobAsLuaLocalVar(); RemoteTargetCallStackLocal(local); } } break; //case Scmp.LuaTypeCodes.LuaVarLocalEnd: // break; case Scmp.LuaTypeCodes.LuaVarLocalLookupBegin: OnDebugServiceLookupBegin(); break; case Scmp.LuaTypeCodes.LuaVarLocalLookupEnd: OnDebugServiceLookupEnd(); break; } } protected override void OnLuaVariableFilterServiceFiltered(object sender, SledLuaVariableFilterService.FilteredEventArgs e) { if (e.NodeType != NodeType) return; if (m_luaCallStackService.CurrentStackLevel >= Collection.Count) return; m_editor.View = Collection[m_luaCallStackService.CurrentStackLevel]; } #endregion #region ISledLuaCallStackService Events private void LuaCallStackServiceClearing(object sender, EventArgs e) { m_editor.View = null; if (m_luaCallStackService.CurrentStackLevel != 0) { if (Collection.Count > 0) Collection[0].ResetExpandedStates(); } foreach (var collection in Collection) collection.Variables.Clear(); } private void LuaCallStackServiceLevelAdding(object sender, SledLuaCallStackServiceEventArgs e) { if ((e.NewLevel + 1) > Collection.Count) { var root = new DomNode( SledLuaSchema.SledLuaVarLocalListType.Type, SledLuaSchema.SledLuaVarLocalsRootElement); var locals = root.As<SledLuaVarLocalListType>(); locals.Name = string.Format( "{0}{1}{2}{3}", ProjectService.ProjectName, Resource.Space, Resource.LuaLocals, e.NewLevel); locals.DomNode.AttributeChanged += DomNodeAttributeChanged; Collection.Add(locals); } if ((e.NewLevel == 0) && (Collection.Count > 0)) m_editor.View = Collection[0]; } private void LuaCallStackServiceStackLevelChanging(object sender, SledLuaCallStackServiceEventArgs e) { foreach (var collection in Collection) collection.ValidationBeginning(); m_editor.View = null; Collection[e.OldLevel].SaveExpandedStates(); m_editor.View = Collection[e.NewLevel]; } private void LuaCallStackServiceStackLevelChanged(object sender, SledLuaCallStackServiceEventArgs e) { foreach (var collection in Collection) collection.ValidationEnded(); } #endregion #region Member Methods private void RemoteTargetCallStackLocal(SledLuaVarLocalType variable) { var iCount = Collection.Count; if (iCount <= variable.Level) return; Collection[variable.Level].ValidationBeginning(); // Add any locations LuaVarLocationService.AddLocations(variable); // Do any filtering variable.Visible = !LuaVariableFilterService.IsVariableFiltered(variable); // Figure out where to insert if (!LookingUp) { Collection[variable.Level].Variables.Add(variable); } else { if (ListInsert.Count > 0) ListInsert[0].Locals.Add(variable); else { SledOutDevice.OutLine( SledMessageType.Error, "[SledLuaLocalVariableService] " + "Failed to add local: {0}", variable.Name); } } } #endregion private ISledLuaCallStackService m_luaCallStackService; #pragma warning disable 649 // Field is never assigned [Import] private SledLuaLocalsEditor m_editor; #pragma warning restore 649 #region Private Classes [Export(typeof(SledLuaLocalsEditor))] [PartCreationPolicy(CreationPolicy.Shared)] private class SledLuaLocalsEditor : SledLuaTreeListViewEditor { [ImportingConstructor] public SledLuaLocalsEditor() : base( Localization.SledLuaLocalsTitle, null, SledLuaVarBaseType.ColumnNames, StandardControlGroup.Right) { } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: RemotingConfiguration.cs ** ** Purpose: Classes for interfacing with remoting configuration ** settings ** ** ===========================================================*/ using System; using System.Security; using System.Security.Permissions; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Contexts; using System.Runtime.CompilerServices; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.Runtime.Remoting { // Configuration - provides static methods interfacing with // configuration settings. [System.Runtime.InteropServices.ComVisible(true)] public static class RemotingConfiguration { private static volatile bool s_ListeningForActivationRequests = false; [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [Obsolete("Use System.Runtime.Remoting.RemotingConfiguration.Configure(string fileName, bool ensureSecurity) instead.", false)] public static void Configure(String filename) { Configure(filename, false/*ensureSecurity*/); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static void Configure(String filename, bool ensureSecurity) { RemotingConfigHandler.DoConfiguration(filename, ensureSecurity); // Set a flag in the VM to mark that remoting is configured // This will enable us to decide if activation for MBR // objects should go through the managed codepath RemotingServices.InternalSetRemoteActivationConfigured(); } // Configure public static String ApplicationName { get { if (!RemotingConfigHandler.HasApplicationNameBeenSet()) return null; else return RemotingConfigHandler.ApplicationName; } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] set { RemotingConfigHandler.ApplicationName = value; } } // ApplicationName // The application id is prepended to object uri's. public static String ApplicationId { [System.Security.SecurityCritical] // auto-generated_required get { return Identity.AppDomainUniqueId; } } // ApplicationId public static String ProcessId { [System.Security.SecurityCritical] // auto-generated_required get { return Identity.ProcessGuid;} } public static CustomErrorsModes CustomErrorsMode { get { return RemotingConfigHandler.CustomErrorsMode; } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] set { RemotingConfigHandler.CustomErrorsMode = value; } } public static bool CustomErrorsEnabled(bool isLocalRequest) { switch (CustomErrorsMode) { case CustomErrorsModes.Off: return false; case CustomErrorsModes.On: return true; case CustomErrorsModes.RemoteOnly: return(!isLocalRequest); default: return true; } } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterActivatedServiceType(Type type) { ActivatedServiceTypeEntry entry = new ActivatedServiceTypeEntry(type); RemotingConfiguration.RegisterActivatedServiceType(entry); } // RegisterActivatedServiceType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterActivatedServiceType(ActivatedServiceTypeEntry entry) { RemotingConfigHandler.RegisterActivatedServiceType(entry); // make sure we're listening for activation requests // (all registrations for activated service types will come through here) if (!s_ListeningForActivationRequests) { s_ListeningForActivationRequests = true; ActivationServices.StartListeningForRemoteRequests(); } } // RegisterActivatedServiceType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterWellKnownServiceType( Type type, String objectUri, WellKnownObjectMode mode) { WellKnownServiceTypeEntry wke = new WellKnownServiceTypeEntry(type, objectUri, mode); RemotingConfiguration.RegisterWellKnownServiceType(wke); } // RegisterWellKnownServiceType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterWellKnownServiceType(WellKnownServiceTypeEntry entry) { RemotingConfigHandler.RegisterWellKnownServiceType(entry); } // RegisterWellKnownServiceType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterActivatedClientType(Type type, String appUrl) { ActivatedClientTypeEntry acte = new ActivatedClientTypeEntry(type, appUrl); RemotingConfiguration.RegisterActivatedClientType(acte); } // RegisterActivatedClientType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterActivatedClientType(ActivatedClientTypeEntry entry) { RemotingConfigHandler.RegisterActivatedClientType(entry); // all registrations for activated client types will come through here RemotingServices.InternalSetRemoteActivationConfigured(); } // RegisterActivatedClientType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterWellKnownClientType(Type type, String objectUrl) { WellKnownClientTypeEntry wke = new WellKnownClientTypeEntry(type, objectUrl); RemotingConfiguration.RegisterWellKnownClientType(wke); } // RegisterWellKnownClientType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static void RegisterWellKnownClientType(WellKnownClientTypeEntry entry) { RemotingConfigHandler.RegisterWellKnownClientType(entry); // all registrations for wellknown client types will come through here RemotingServices.InternalSetRemoteActivationConfigured(); } // RegisterWellKnownClientType [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static ActivatedServiceTypeEntry[] GetRegisteredActivatedServiceTypes() { return RemotingConfigHandler.GetRegisteredActivatedServiceTypes(); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static WellKnownServiceTypeEntry[] GetRegisteredWellKnownServiceTypes() { return RemotingConfigHandler.GetRegisteredWellKnownServiceTypes(); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static ActivatedClientTypeEntry[] GetRegisteredActivatedClientTypes() { return RemotingConfigHandler.GetRegisteredActivatedClientTypes(); } [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static WellKnownClientTypeEntry[] GetRegisteredWellKnownClientTypes() { return RemotingConfigHandler.GetRegisteredWellKnownClientTypes(); } // This is used at the client end to check if an activation needs // to go remote. [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static ActivatedClientTypeEntry IsRemotelyActivatedClientType(Type svrType) { if (svrType == null) throw new ArgumentNullException("svrType"); RuntimeType rt = svrType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); return RemotingConfigHandler.IsRemotelyActivatedClientType(rt); } // This is used at the client end to check if an activation needs // to go remote. [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static ActivatedClientTypeEntry IsRemotelyActivatedClientType(String typeName, String assemblyName) { return RemotingConfigHandler.IsRemotelyActivatedClientType(typeName, assemblyName); } // This is used at the client end to check if a "new Foo" needs to // happen via a Connect() under the covers. [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static WellKnownClientTypeEntry IsWellKnownClientType(Type svrType) { if (svrType == null) throw new ArgumentNullException("svrType"); RuntimeType rt = svrType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); return RemotingConfigHandler.IsWellKnownClientType(rt); } // This is used at the client end to check if a "new Foo" needs to // happen via a Connect() under the covers. [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static WellKnownClientTypeEntry IsWellKnownClientType(String typeName, String assemblyName) { return RemotingConfigHandler.IsWellKnownClientType(typeName, assemblyName); } // This is used at the server end to check if a type being activated // is explicitly allowed by the server. [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] public static bool IsActivationAllowed(Type svrType) { RuntimeType rt = svrType as RuntimeType; if (svrType != null && rt == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); return RemotingConfigHandler.IsActivationAllowed(rt); } } // class Configuration // // The following classes are used to register and retrieve remoted type information // // Base class for all configuration entries [System.Runtime.InteropServices.ComVisible(true)] public class TypeEntry { String _typeName; String _assemblyName; RemoteAppEntry _cachedRemoteAppEntry = null; protected TypeEntry() { // Forbid creation of this class by outside users... } public String TypeName { get { return _typeName; } set {_typeName = value;} } public String AssemblyName { get { return _assemblyName; } set {_assemblyName = value;} } internal void CacheRemoteAppEntry(RemoteAppEntry entry) {_cachedRemoteAppEntry = entry;} internal RemoteAppEntry GetRemoteAppEntry() { return _cachedRemoteAppEntry;} } [System.Runtime.InteropServices.ComVisible(true)] public class ActivatedClientTypeEntry : TypeEntry { String _appUrl; // url of application to activate the type in // optional data IContextAttribute[] _contextAttributes = null; public ActivatedClientTypeEntry(String typeName, String assemblyName, String appUrl) { if (typeName == null) throw new ArgumentNullException("typeName"); if (assemblyName == null) throw new ArgumentNullException("assemblyName"); if (appUrl == null) throw new ArgumentNullException("appUrl"); Contract.EndContractBlock(); TypeName = typeName; AssemblyName = assemblyName; _appUrl = appUrl; } // ActivatedClientTypeEntry public ActivatedClientTypeEntry(Type type, String appUrl) { if (type == null) throw new ArgumentNullException("type"); if (appUrl == null) throw new ArgumentNullException("appUrl"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly")); TypeName = type.FullName; AssemblyName = rtType.GetRuntimeAssembly().GetSimpleName(); _appUrl = appUrl; } // ActivatedClientTypeEntry public String ApplicationUrl { get { return _appUrl; } } public Type ObjectType { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable get { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeTypeHandle.GetTypeByName(TypeName + ", " + AssemblyName, ref stackMark); } } public IContextAttribute[] ContextAttributes { get { return _contextAttributes; } set { _contextAttributes = value; } } public override String ToString() { return "type='" + TypeName + ", " + AssemblyName + "'; appUrl=" + _appUrl; } } // class ActivatedClientTypeEntry [System.Runtime.InteropServices.ComVisible(true)] public class ActivatedServiceTypeEntry : TypeEntry { // optional data IContextAttribute[] _contextAttributes = null; public ActivatedServiceTypeEntry(String typeName, String assemblyName) { if (typeName == null) throw new ArgumentNullException("typeName"); if (assemblyName == null) throw new ArgumentNullException("assemblyName"); Contract.EndContractBlock(); TypeName = typeName; AssemblyName = assemblyName; } public ActivatedServiceTypeEntry(Type type) { if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly")); TypeName = type.FullName; AssemblyName = rtType.GetRuntimeAssembly().GetSimpleName(); } public Type ObjectType { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable get { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeTypeHandle.GetTypeByName(TypeName + ", " + AssemblyName, ref stackMark); } } public IContextAttribute[] ContextAttributes { get { return _contextAttributes; } set { _contextAttributes = value; } } public override String ToString() { return "type='" + TypeName + ", " + AssemblyName + "'"; } } // class ActivatedServiceTypeEntry [System.Runtime.InteropServices.ComVisible(true)] public class WellKnownClientTypeEntry : TypeEntry { String _objectUrl; // optional data String _appUrl = null; // url of application to associate this object with public WellKnownClientTypeEntry(String typeName, String assemblyName, String objectUrl) { if (typeName == null) throw new ArgumentNullException("typeName"); if (assemblyName == null) throw new ArgumentNullException("assemblyName"); if (objectUrl == null) throw new ArgumentNullException("objectUrl"); Contract.EndContractBlock(); TypeName = typeName; AssemblyName = assemblyName; _objectUrl = objectUrl; } public WellKnownClientTypeEntry(Type type, String objectUrl) { if (type == null) throw new ArgumentNullException("type"); if (objectUrl == null) throw new ArgumentNullException("objectUrl"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); TypeName = type.FullName; AssemblyName = rtType.GetRuntimeAssembly().GetSimpleName(); _objectUrl = objectUrl; } public String ObjectUrl { get { return _objectUrl; } } public Type ObjectType { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable get { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeTypeHandle.GetTypeByName(TypeName + ", " + AssemblyName, ref stackMark); } } public String ApplicationUrl { get { return _appUrl; } set { _appUrl = value; } } public override String ToString() { String str = "type='" + TypeName + ", " + AssemblyName + "'; url=" + _objectUrl; if (_appUrl != null) str += "; appUrl=" + _appUrl; return str; } } // class WellKnownClientTypeEntry [System.Runtime.InteropServices.ComVisible(true)] public class WellKnownServiceTypeEntry : TypeEntry { String _objectUri; WellKnownObjectMode _mode; // optional data IContextAttribute[] _contextAttributes = null; public WellKnownServiceTypeEntry(String typeName, String assemblyName, String objectUri, WellKnownObjectMode mode) { if (typeName == null) throw new ArgumentNullException("typeName"); if (assemblyName == null) throw new ArgumentNullException("assemblyName"); if (objectUri == null) throw new ArgumentNullException("objectUri"); Contract.EndContractBlock(); TypeName = typeName; AssemblyName = assemblyName; _objectUri = objectUri; _mode = mode; } public WellKnownServiceTypeEntry(Type type, String objectUri, WellKnownObjectMode mode) { if (type == null) throw new ArgumentNullException("type"); if (objectUri == null) throw new ArgumentNullException("objectUri"); Contract.EndContractBlock(); if (!(type is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); TypeName = type.FullName; AssemblyName = type.Module.Assembly.FullName; _objectUri = objectUri; _mode = mode; } public String ObjectUri { get { return _objectUri; } } public WellKnownObjectMode Mode { get { return _mode; } } public Type ObjectType { [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable get { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeTypeHandle.GetTypeByName(TypeName + ", " + AssemblyName, ref stackMark); } } public IContextAttribute[] ContextAttributes { get { return _contextAttributes; } set { _contextAttributes = value; } } public override String ToString() { return "type='" + TypeName + ", " + AssemblyName + "'; objectUri=" + _objectUri + "; mode=" + _mode.ToString(); } } // class WellKnownServiceTypeEntry internal class RemoteAppEntry { String _remoteAppName; String _remoteAppURI; internal RemoteAppEntry(String appName, String appURI) { Contract.Assert(appURI != null, "Bad remote app URI"); _remoteAppName = appName; _remoteAppURI = appURI; } internal String GetAppURI() { return _remoteAppURI;} } // class RemoteAppEntry [System.Runtime.InteropServices.ComVisible(true)] public enum CustomErrorsModes { On, Off, RemoteOnly } } // namespace System.Runtime.Remoting
#if UNITY_EDITOR #pragma warning disable 0618 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Zios.Event { using Containers; //======================= // Enumerations //======================= [Flags] [Serializable] public enum EventDisabled : int { Add = 0x001, Call = 0x002, } [Flags] [Serializable] public enum EventDebug : int { Add = 0x001, Remove = 0x002, Call = 0x004, CallEmpty = 0x008, CallDeep = 0x010, CallTimer = 0x020, CallTimerZero = 0x040, CallUpdate = 0x080, Pause = 0x100, History = 0x200, } [Serializable] public enum EventDebugScope : int { Global = 0x001, Scoped = 0x002, } //======================= // Delegates //======================= public delegate void Method(); public delegate void MethodObject(object value); public delegate void MethodInt(int value); public delegate void MethodFloat(float value); public delegate void MethodString(string value); public delegate void MethodBool(bool value); public delegate void MethodVector2(Vector2 value); public delegate void MethodVector3(Vector3 value); public delegate void MethodFull(object[] values); public delegate void MethodStep(object collection, int value); public delegate object MethodReturn(); public delegate object MethodObjectReturn(object value); public delegate object MethodIntReturn(int value); public delegate object MethodFloatReturn(float value); public delegate object MethodStringReturn(string value); public delegate object MethodBoolReturn(bool value); public delegate object MethodVector2Return(Vector2 value); public delegate object MethodVector3Return(Vector3 value); //======================= // Main //======================= [InitializeOnLoad] public static class Events { [EnumMask] public static EventDisabled disabled; [EnumMask] public static EventDebugScope debugScope; [EnumMask] public static EventDebug debug; public static object all = "All"; public static object global = "Global"; public static EventListener emptyListener = new EventListener(); public static Dictionary<object, Dictionary<string, EventListener>> unique = new Dictionary<object, Dictionary<string, EventListener>>(); public static Dictionary<object, Dictionary<string, Dictionary<object, EventListener>>> cache = new Dictionary<object, Dictionary<string, Dictionary<object, EventListener>>>(); public static List<EventListener> listeners = new List<EventListener>(); public static Dictionary<object, List<string>> callers = new Dictionary<object, List<string>>(); public static Dictionary<object, List<string>> active = new Dictionary<object, List<string>>(); public static string lastCalled; public static FixedList<string> eventHistory = new FixedList<string>(15); public static List<EventListener> stack = new List<EventListener>(); static Events() { Events.callers.Clear(); Events.cache.Clear(); Events.listeners.RemoveAll(x => x.name != "On Events Reset" && (!x.permanent || x.occurrences == 0)); #if UNITY_EDITOR Action Repair = () => { var main = Locate.GetScenePath("@Main"); if (main.GetComponent<EventDetector>().IsNull()) { main.AddComponent<EventDetector>(); main.hideFlags = HideFlags.HideInHierarchy; } #if UNITY_THEMES main.hideFlags = HideFlags.HideAndDontSave; #endif }; Repair(); Events.Add("On Destroy", () => Utility.DelayCall(Repair)); #endif foreach (var listener in Events.listeners) { var scope = Events.cache.AddNew(listener.target).AddNew(listener.name); scope[listener.method] = listener; } Events.Call("On Events Reset"); } public static void Cleanup() { if (Application.isPlaying) { return; } foreach (var cached in Events.cache.Copy()) { foreach (var set in cached.Value.Copy()) { foreach (var eventPair in set.Value.Copy()) { var listener = eventPair.Value; Delegate method = (Delegate)listener.method; bool targetMissing = !listener.isStatic && listener.target.IsNull(); bool methodMissing = !listener.isStatic && method.Target.IsNull(); if (targetMissing || methodMissing || eventPair.Key.IsNull()) { listener.Remove(); } } if (set.Key.IsNull() || set.Value.Count < 1) { Events.cache[cached.Key].Remove(set.Key); } } if (cached.Key.IsNull() || cached.Value.Count < 1) { Events.cache.Remove(cached.Key); } } foreach (var listener in Events.listeners.Copy()) { Delegate method = (Delegate)listener.method; bool targetMissing = !listener.isStatic && listener.target.IsNull(); bool methodMissing = !listener.isStatic && method.Target.IsNull(); if (targetMissing || methodMissing) { listener.Remove(); } } foreach (var item in Events.callers.Copy()) { if (item.Key.IsNull()) { Events.callers.Remove(item.Key); } } } public static object Verify(object target = null) { if (target.IsNull()) { target = Events.global; } return target; } public static object[] VerifyAll(params object[] targets) { if (targets.Length < 1) { targets = new object[1] { Events.global }; } return targets; } public static void Empty() { } public static void Register(string name) { Events.Register(name, Events.Verify()); } public static void Register(string name, params object[] targets) { if (Events.HasDisabled("Add")) { return; } foreach (object target in targets) { if (target.IsNull()) { continue; } Events.callers.AddNew(target); Events.callers[target].AddNew(name); } } public static void AddStepper(string eventName, MethodStep method, IList collection, int passes = 1) { var stepper = new EventStepper(method, null, collection, passes); stepper.onComplete = () => Events.Remove(eventName, stepper.Step); Events.Add(eventName, stepper.Step).SetPermanent(); } public static EventListener Add(string name, Method method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodObject method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodFull method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodString method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodInt method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodFloat method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodBool method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodVector2 method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener Add(string name, MethodVector3 method, params object[] targets) { return Events.Add(name, (object)method, -1, targets); } public static EventListener AddLimited(string name, Method method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodObject method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodFull method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodString method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodInt method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodFloat method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodBool method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodVector2 method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener AddLimited(string name, MethodVector3 method, int amount = 1, params object[] targets) { return Events.Add(name, (object)method, amount, targets); } public static EventListener Add(string name, object method, int amount, params object[] targets) { if (Events.HasDisabled("Add")) { Debug.LogWarning("[Events] : Add attempted while Events disabled. " + name); return null; } targets = Events.VerifyAll(targets); var listener = Events.emptyListener; foreach (object current in targets) { var target = current; if (target.IsNull()) { continue; } if (Events.unique.ContainsKey(target) && Events.unique[target].ContainsKey(name)) { listener = Events.unique[target][name]; continue; } if (!Events.cache.AddNew(target).AddNew(name).ContainsKey(method)) { listener = new EventListener(); if (Events.HasDebug("Add")) { var info = (Delegate)method; Debug.Log("[Events] : Adding event -- " + Events.GetMethodName(info) + " -- " + name, target as UnityObject); } Events.listeners.Add(listener); Utility.DelayCall(Events.OnEventsChanged); } else { listener = Events.cache[target][name].AddNew(method); } listener.name = name; listener.method = method; listener.target = target; listener.occurrences = amount; listener.isStatic = ((Delegate)method).Target.IsNull(); Events.cache.AddNew(target).AddNew(listener.name)[listener.method] = listener; Events.cache.AddNew(Events.all).AddNew(listener.name)[listener.method] = listener; } return listener; } public static void OnEventsChanged() { Events.Call("On Events Changed"); } public static void Remove(string name, Method method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodObject method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodFull method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodString method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodInt method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodFloat method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodBool method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodVector2 method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, MethodVector3 method, params object[] targets) { Events.Remove(name, (object)method, targets); } public static void Remove(string name, object method, params object[] targets) { if (Events.HasDisabled("Add")) { return; } targets = Events.VerifyAll(targets); foreach (var target in targets) { var removals = Events.listeners.Where(x => x.method == method && x.target == target && x.name == name).ToList(); removals.ForEach(x => x.Remove()); } Utility.DelayCall(Events.OnEventsChanged); } public static void RemoveAll(string name, params object[] targets) { foreach (var target in targets) { Events.listeners.Where(x => x.target == target && x.name == name).ToList().ForEach(x => x.Remove()); } } public static void RemoveAll(params object[] targets) { if (Events.HasDisabled("Add")) { return; } targets = Events.VerifyAll(targets); foreach (var target in targets) { var removals = Events.listeners.Where(x => x.target == target || x.method.As<Delegate>().Target == target).ToList(); removals.ForEach(x => x.Remove()); Events.cache.AddNew(target).SelectMany(x => x.Value).Select(x => x.Value).ToList().ForEach(x => x.Remove()); Events.cache.Remove(target); } Utility.DelayCall(Events.OnEventsChanged); } public static Dictionary<object, EventListener> Get(string name) { return Events.Get(Events.global, name); } public static Dictionary<object, EventListener> Get(object target, string name) { return Events.cache.AddNew(target).AddNew(name); } public static bool HasListeners(object target, string name = "*") { target = Events.Verify(target); if (name == "*") { return Events.cache.ContainsKey(target); } return Events.cache.ContainsKey(target) && Events.cache[target].ContainsKey(name); } public static bool HasCallers(object target, string name = "*") { target = Events.Verify(target); if (name == "*") { return Events.callers.ContainsKey(target); } return Events.callers.ContainsKey(target) && Events.callers[target].Contains(name); } public static void SetPause(string type, string name, object target) { target = Events.Verify(target); if (Events.HasDebug("Pause")) { string message = "[Events] : " + type + " event -- " + Events.GetTargetName(target) + " -- " + name; Debug.Log(message, target as UnityObject); } foreach (var item in Events.Get(target, name)) { item.Value.paused = type == "Pausing"; } } public static void Pause(string name, object target = null) { Events.SetPause("Pausing", name, target); } public static void Resume(string name, object target = null) { Events.SetPause("Resuming", name, target); } public static void AddHistory(string name) { if (Events.HasDebug("History")) { int lastIndex = Events.eventHistory.Count - 1; if (lastIndex >= 0) { string last = Events.eventHistory[lastIndex]; string lastReal = last.Split("(")[0].Trim(); if (lastReal == name) { string value = last.Parse("(", ")"); int count = value.IsEmpty() ? 2 : value.ToInt() + 1; value = " (" + count.ToString() + ")"; Events.eventHistory[lastIndex] = name + value; return; } } Events.eventHistory.Add(name); } } public static void Rest(string name, float seconds) { Events.Rest(Events.global, name, seconds); } public static void Rest(object target, string name, float seconds) { foreach (var item in Events.Get(target, name)) { item.Value.Rest(seconds); } } public static void SetCooldown(string name, float seconds) { Events.SetCooldown(Events.global, name, seconds); } public static void SetCooldown(object target, string name, float seconds) { foreach (var item in Events.Get(target, name)) { item.Value.SetCooldown(seconds); } } public static void DelayCall(string name, float delay = 0.5f, params object[] values) { Events.DelayCall(Events.global, "Global", name, delay, values); } public static void DelayCall(object key, string name, float delay = 0.5f, params object[] values) { Events.DelayCall(Events.global, key, name, delay, values); } public static void DelayCall(object target, object key, string name, float delay = 0.5f, params object[] values) { if (target.IsNull()) { return; } Utility.DelayCall(key, () => Events.Call(target, name, values), delay); } public static void Call(string name, params object[] values) { if (Events.HasDisabled("Call")) { return; } Events.Call(Events.Verify(), name, values); } public static void Call(object target, string name, params object[] values) { if (Events.HasDisabled("Call")) { return; } if (Events.active.AddNew(target).Contains(name)) { return; } if (Events.stack.Count > 1000) { Debug.LogWarning("[Events] : Event stack overflow."); Events.disabled = (EventDisabled)(-1); return; } target = Events.Verify(target); bool hasEvents = Events.HasListeners(target, name); var events = hasEvents ? Events.cache[target][name] : null; int count = hasEvents ? events.Count : 0; bool canDebug = Events.CanDebug(target, name, count); bool debugDeep = canDebug && Events.HasDebug("CallDeep"); bool debugTime = canDebug && Events.HasDebug("CallTimer"); float duration = Time.realtimeSinceStartup; if (hasEvents) { Events.lastCalled = name; Events.active[target].Add(name); foreach (var item in events.Copy()) { item.Value.Call(debugDeep, debugTime, values); } Events.lastCalled = ""; Events.active[target].Remove(name); } if (debugTime && (!debugDeep || count < 1)) { duration = Time.realtimeSinceStartup - duration; if (duration > 0.001f || Events.HasDebug("CallTimerZero")) { string time = duration.ToString("F10").TrimRight("0", ".").Trim() + " seconds."; string message = "[Events] : " + Events.GetTargetName(target) + " -- " + name + " -- " + count + " events -- " + time; Debug.Log(message, target as UnityObject); } } } public static void CallChildren(object target, string name, object[] values, bool self = false) { if (Events.HasDisabled("Call")) { return; } if (self) { Events.Call(target, name, values); } if (target is GameObject) { var gameObject = (GameObject)target; Transform[] children = Locate.GetObjectComponents<Transform>(gameObject); foreach (Transform transform in children) { if (transform.gameObject == gameObject) { continue; } Events.CallChildren(transform.gameObject, name, values, true); } } } public static void CallParents(object target, string name, object[] values, bool self = false) { if (Events.HasDisabled("Call")) { return; } if (self) { Events.Call(target, name, values); } if (target is GameObject) { var gameObject = (GameObject)target; Transform parent = gameObject.transform.parent; while (parent != null) { Events.CallParents(parent.gameObject, name, values, true); parent = parent.parent; } } } public static void CallFamily(object target, string name, object[] values, bool self = false) { if (Events.HasDisabled("Call")) { return; } if (self) { Events.Call(target, name, values); } Events.CallChildren(target, name, values); Events.CallParents(target, name, values); } //======================== // Editor //======================== public static string GetTargetName(object target) { if (target.IsNull()) { return "Null"; } string targetName = ""; if (target is string) { targetName = target.ToString(); } if (target is GameObject) { targetName = ((GameObject)target).GetPath(); } else if (target is Component) { targetName = ((Component)target).GetPath(); } else if (target.HasVariable("path")) { targetName = target.GetVariable<string>("path"); } if (targetName.IsEmpty()) { targetName = target.GetType().Name; } targetName = targetName.Trim("/"); if (targetName.Contains("__")) { targetName = "Anonymous"; } return targetName; } public static string GetMethodName(object method) { string name = "Unknown"; if (method is Delegate) { var info = (Delegate)method; string targetName = info.Method.DeclaringType.Name; string methodName = info.Method.Name; if (!info.Target.IsNull()) { targetName = GetTargetName(info.Target); } if (targetName.Contains("__")) { targetName = "Anonymous"; } if (methodName.Contains("__")) { methodName = "Anonymous"; } name = targetName + "." + methodName + "()"; } return name; } public static bool CanDebug(object target, string name, int count) { bool allowed = true; var debug = Events.debug; var scope = Events.debugScope; allowed = target == Events.global ? scope.Has("Global") : scope.Has("Scoped"); allowed = allowed && (count > 0 || debug.HasAny("CallEmpty")); if (allowed && name.ContainsAny("On Update", "On Late Update", "On Fixed Update", "On Editor Update", "On GUI", "On Camera", "On Undo Flushing")) { allowed = debug.Has("CallUpdate"); } if (allowed && !debug.Has("CallTimer") && debug.HasAny("Call", "CallUpdate", "CallDeep", "CallEmpty")) { string message = "[Events] : Calling " + name + " -- " + count + " events -- " + Events.GetTargetName(target); Debug.Log(message, target as UnityObject); } return allowed; } public static bool HasDisabled(string term) { return Events.disabled.Has(term); } public static bool HasDebug(string term) { return Events.debug.Has(term); } public static void Clean(string ignoreName = "", object target = null, object targetMethod = null) { foreach (var eventListener in Events.listeners) { string eventName = eventListener.name; object eventTarget = eventListener.target; object eventMethod = eventListener.method; bool duplicate = eventName != ignoreName && eventTarget == target && eventMethod.Equals(targetMethod); bool invalid = eventTarget.IsNull() || eventMethod.IsNull() || (!eventListener.isStatic && ((Delegate)eventMethod).Target.IsNull()); if (duplicate || invalid) { Utility.DelayCall(() => Events.listeners.Remove(eventListener)); if (Events.HasDebug("Remove")) { string messageType = eventMethod.IsNull() ? "empty method" : "duplicate method"; string message = "[Events] Removing " + messageType + " from -- " + eventTarget + "/" + eventName; Debug.Log(message, target as UnityObject); } } } foreach (var current in Events.callers) { object scope = current.Key; if (scope.IsNull()) { Utility.DelayCall(() => Events.callers.Remove(scope)); } } } public static List<string> GetEventNames(string type, object target = null) { Utility.EditorCall(() => Events.Clean()); target = Events.Verify(target); if (type.Contains("Listen", true)) { return Events.listeners.ToList().FindAll(x => x.target == target).Select(x => x.name).ToList(); } if (Events.callers.ContainsKey(target)) { return Events.callers[target]; } return new List<string>(); } } public static class ObjectEventExtensions { public static void RegisterEvent(this object current, string name, params object[] values) { if (current.IsNull()) { return; } Events.Register(name, current); } public static EventListener AddEvent(this object current, string name, object method, int amount = -1) { if (current.IsNull()) { return Events.emptyListener; } return Events.Add(name, method, amount, current); } public static void RemoveEvent(this object current, string name, object method) { if (current.IsNull()) { return; } Events.Remove(name, method, current); } public static void RemoveAllEvents(this object current, string name, object method) { if (current.IsNull()) { return; } Events.RemoveAll(current); } public static void DelayEvent(this object current, string name, float delay = 0.5f, params object[] values) { Events.DelayCall(current, current, name, delay, values); } public static void DelayEvent(this object current, object key, string name, float delay = 0.5f, params object[] values) { Events.DelayCall(current, key, name, delay, values); } public static void RestEvent(this object current, string name, float seconds) { if (current.IsNull()) { return; } Events.Rest(current, name, seconds); } public static void CooldownEvent(this object current, string name, float seconds) { if (current.IsNull()) { return; } Events.SetCooldown(current, name, seconds); } public static void CallEvent(this object current, string name, params object[] values) { if (current.IsNull()) { return; } Events.Call(current, name, values); } public static void CallEventChildren(this object current, string name, bool self = true, params object[] values) { if (current.IsNull()) { return; } Events.CallChildren(current, name, values, self); } public static void CallEventParents(this object current, string name, bool self = true, params object[] values) { if (current.IsNull()) { return; } Events.CallParents(current, name, values, self); } public static void CallEventFamily(this object current, string name, bool self = true, params object[] values) { if (current.IsNull()) { return; } Events.CallFamily(current, name, values, self); } } } #endif
namespace Microsoft.Azure.Management.StorSimple8000Series { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for AccessControlRecordsOperations. /// </summary> public static partial class AccessControlRecordsOperationsExtensions { /// <summary> /// Retrieves all the access control records in a manager. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<AccessControlRecord> ListByManager(this IAccessControlRecordsOperations operations, string resourceGroupName, string managerName) { return operations.ListByManagerAsync(resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves all the access control records in a manager. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<AccessControlRecord>> ListByManagerAsync(this IAccessControlRecordsOperations operations, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByManagerWithHttpMessagesAsync(resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the properties of the specified access control record name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// Name of access control record to be fetched. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static AccessControlRecord Get(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName) { return operations.GetAsync(accessControlRecordName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties of the specified access control record name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// Name of access control record to be fetched. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessControlRecord> GetAsync(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(accessControlRecordName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or Updates an access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record. /// </param> /// <param name='parameters'> /// The access control record to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static AccessControlRecord CreateOrUpdate(this IAccessControlRecordsOperations operations, string accessControlRecordName, AccessControlRecord parameters, string resourceGroupName, string managerName) { return operations.CreateOrUpdateAsync(accessControlRecordName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or Updates an access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record. /// </param> /// <param name='parameters'> /// The access control record to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessControlRecord> CreateOrUpdateAsync(this IAccessControlRecordsOperations operations, string accessControlRecordName, AccessControlRecord parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(accessControlRecordName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record to delete. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void Delete(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName) { operations.DeleteAsync(accessControlRecordName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record to delete. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(accessControlRecordName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or Updates an access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record. /// </param> /// <param name='parameters'> /// The access control record to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static AccessControlRecord BeginCreateOrUpdate(this IAccessControlRecordsOperations operations, string accessControlRecordName, AccessControlRecord parameters, string resourceGroupName, string managerName) { return operations.BeginCreateOrUpdateAsync(accessControlRecordName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or Updates an access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record. /// </param> /// <param name='parameters'> /// The access control record to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessControlRecord> BeginCreateOrUpdateAsync(this IAccessControlRecordsOperations operations, string accessControlRecordName, AccessControlRecord parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(accessControlRecordName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record to delete. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void BeginDelete(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName) { operations.BeginDeleteAsync(accessControlRecordName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the access control record. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accessControlRecordName'> /// The name of the access control record to delete. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IAccessControlRecordsOperations operations, string accessControlRecordName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(accessControlRecordName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software, you may not (a) modify, translate, adapt or * otherwise create derivative works, improvements of the Software or develop * new applications using the Software or (b) remove, delete, alter or obscure * any trademarks or any copyright, trademark, patent or other intellectual * property or proprietary rights notices on or in the Software, including * any copy thereof. Redistributions in binary or source form must include * this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE * "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 ESOTERIC SOFTARE BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.IO; using System.Collections.Generic; using UnityEngine; using Spine; /** Renders a skeleton. Extend to apply animations, get bones and manipulate them, etc. */ [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] [AddComponentMenu("Spine/SkeletonComponent")] public class SkeletonComponent : MonoBehaviour { public SkeletonDataAsset skeletonDataAsset; public Skeleton skeleton; public String initialSkinName; public float timeScale = 1; public bool calculateNormals; public bool calculateTangents; public float zSpacing; private MeshFilter meshFilter; private Mesh mesh, mesh1, mesh2; private bool useMesh1; private float[] vertexPositions = new float[8]; private int lastVertexCount; private Vector3[] vertices; private Color32[] colors; private Vector2[] uvs; private Material[] sharedMaterials = new Material[0]; private List<Material> submeshMaterials = new List<Material>(); private List<Submesh> submeshes = new List<Submesh>(); /// <summary>False if Initialize needs to be called.</summary> public bool Initialized { get { if (skeletonDataAsset == null) return true; SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); if (skeletonData == null) return true; return skeleton != null && skeleton.Data == skeletonData; } } public virtual void Clear () { if (meshFilter != null) meshFilter.sharedMesh = null; if (mesh != null) DestroyImmediate(mesh); if (renderer != null) renderer.sharedMaterial = null; mesh = null; mesh1 = null; mesh2 = null; lastVertexCount = 0; vertices = null; colors = null; uvs = null; sharedMaterials = new Material[0]; submeshMaterials.Clear(); submeshes.Clear(); skeleton = null; } public virtual void Initialize () { if (Initialized) return; meshFilter = GetComponent<MeshFilter>(); mesh1 = newMesh(); mesh2 = newMesh(); vertices = new Vector3[0]; skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData(false)); if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default") { skeleton.SetSkin(initialSkinName); skeleton.SetSlotsToSetupPose(); } } private Mesh newMesh () { Mesh mesh = new Mesh(); mesh.name = "Skeleton Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.MarkDynamic(); return mesh; } public virtual void UpdateSkeleton (float deltaTime) { skeleton.Update(deltaTime * timeScale); skeleton.UpdateWorldTransform(); } public virtual void Update () { if (skeletonDataAsset == null) { Clear(); return; } SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); if (skeletonData == null) { Clear(); return; } // Initialize fields. if (skeleton == null || skeleton.Data != skeletonData) Initialize(); UpdateSkeleton(Time.deltaTime); // Count quads and submeshes. int quadCount = 0, submeshQuadCount = 0; Material lastMaterial = null; submeshMaterials.Clear(); List<Slot> drawOrder = skeleton.DrawOrder; for (int i = 0, n = drawOrder.Count; i < n; i++) { RegionAttachment regionAttachment = drawOrder[i].Attachment as RegionAttachment; if (regionAttachment == null) continue; // Add submesh when material changes. Material material = (Material)((AtlasRegion)regionAttachment.RendererObject).page.rendererObject; if (lastMaterial != material && lastMaterial != null) { addSubmesh(lastMaterial, quadCount, submeshQuadCount, false); submeshQuadCount = 0; } lastMaterial = material; quadCount++; submeshQuadCount++; } addSubmesh(lastMaterial, quadCount, submeshQuadCount, true); // Set materials. if (submeshMaterials.Count == sharedMaterials.Length) submeshMaterials.CopyTo(sharedMaterials); else sharedMaterials = submeshMaterials.ToArray(); renderer.sharedMaterials = sharedMaterials; // Double buffer mesh. Mesh mesh = useMesh1 ? mesh1 : mesh2; meshFilter.sharedMesh = mesh; // Ensure mesh data is the right size. Vector3[] vertices = this.vertices; int vertexCount = quadCount * 4; bool newTriangles = vertexCount > vertices.Length; if (newTriangles) { // Not enough vertices, increase size. this.vertices = vertices = new Vector3[vertexCount]; this.colors = new Color32[vertexCount]; this.uvs = new Vector2[vertexCount]; mesh1.Clear(); mesh2.Clear(); } else { // Too many vertices, zero the extra. Vector3 zero = Vector3.zero; for (int i = vertexCount, n = lastVertexCount; i < n; i++) vertices[i] = zero; } lastVertexCount = vertexCount; // Setup mesh. float[] vertexPositions = this.vertexPositions; Vector2[] uvs = this.uvs; Color32[] colors = this.colors; int vertexIndex = 0; Color32 color = new Color32(); float a = skeleton.A * 255, r = skeleton.R, g = skeleton.G, b = skeleton.B, zSpacing = this.zSpacing; for (int i = 0, n = drawOrder.Count; i < n; i++) { Slot slot = drawOrder[i]; RegionAttachment regionAttachment = slot.Attachment as RegionAttachment; if (regionAttachment == null) continue; regionAttachment.ComputeWorldVertices(skeleton.X, skeleton.Y, slot.Bone, vertexPositions); float z = i * zSpacing; vertices[vertexIndex] = new Vector3(vertexPositions[RegionAttachment.X1], vertexPositions[RegionAttachment.Y1], z); vertices[vertexIndex + 1] = new Vector3(vertexPositions[RegionAttachment.X4], vertexPositions[RegionAttachment.Y4], z); vertices[vertexIndex + 2] = new Vector3(vertexPositions[RegionAttachment.X2], vertexPositions[RegionAttachment.Y2], z); vertices[vertexIndex + 3] = new Vector3(vertexPositions[RegionAttachment.X3], vertexPositions[RegionAttachment.Y3], z); color.a = (byte)(a * slot.A); color.r = (byte)(r * slot.R * color.a); color.g = (byte)(g * slot.G * color.a); color.b = (byte)(b * slot.B * color.a); colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color; float[] regionUVs = regionAttachment.UVs; uvs[vertexIndex] = new Vector2(regionUVs[RegionAttachment.X1], 1 - regionUVs[RegionAttachment.Y1]); uvs[vertexIndex + 1] = new Vector2(regionUVs[RegionAttachment.X4], 1 - regionUVs[RegionAttachment.Y4]); uvs[vertexIndex + 2] = new Vector2(regionUVs[RegionAttachment.X2], 1 - regionUVs[RegionAttachment.Y2]); uvs[vertexIndex + 3] = new Vector2(regionUVs[RegionAttachment.X3], 1 - regionUVs[RegionAttachment.Y3]); vertexIndex += 4; } mesh.vertices = vertices; mesh.colors32 = colors; mesh.uv = uvs; int submeshCount = submeshMaterials.Count; mesh.subMeshCount = submeshCount; for (int i = 0; i < submeshCount; ++i) mesh.SetTriangles(submeshes[i].indexes, i); mesh.RecalculateBounds(); if (newTriangles && calculateNormals) { Vector3[] normals = new Vector3[vertexCount]; Vector3 normal = new Vector3(0, 0, -1); for (int i = 0; i < vertexCount; i++) normals[i] = normal; (useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices. mesh1.normals = normals; mesh2.normals = normals; if (calculateTangents) { Vector4[] tangents = new Vector4[vertexCount]; Vector3 tangent = new Vector3(0, 0, 1); for (int i = 0; i < vertexCount; i++) tangents[i] = tangent; mesh1.tangents = tangents; mesh2.tangents = tangents; } } useMesh1 = !useMesh1; } /** Adds a material. Adds submesh indexes if existing indexes aren't sufficient. */ private void addSubmesh (Material material, int endQuadCount, int submeshQuadCount, bool lastSubmesh) { int submeshIndex = submeshMaterials.Count; submeshMaterials.Add(material); int indexCount = submeshQuadCount * 6; int vertexIndex = (endQuadCount - submeshQuadCount) * 4; if (submeshes.Count <= submeshIndex) submeshes.Add(new Submesh()); Submesh submesh = submeshes[submeshIndex]; // Allocate indexes if not the right size, allowing last submesh to have more than required. int[] indexes = submesh.indexes; if (lastSubmesh ? (indexes.Length < indexCount) : (indexes.Length != indexCount)) { submesh.indexes = indexes = new int[indexCount]; submesh.indexCount = 0; } // Set indexes if not already set. if (submesh.firstVertex != vertexIndex || submesh.indexCount < indexCount) { submesh.indexCount = indexCount; submesh.firstVertex = vertexIndex; for (int i = 0; i < indexCount; i += 6, vertexIndex += 4) { indexes[i] = vertexIndex; indexes[i + 1] = vertexIndex + 2; indexes[i + 2] = vertexIndex + 1; indexes[i + 3] = vertexIndex + 2; indexes[i + 4] = vertexIndex + 3; indexes[i + 5] = vertexIndex + 1; } } // Last submesh may have more indices than required, so zero indexes to the end. if (lastSubmesh && submesh.indexCount != indexCount) { submesh.indexCount = indexCount; for (int i = indexCount, n = indexes.Length; i < n; i++) indexes[i] = 0; } } public virtual void OnEnable () { Initialize(); } public virtual void Reset () { Initialize(); } #if UNITY_EDITOR void OnDrawGizmos() { // Make selection easier by drawing a clear gizmo over the skeleton. if (vertices == null) return; Vector3 gizmosCenter = new Vector3(); Vector3 gizmosSize = new Vector3(); Vector3 min = new Vector3(float.MaxValue, float.MaxValue, 0f); Vector3 max = new Vector3(float.MinValue, float.MinValue, 0f); foreach (Vector3 vert in vertices) { min = Vector3.Min (min, vert); max = Vector3.Max (max, vert); } float width = max.x - min.x; float height = max.y - min.y; gizmosCenter = new Vector3(min.x + (width / 2f), min.y + (height / 2f), 0f); gizmosSize = new Vector3(width, height, 1f); Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(gizmosCenter, gizmosSize); } #endif } class Submesh { public int[] indexes = new int[0]; public int firstVertex = -1; public int indexCount; }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.ComponentModel; using System.Globalization; namespace InteractiveDataDisplay.WPF { /// <summary> /// Control to render 2d image as a heatmap. Heatmap is widely used graphical representation of 2D array /// where the values of array items are represented as colors. /// </summary> [Description("Plots a heatmap graph")] public class HeatmapGraph : BackgroundBitmapRenderer, ITooltipProvider { private object locker = new object(); // Instance to hold locks for multithread access private double[] xArr; private double[] yArr; private long dataVersion = 0; private double[,] data; private double missingValue; /// <summary> /// Initializes a new instance of <see cref="HeatmapGraph"/> class with default tooltip. /// </summary> public HeatmapGraph() { TooltipContentFunc = GetTooltipForPoint; } private static void VerifyDimensions(double[,] d, double[] x, double[] y) { double dlen0 = d.GetLength(0); double dlen1 = d.GetLength(1); double xlen = x.Length; double ylen = y.Length; if (dlen0 == xlen && dlen1 == ylen || dlen0 == xlen - 1 && xlen > 1 && dlen1 == ylen - 1 && ylen > 1) return; throw new ArgumentException("Array dimensions do not match"); } /// <summary>Plots rectangular heatmap. /// If size <paramref name="data"/> dimensions are equal to lenghtes of corresponding grid parameters /// <paramref name="x"/> and <paramref name="y"/> then Gradient render method is used. If <paramref name="data"/> /// dimension are smaller by one then Bitmap render method is used for heatmap. In all other cases exception is thrown. /// </summary> /// <param name="data">Two dimensional array of data.</param> /// <param name="x">Grid along x axis.</param> /// <param name="y">Grid along y axis.</param> /// <returns>ID of background operation. You can subscribe to <see cref="RenderCompletion"/> /// notification to be notified when this operation is completed or request is dropped.</returns> public long Plot(double[,] data, double[] x, double[] y) { return Plot(data, x, y, Double.NaN); } /// <summary>Plots rectangular heatmap where some data may be missing. /// If size <paramref name="data"/> dimensions are equal to lenghtes of corresponding grid parameters /// <paramref name="x"/> and <paramref name="y"/> then Gradient render method is used. If <paramref name="data"/> /// dimension are smaller by one then Bitmap render method is used for heatmap. In all other cases exception is thrown. /// </summary> /// <param name="data">Two dimensional array of data.</param> /// <param name="x">Grid along x axis.</param> /// <param name="y">Grid along y axis.</param> /// <param name="missingValue">Missing value. Data items equal to <paramref name="missingValue"/> aren't shown.</param> /// <returns>ID of background operation. You can subscribe to <see cref="RenderCompletion"/> /// notification to be notified when this operation is completed or request is dropped.</returns> public long Plot(double[,] data, double[] x, double[] y, double missingValue) { VerifyDimensions(data, x, y); lock (locker) { this.xArr = x; this.yArr = y; this.data = data; this.missingValue = missingValue; dataVersion++; } InvalidateBounds(); return QueueRenderTask(); } /// <summary>Plots rectangular heatmap where some data may be missing. /// If size <paramref name="data"/> dimensions are equal to lenghtes of corresponding grid parameters /// <paramref name="x"/> and <paramref name="y"/> then Gradient render method is used. If <paramref name="data"/> /// dimension are smaller by one then Bitmap render method is used for heatmap. In all other cases exception is thrown. /// Double, float, integer and boolean types are supported as data and grid array elements</summary> /// <param name="data">Two dimensional array of data.</param> /// <param name="x">Grid along x axis.</param> /// <param name="y">Grid along y axis.</param> /// <param name="missingValue">Missing value. Data items equal to <paramref name="missingValue"/> aren't shown.</param> /// <returns>ID of background operation. You can subscribe to <see cref="RenderCompletion"/> /// notification to be notified when this operation is completed or request is dropped.</returns> public long Plot<T, A>(T[,] data, A[] x, A[] y, T missingValue) { return Plot(ArrayExtensions.ToDoubleArray2D(data), ArrayExtensions.ToDoubleArray(x), ArrayExtensions.ToDoubleArray(y), Convert.ToDouble(missingValue, CultureInfo.InvariantCulture)); } /// <summary>Plots rectangular heatmap where some data may be missing. /// If size <paramref name="data"/> dimensions are equal to lenghtes of corresponding grid parameters /// <paramref name="x"/> and <paramref name="y"/> then Gradient render method is used. If <paramref name="data"/> /// dimension are smaller by one then Bitmap render method is used for heatmap. In all other cases exception is thrown. /// Double, float, integer and boolean types are supported as data and grid array elements</summary> /// <param name="data">Two dimensional array of data.</param> /// <param name="x">Grid along x axis.</param> /// <param name="y">Grid along y axis.</param> /// <returns>ID of background operation. You can subscribe to <see cref="RenderCompletion"/> /// notification to be notified when this operation is completed or request is dropped.</returns> public long Plot<T, A>(T[,] data, A[] x, A[] y) { return Plot(ArrayExtensions.ToDoubleArray2D(data), ArrayExtensions.ToDoubleArray(x), ArrayExtensions.ToDoubleArray(y), Double.NaN); } /// <summary>Returns content bounds of this elements in cartesian coordinates.</summary> /// <returns>Rectangle with content bounds.</returns> protected override DataRect ComputeBounds() { if (xArr != null && yArr != null) return new DataRect(xArr[0], yArr[0], xArr[xArr.Length - 1], yArr[yArr.Length - 1]); else return DataRect.Empty; } /// <summary> /// Cached value of <see cref="Palette"/> property. Accessed both from UI and rendering thread. /// </summary> private IPalette palette = InteractiveDataDisplay.WPF.Palette.Heat; /// <summary> /// Identifies the <see cref="Palette"/> dependency property. /// </summary> public static readonly DependencyProperty PaletteProperty = DependencyProperty.Register( "Palette", typeof(Palette), typeof(HeatmapGraph), new PropertyMetadata(InteractiveDataDisplay.WPF.Palette.Heat, OnPalettePropertyChanged)); /// <summary>Gets or sets the palette for heatmap rendering.</summary> [TypeConverter(typeof(StringToPaletteTypeConverter))] [Category("InteractiveDataDisplay")] [Description("Defines mapping from values to color")] public IPalette Palette { get { return (IPalette)GetValue(PaletteProperty); } set { SetValue(PaletteProperty, value); } } private bool paletteRangeUpdateRequired = true; private static void OnPalettePropertyChanged(object sender, DependencyPropertyChangedEventArgs e) { HeatmapGraph heatmap = (HeatmapGraph)sender; lock (heatmap.locker) { heatmap.paletteRangeUpdateRequired = true; heatmap.palette = (Palette)e.NewValue; } heatmap.QueueRenderTask(); } /// <summary> /// Identifies the <see cref="PaletteRange"/> dependency property. /// </summary> public static readonly DependencyProperty PaletteRangeProperty = DependencyProperty.Register( "PaletteRange", typeof(Range), typeof(HeatmapGraph), new PropertyMetadata(new Range(0, 1), OnPaletteRangePropertyChanged)); /// <summary> /// Cached range of data values. It is accessed from UI and rendering thread. /// </summary> private Range dataRange = new Range(0, 1); /// <summary>Version of data for current data range. If dataVersion != dataRangeVersion then /// data range version should be recalculated.</summary> private long dataRangeVersion = -1; private int insidePaletteRangeSetter = 0; /// <summary>Gets range of data values used in palette building.</summary> /// <remarks>This property cannot be set from outside code. Attempt to set it from /// bindings result in exception.</remarks> [Browsable(false)] public Range PaletteRange { get { return (Range)GetValue(PaletteRangeProperty); } protected set { try { insidePaletteRangeSetter++; SetValue(PaletteRangeProperty, value); } finally { insidePaletteRangeSetter--; } } } private static void OnPaletteRangePropertyChanged(object sender, DependencyPropertyChangedEventArgs e) { var heatmap = (HeatmapGraph)sender; if (heatmap.insidePaletteRangeSetter <= 0) throw new InvalidOperationException("Palette Range property cannot be changed by binding. Use Palette property instead"); } private void UpdatePaletteRange(long localDataVersion) { if (dataVersion != localDataVersion) return; paletteRangeUpdateRequired = false; if (palette.IsNormalized) PaletteRange = dataRange; else PaletteRange = palette.Range; } /// <summary>Gets range of data values for current data.</summary> public Range DataRange { get { if (data != null && dataVersion != dataRangeVersion) { var r = Double.IsNaN(missingValue) ? HeatmapBuilder.GetMaxMin(data) : HeatmapBuilder.GetMaxMin(data, missingValue); lock (locker) { dataRangeVersion = dataVersion; dataRange = r; } UpdatePaletteRange(dataVersion); } return dataRange; } } /// <summary> /// Renders frame and returns it as a render result. /// </summary> /// <param name="state">Render task state for rendering frame.</param> /// <returns>Render result of rendered frame.</returns> protected override RenderResult RenderFrame(RenderTaskState state) { if (state == null) throw new ArgumentNullException("state"); if (!state.Bounds.IsEmpty && !state.IsCanceled && data != null) { //DataRect dataRect = new DataRect(state.Transform.Visible); //Rect output = state.Transform.Screen; DataRect dataRect = state.ActualPlotRect; DataRect output = new DataRect(0, 0, state.ScreenSize.Width, state.ScreenSize.Height); DataRect bounds = state.Bounds; if (dataRect.XMin >= bounds.XMax || dataRect.XMax <= bounds.XMin || dataRect.YMin >= bounds.YMax || dataRect.YMax <= bounds.YMin) return null; double left = 0; double xmin = dataRect.XMin; double scale = output.Width / dataRect.Width; if (xmin < bounds.XMin) { left = (bounds.XMin - dataRect.XMin) * scale; xmin = bounds.XMin; } double width = output.Width - left; double xmax = dataRect.XMax; if (xmax > bounds.XMax) { width -= (dataRect.XMax - bounds.XMax) * scale; xmax = bounds.XMax; } scale = output.Height / dataRect.Height; double top = 0; double ymax = dataRect.YMax; if (ymax > bounds.YMax) { top = (dataRect.YMax - bounds.YMax) * scale; ymax = bounds.YMax; } double height = output.Height - top; double ymin = dataRect.YMin; if (ymin < bounds.YMin) { height -= (bounds.YMin - dataRect.YMin) * scale; ymin = bounds.YMin; } if (xmin < bounds.XMin) xmin = bounds.XMin; if (xmax > bounds.XMax) xmax = bounds.XMax; if (ymin < bounds.YMin) ymin = bounds.YMin; if (ymax > bounds.YMax) ymax = bounds.YMax; DataRect visibleData = new DataRect(xmin, ymin, xmax, ymax); // Capture data to local variable double[,] localData; double[] localX, localY; long localDataVersion; IPalette localPalette; double localMV; Range localDataRange; bool getMaxMin = false; lock (locker) { localData = data; localX = xArr; localY = yArr; localDataVersion = dataVersion; localPalette = palette; localMV = missingValue; localDataRange = dataRange; if (palette.IsNormalized && dataVersion != dataRangeVersion) getMaxMin = true; } if (getMaxMin) { localDataRange = Double.IsNaN(missingValue) ? HeatmapBuilder.GetMaxMin(data) : HeatmapBuilder.GetMaxMin(data, missingValue); lock (locker) { if (dataVersion == localDataVersion) { dataRangeVersion = dataVersion; dataRange = localDataRange; } else return null; // New data was passed to Plot method so this render task is obsolete } } if (paletteRangeUpdateRequired) Dispatcher.BeginInvoke(new Action<long>(UpdatePaletteRange), localDataVersion); return new RenderResult(HeatmapBuilder.BuildHeatMap(new Rect(0, 0, width, height), visibleData, localX, localY, localData, localMV, localPalette, localDataRange), visibleData, new Point(left, top), width, height); } else return null; } /// <summary>Gets or sets function to get tooltip object (string or UIElement) /// for given screen point.</summary> /// <remarks><see cref="GetTooltipForPoint"/> method is called by default.</remarks> public Func<Point, object> TooltipContentFunc { get; set; } /// <summary> /// Returns the string that is shown in tooltip for the screen point. If there is no data for this point (or nearest points) on a screen then returns null. /// </summary> /// <param name="screenPoint">A point to show tooltip for.</param> /// <returns>An object.</returns> public object GetTooltipForPoint(Point screenPoint) { double pointData; Point nearest; if (GetNearestPointAndValue(screenPoint, out nearest, out pointData)) return String.Format(CultureInfo.InvariantCulture, "Data: {0}; X: {1}; Y: {2}", pointData, nearest.X, nearest.Y); else return null; } /// <summary> /// Finds the point nearest to a specified point on a screen. /// </summary> /// <param name="screenPoint">The point to search nearest for.</param> /// <param name="nearest">The out parameter to handle the founded point.</param> /// <param name="vd">The out parameter to handle data of founded point.</param> /// <returns>Boolen value indicating whether the nearest point was found or not.</returns> public bool GetNearestPointAndValue(Point screenPoint, out Point nearest, out double vd) { nearest = new Point(Double.NaN, Double.NaN); vd = Double.NaN; if (data == null || xArr == null || yArr == null) return false; Point dataPoint = new Point(XDataTransform.PlotToData(XFromLeft(screenPoint.X)), YDataTransform.PlotToData(YFromTop(screenPoint.Y)));//PlotContext.ScreenToData(screenPoint); int i = ArrayExtensions.GetNearestIndex(xArr, dataPoint.X); if (i < 0) return false; int j = ArrayExtensions.GetNearestIndex(yArr, dataPoint.Y); if (j < 0) return false; if (IsBitmap) { if (i > 0 && xArr[i - 1] > dataPoint.X) i--; if (j > 0 && yArr[j - 1] > dataPoint.Y) j--; } if (i < data.GetLength(0) && j < data.GetLength(1)) { vd = data[i, j]; nearest = new Point(xArr[i], yArr[j]); return true; } else return false; } /// <summary> /// Gets the boolen value indicating whether heatmap is rendered using gradient filling. /// </summary> public bool IsGradient { get { return (data == null || xArr == null) ? false : (data.GetLength(0) == xArr.Length); } } /// <summary> /// Gets the boolen value indicating whether heatmap is rendered as a bitmap. /// </summary> public bool IsBitmap { get { return (data == null || xArr == null) ? false : (data.GetLength(0) == xArr.Length - 1); } } } }
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot ([email protected]) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Linq; using NServiceKit.Common.Utils; using NServiceKit.DesignPatterns.Model; using NServiceKit.Redis.Support; using NServiceKit.Text; using NServiceKit.Common.Extensions; namespace NServiceKit.Redis.Generic { public partial class RedisTypedClient<T> { public IHasNamed<IRedisSortedSet<T>> SortedSets { get; set; } internal class RedisClientSortedSets : IHasNamed<IRedisSortedSet<T>> { private readonly RedisTypedClient<T> client; public RedisClientSortedSets(RedisTypedClient<T> client) { this.client = client; } public IRedisSortedSet<T> this[string setId] { get { return new RedisClientSortedSet<T>(client, setId); } set { var col = this[setId]; col.Clear(); col.CopyTo(value.ToArray(), 0); } } } public static T DeserializeFromString(string serializedObj) { return JsonSerializer.DeserializeFromString<T>(serializedObj); } private static IDictionary<T, double> CreateGenericMap(IDictionary<string, double> map) { var genericMap = new OrderedDictionary<T, double>(); foreach (var entry in map) { genericMap[DeserializeFromString(entry.Key)] = entry.Value; } return genericMap; } public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value) { client.AddItemToSortedSet(toSet.Id, value.SerializeToString()); } public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value, double score) { client.AddItemToSortedSet(toSet.Id, value.SerializeToString(), score); } public bool RemoveItemFromSortedSet(IRedisSortedSet<T> fromSet, T value) { return client.RemoveItemFromSortedSet(fromSet.Id, value.SerializeToString()); } public T PopItemWithLowestScoreFromSortedSet(IRedisSortedSet<T> fromSet) { return DeserializeFromString( client.PopItemWithLowestScoreFromSortedSet(fromSet.Id)); } public T PopItemWithHighestScoreFromSortedSet(IRedisSortedSet<T> fromSet) { return DeserializeFromString( client.PopItemWithHighestScoreFromSortedSet(fromSet.Id)); } public bool SortedSetContainsItem(IRedisSortedSet<T> set, T value) { return client.SortedSetContainsItem(set.Id, value.SerializeToString()); } public double IncrementItemInSortedSet(IRedisSortedSet<T> set, T value, double incrementBy) { return client.IncrementItemInSortedSet(set.Id, value.SerializeToString(), incrementBy); } public long GetItemIndexInSortedSet(IRedisSortedSet<T> set, T value) { return client.GetItemIndexInSortedSet(set.Id, value.SerializeToString()); } public long GetItemIndexInSortedSetDesc(IRedisSortedSet<T> set, T value) { return client.GetItemIndexInSortedSetDesc(set.Id, value.SerializeToString()); } public List<T> GetAllItemsFromSortedSet(IRedisSortedSet<T> set) { var list = client.GetAllItemsFromSortedSet(set.Id); return list.ConvertEachTo<T>(); } public List<T> GetAllItemsFromSortedSetDesc(IRedisSortedSet<T> set) { var list = client.GetAllItemsFromSortedSetDesc(set.Id); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank) { var list = client.GetRangeFromSortedSet(set.Id, fromRank, toRank); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank) { var list = client.GetRangeFromSortedSetDesc(set.Id, fromRank, toRank); return list.ConvertEachTo<T>(); } public IDictionary<T, double> GetAllWithScoresFromSortedSet(IRedisSortedSet<T> set) { var map = client.GetRangeWithScoresFromSortedSet(set.Id, FirstElement, LastElement); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank) { var map = client.GetRangeWithScoresFromSortedSet(set.Id, fromRank, toRank); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank) { var map = client.GetRangeWithScoresFromSortedSetDesc(set.Id, fromRank, toRank); return CreateGenericMap(map); } public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore) { var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take) { var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore) { var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take) { var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take); return list.ConvertEachTo<T>(); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore) { var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take) { var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore) { var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take) { var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take); return CreateGenericMap(map); } public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore) { var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take) { var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore) { var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore); return list.ConvertEachTo<T>(); } public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take) { var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore, skip, take); return list.ConvertEachTo<T>(); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore) { var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take) { var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore) { var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore); return CreateGenericMap(map); } public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take) { var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore, skip, take); return CreateGenericMap(map); } public long RemoveRangeFromSortedSet(IRedisSortedSet<T> set, int minRank, int maxRank) { return client.RemoveRangeFromSortedSet(set.Id, minRank, maxRank); } public long RemoveRangeFromSortedSetByScore(IRedisSortedSet<T> set, double fromScore, double toScore) { return client.RemoveRangeFromSortedSetByScore(set.Id, fromScore, toScore); } public long GetSortedSetCount(IRedisSortedSet<T> set) { return client.GetSortedSetCount(set.Id); } public double GetItemScoreInSortedSet(IRedisSortedSet<T> set, T value) { return client.GetItemScoreInSortedSet(set.Id, value.SerializeToString()); } public long StoreIntersectFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds) { return client.StoreIntersectFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray()); } public long StoreUnionFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds) { return client.StoreUnionFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray()); } } }
using System; /// <summary> /// System.Array.IndexOf<>(T<>,T,System.Int32,System.Int32) /// </summary> public class ArrayIndexOf4 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Travel the array"); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; for (int i = 0; i < length; i++) //set the value for the array { i1[i] = i; } for (int a = 0; a < length; a++) //check every value using indexof<> method { int result = Array.IndexOf<int>(i1, a, 0, length); if (result != a) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected. The index is:" + a.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Search the value from the middle of the array"); try { int[] i1 = new int[5] { 6, 3, 4, 7, 10 }; int result = Array.IndexOf<int>(i1, 7, 3, 2); if (result != 3) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Set the fourth argument \"count\"to zero"); try { int[] i1 = new int[5] { 6, 6, 6, 6, 6 }; int result = Array.IndexOf<int>(i1, 6, 2, 0); if (result != -1) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Set two equal value in one array"); try { string[] i1 = new string[6]{"Fix", "Right", "Correct", "Right", "Hello", "Back"}; int result = Array.IndexOf<string>(i1, "Right", 0, 5); if (result != 1) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Find out the second value which has a equal value before it"); try { char[] i1 = { 'g', 't', 'r', 'd', 't', 'o' }; int result = Array.IndexOf<char>(i1, 't', 3, 2); if (result != 4) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Find out no expected value"); try { int[] i1 = new int[5] { 1, 3, 7, 8, 2 }; int result = Array.IndexOf<int>(i1, 9, 0, 5); if (result != -1) { TestLibrary.TestFramework.LogError("011", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Set the second argument as a different type value"); try { int[] i1 = new int[5] { 5, 7, 15, 6, 0 }; byte i2 = 7; int result = Array.IndexOf<int>(i1, i2, 0, 5); if (result != 1) { TestLibrary.TestFramework.LogError("013", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array to be searched is null reference "); try { string[] s1 = null; int result = Array.IndexOf<string>(s1, "Tom", 0, 10); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The startIndex is less than zero "); try { int[] s1 = new int[5] { 3, 4, 5, 6, 7 }; int result = Array.IndexOf<int>(s1, 4, -1, 3); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The startIndex is greater than range of index for the array "); try { int[] s1 = new int[5] { 3, 4, 5, 6, 7 }; int result = Array.IndexOf<int>(s1, 4, 6, 0); TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: The count is less than zero "); try { int[] s1 = new int[5] { 3, 4, 5, 6, 7 }; int result = Array.IndexOf<int>(s1, 4, 0, -1); TestLibrary.TestFramework.LogError("107", "The ArgumentOutOfRangeException is not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: The count exceed the end of the array "); try { int[] s1 = new int[5] { 3, 4, 5, 6, 7 }; int result = Array.IndexOf<int>(s1, 4, 3, 8); TestLibrary.TestFramework.LogError("109", "The ArgumentOutOfRangeException is not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayIndexOf4 test = new ArrayIndexOf4(); TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf4"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Copyright (c) .NET Foundation. 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.Diagnostics; namespace Ixq.Core.DependencyInjection { [DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")] public class ServiceDescriptor { /// <summary> /// Initializes a new instance of <see cref="ServiceDescriptor" /> with the specified /// <paramref name="implementationType" />. /// </summary> /// <param name="serviceType">The <see cref="Type" /> of the service.</param> /// <param name="implementationType">The <see cref="Type" /> implementing the service.</param> /// <param name="lifetime">The <see cref="ServiceLifetime" /> of the service.</param> /// <param name="alias"></param> public ServiceDescriptor( Type serviceType, Type implementationType, ServiceLifetime lifetime, string alias = null) : this(serviceType, lifetime) { if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); Alias = alias; ImplementationType = implementationType ?? throw new ArgumentNullException(nameof(implementationType)); } /// <summary> /// Initializes a new instance of <see cref="ServiceDescriptor" /> with the specified <paramref name="instance" /> /// as a <see cref="ServiceLifetime.Singleton" />. /// </summary> /// <param name="serviceType">The <see cref="Type" /> of the service.</param> /// <param name="instance">The instance implementing the service.</param> /// <param name="alias"></param> public ServiceDescriptor( Type serviceType, object instance, string alias = null) : this(serviceType, ServiceLifetime.Singleton) { if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); Alias = alias; ImplementationInstance = instance ?? throw new ArgumentNullException(nameof(instance)); } /// <summary> /// Initializes a new instance of <see cref="ServiceDescriptor" /> with the specified <paramref name="factory" />. /// </summary> /// <param name="serviceType">The <see cref="Type" /> of the service.</param> /// <param name="factory">A factory used for creating service instances.</param> /// <param name="lifetime">The <see cref="ServiceLifetime" /> of the service.</param> public ServiceDescriptor( Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime, string alias = null) : this(serviceType, lifetime) { if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); Alias = alias; ImplementationFactory = factory ?? throw new ArgumentNullException(nameof(factory)); } private ServiceDescriptor(Type serviceType, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; } /// <inheritdoc /> public string Alias { get; set; } /// <inheritdoc /> public ServiceLifetime Lifetime { get; } /// <inheritdoc /> public Type ServiceType { get; } /// <inheritdoc /> public Type ImplementationType { get; } /// <inheritdoc /> public object ImplementationInstance { get; } /// <inheritdoc /> public Func<IServiceProvider, object> ImplementationFactory { get; } internal Type GetImplementationType() { if (ImplementationType != null) return ImplementationType; if (ImplementationInstance != null) return ImplementationInstance.GetType(); if (ImplementationFactory != null) { var typeArguments = ImplementationFactory.GetType().GenericTypeArguments; Debug.Assert(typeArguments.Length == 2); return typeArguments[1]; } Debug.Assert(false, "ImplementationType, ImplementationInstance or ImplementationFactory must be non null"); return null; } public static ServiceDescriptor Transient<TService, TImplementation>(string alias = null) where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Transient, alias); } public static ServiceDescriptor Transient(Type service, Type implementationType, string alias = null) { if (service == null) throw new ArgumentNullException(nameof(service)); if (implementationType == null) throw new ArgumentNullException(nameof(implementationType)); return Describe(service, implementationType, ServiceLifetime.Transient, alias); } public static ServiceDescriptor Transient<TService, TImplementation>( Func<IServiceProvider, TImplementation> implementationFactory, string alias = null) where TService : class where TImplementation : class, TService { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient, alias); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory, string alias = null) where TService : class { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient, alias); } public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory, string alias = null) { if (service == null) throw new ArgumentNullException(nameof(service)); if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(service, implementationFactory, ServiceLifetime.Transient, alias); } public static ServiceDescriptor Scoped<TService, TImplementation>(string alias = null) where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Scoped, alias); } public static ServiceDescriptor Scoped(Type service, Type implementationType, string alias = null) { return Describe(service, implementationType, ServiceLifetime.Scoped, alias); } public static ServiceDescriptor Scoped<TService, TImplementation>( Func<IServiceProvider, TImplementation> implementationFactory, string alias = null) where TService : class where TImplementation : class, TService { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped, alias); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory, string alias = null) where TService : class { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped, alias); } public static ServiceDescriptor Scoped (Type service, Func<IServiceProvider, object> implementationFactory, string alias = null) { if (service == null) throw new ArgumentNullException(nameof(service)); if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(service, implementationFactory, ServiceLifetime.Scoped, alias); } public static ServiceDescriptor Singleton<TService, TImplementation>(string alias = null) where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Singleton, alias); } public static ServiceDescriptor Singleton(Type service, Type implementationType, string alias = null) { if (service == null) throw new ArgumentNullException(nameof(service)); if (implementationType == null) throw new ArgumentNullException(nameof(implementationType)); return Describe(service, implementationType, ServiceLifetime.Singleton, alias); } public static ServiceDescriptor Singleton<TService, TImplementation>( Func<IServiceProvider, TImplementation> implementationFactory, string alias = null) where TService : class where TImplementation : class, TService { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton, alias); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory, string alias = null) where TService : class { if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton, alias); } public static ServiceDescriptor Singleton( Type serviceType, Func<IServiceProvider, object> implementationFactory, string alias = null) { if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); if (implementationFactory == null) throw new ArgumentNullException(nameof(implementationFactory)); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton, alias); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance, string alias = null) where TService : class { if (implementationInstance == null) throw new ArgumentNullException(nameof(implementationInstance)); return Singleton(typeof(TService), implementationInstance, alias); } public static ServiceDescriptor Singleton( Type serviceType, object implementationInstance, string alias = null) { if (serviceType == null) throw new ArgumentNullException(nameof(serviceType)); if (implementationInstance == null) throw new ArgumentNullException(nameof(implementationInstance)); return new ServiceDescriptor(serviceType, implementationInstance, alias); } private static ServiceDescriptor Describe<TService, TImplementation>(ServiceLifetime lifetime, string alias = null) where TService : class where TImplementation : class, TService { return Describe( typeof(TService), typeof(TImplementation), lifetime, alias); } public static ServiceDescriptor Describe(Type serviceType, Type implementationType, ServiceLifetime lifetime, string alias = null) { return new ServiceDescriptor(serviceType, implementationType, lifetime, alias); } public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime, string alias = null) { return new ServiceDescriptor(serviceType, implementationFactory, lifetime, alias); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Xml; namespace System.Runtime.Serialization.Json { internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer { private const char BACK_SLASH = '\\'; private const char FORWARD_SLASH = '/'; private const char HIGH_SURROGATE_START = (char)0xd800; private const char LOW_SURROGATE_END = (char)0xdfff; private const char MAX_CHAR = (char)0xfffe; private const char WHITESPACE = ' '; private const char CARRIAGE_RETURN = '\r'; private const char NEWLINE = '\n'; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; [SecurityCritical] private static BinHexEncoding s_binHexEncoding; private string _attributeText; private JsonDataType _dataType; private int _depth; private bool _endElementBuffer; private bool _isWritingDataTypeAttribute; private bool _isWritingServerTypeAttribute; private bool _isWritingXmlnsAttribute; private bool _isWritingXmlnsAttributeDefaultNs; private NameState _nameState; private JsonNodeType _nodeType; private JsonNodeWriter _nodeWriter; private JsonNodeType[] _scopes; private string _serverTypeValue; // Do not use this field's value anywhere other than the WriteState property. // It's OK to set this field's value anywhere and then change the WriteState property appropriately. // If it's necessary to check the WriteState outside WriteState, use the WriteState property. private WriteState _writeState; private bool _wroteServerTypeAttribute; private bool _indent; private string _indentChars; private int _indentLevel; public XmlJsonWriter() : this(false, null) { } public XmlJsonWriter(bool indent, string indentChars) { _indent = indent; if (indent) { if (indentChars == null) { throw new ArgumentNullException("indentChars"); } _indentChars = indentChars; } InitializeWriter(); } private enum JsonDataType { None, Null, Boolean, Number, String, Object, Array }; [Flags] private enum NameState { None = 0, IsWritingNameWithMapping = 1, IsWritingNameAttribute = 2, WrittenNameWithMapping = 4, } public override XmlWriterSettings Settings { // The XmlWriterSettings object used to create this writer instance. // If this writer was not created using the Create method, this property // returns a null reference. get { return null; } } public override WriteState WriteState { get { if (_writeState == WriteState.Closed) { return WriteState.Closed; } if (HasOpenAttribute) { return WriteState.Attribute; } switch (_nodeType) { case JsonNodeType.None: return WriteState.Start; case JsonNodeType.Element: return WriteState.Element; case JsonNodeType.QuotedText: case JsonNodeType.StandaloneText: case JsonNodeType.EndElement: return WriteState.Content; default: return WriteState.Error; } } } public override string XmlLang { get { return null; } } public override XmlSpace XmlSpace { get { return XmlSpace.None; } } private static BinHexEncoding BinHexEncoding { [SecuritySafeCritical] get { if (s_binHexEncoding == null) { s_binHexEncoding = new BinHexEncoding(); } return s_binHexEncoding; } } private bool HasOpenAttribute { get { return (_isWritingDataTypeAttribute || _isWritingServerTypeAttribute || IsWritingNameAttribute || _isWritingXmlnsAttribute); } } private bool IsClosed { get { return (WriteState == WriteState.Closed); } } private bool IsWritingCollection { get { return (_depth > 0) && (_scopes[_depth] == JsonNodeType.Collection); } } private bool IsWritingNameAttribute { get { return (_nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute; } } private bool IsWritingNameWithMapping { get { return (_nameState & NameState.IsWritingNameWithMapping) == NameState.IsWritingNameWithMapping; } } private bool WrittenNameWithMapping { get { return (_nameState & NameState.WrittenNameWithMapping) == NameState.WrittenNameWithMapping; } } protected override void Dispose(bool disposing) { if (!IsClosed) { try { WriteEndDocument(); } finally { try { _nodeWriter.Flush(); _nodeWriter.Close(); } finally { _writeState = WriteState.Closed; if (_depth != 0) { _depth = 0; } } } } base.Dispose(disposing); } public override void Flush() { if (IsClosed) { ThrowClosed(); } _nodeWriter.Flush(); } public override string LookupPrefix(string ns) { if (ns == null) { throw new ArgumentNullException("ns"); } if (ns == Globals.XmlnsNamespace) { return Globals.XmlnsPrefix; } if (ns == xmlNamespace) { return JsonGlobals.xmlPrefix; } if (ns == string.Empty) { return string.Empty; } return null; } public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (encoding.WebName != Encoding.UTF8.WebName) { stream = new JsonEncodingStreamWrapper(stream, encoding, false); } else { encoding = null; } if (_nodeWriter == null) { _nodeWriter = new JsonNodeWriter(); } _nodeWriter.SetOutput(stream, ownsStream, encoding); InitializeWriter(); } public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int16[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int32[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Int64[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } public override void WriteBase64(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } StartText(); _nodeWriter.WriteBase64Text(buffer, 0, buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } StartText(); WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count)); } public override void WriteCData(string text) { WriteString(text); } public override void WriteCharEntity(char ch) { WriteString(ch.ToString()); } public override void WriteChars(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } WriteString(new string(buffer, index, count)); } public override void WriteComment(string text) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteComment")); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "2#sysid", Justification = "This method is derived from the base")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "1#pubid", Justification = "This method is derived from the base")] public override void WriteDocType(string name, string pubid, string sysid, string subset) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteDocType")); } public override void WriteEndAttribute() { if (IsClosed) { ThrowClosed(); } if (!HasOpenAttribute) { throw new XmlException(SR.JsonNoMatchingStartAttribute); } Fx.Assert(!(_isWritingDataTypeAttribute && _isWritingServerTypeAttribute), "Can not write type attribute and __type attribute at the same time."); if (_isWritingDataTypeAttribute) { switch (_attributeText) { case JsonGlobals.numberString: { ThrowIfServerTypeWritten(JsonGlobals.numberString); _dataType = JsonDataType.Number; break; } case JsonGlobals.stringString: { ThrowIfServerTypeWritten(JsonGlobals.stringString); _dataType = JsonDataType.String; break; } case JsonGlobals.arrayString: { ThrowIfServerTypeWritten(JsonGlobals.arrayString); _dataType = JsonDataType.Array; break; } case JsonGlobals.objectString: { _dataType = JsonDataType.Object; break; } case JsonGlobals.nullString: { ThrowIfServerTypeWritten(JsonGlobals.nullString); _dataType = JsonDataType.Null; break; } case JsonGlobals.booleanString: { ThrowIfServerTypeWritten(JsonGlobals.booleanString); _dataType = JsonDataType.Boolean; break; } default: throw new XmlException(SR.Format(SR.JsonUnexpectedAttributeValue, _attributeText)); } _attributeText = null; _isWritingDataTypeAttribute = false; if (!IsWritingNameWithMapping || WrittenNameWithMapping) { WriteDataTypeServerType(); } } else if (_isWritingServerTypeAttribute) { _serverTypeValue = _attributeText; _attributeText = null; _isWritingServerTypeAttribute = false; // we are writing __type after type="object" (enforced by WSE) if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && _dataType == JsonDataType.Object) { WriteServerTypeAttribute(); } } else if (IsWritingNameAttribute) { WriteJsonElementName(_attributeText); _attributeText = null; _nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping; WriteDataTypeServerType(); } else if (_isWritingXmlnsAttribute) { if (!string.IsNullOrEmpty(_attributeText) && _isWritingXmlnsAttributeDefaultNs) { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, _attributeText)); } _attributeText = null; _isWritingXmlnsAttribute = false; _isWritingXmlnsAttributeDefaultNs = false; } } public override void WriteEndDocument() { if (IsClosed) { ThrowClosed(); } if (_nodeType != JsonNodeType.None) { while (_depth > 0) { WriteEndElement(); } } } public override void WriteEndElement() { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new XmlException(SR.JsonEndElementNoOpenNodes); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteEndElement")); } _endElementBuffer = false; JsonNodeType token = ExitScope(); if (token == JsonNodeType.Collection) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndCollectionChar); token = ExitScope(); } else if (_nodeType == JsonNodeType.QuotedText) { // For writing " WriteJsonQuote(); } else if (_nodeType == JsonNodeType.Element) { if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Ending </item> without writing item attribute // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } // the element is empty, it does not have any content, if ((_dataType == JsonDataType.None) || (_dataType == JsonDataType.String)) { _nodeWriter.WriteText(JsonGlobals.QuoteChar); _nodeWriter.WriteText(JsonGlobals.QuoteChar); } } else { // Assert on only StandaloneText and EndElement because preceding if // conditions take care of checking for QuotedText and Element. Fx.Assert((_nodeType == JsonNodeType.StandaloneText) || (_nodeType == JsonNodeType.EndElement), "nodeType has invalid value " + _nodeType + ". Expected it to be QuotedText, Element, StandaloneText, or EndElement."); } if (_depth != 0) { if (token == JsonNodeType.Element) { _endElementBuffer = true; } else if (token == JsonNodeType.Object) { _indentLevel--; if (_indent) { if (_nodeType == JsonNodeType.Element) { _nodeWriter.WriteText(WHITESPACE); } else { WriteNewLine(); WriteIndent(); } } _nodeWriter.WriteText(JsonGlobals.EndObjectChar); if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element) { ExitScope(); _endElementBuffer = true; } } } _dataType = JsonDataType.None; _nodeType = JsonNodeType.EndElement; _nameState = NameState.None; _wroteServerTypeAttribute = false; } public override void WriteEntityRef(string name) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteEntityRef")); } public override void WriteFullEndElement() { WriteEndElement(); } public override void WriteProcessingInstruction(string name, string text) { if (IsClosed) { ThrowClosed(); } if (!name.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.JsonXmlProcessingInstructionNotSupported, "name"); } if (WriteState != WriteState.Start) { throw new XmlException(SR.JsonXmlInvalidDeclaration); } } public override void WriteQualifiedName(string localName, string ns) { if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if (ns == null) { ns = string.Empty; } base.WriteQualifiedName(localName, ns); } public override void WriteRaw(string data) { WriteString(data); } public override void WriteRaw(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ValueMustBeNonNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ValueMustBeNonNegative); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count", SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index)); } WriteString(new string(buffer, index, count)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message public override void WriteStartAttribute(string prefix, string localName, string ns) { if (IsClosed) { ThrowClosed(); } if (!string.IsNullOrEmpty(prefix)) { if (IsWritingNameWithMapping && prefix == JsonGlobals.xmlnsPrefix) { if (ns != null && ns != xmlnsNamespace) { throw new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), "ns"); } } else { throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), "prefix"); } } else { if (IsWritingNameWithMapping && ns == xmlnsNamespace && localName != JsonGlobals.xmlnsPrefix) { prefix = JsonGlobals.xmlnsPrefix; } } if (!string.IsNullOrEmpty(ns)) { if (IsWritingNameWithMapping && ns == xmlnsNamespace) { prefix = JsonGlobals.xmlnsPrefix; } else if (string.IsNullOrEmpty(prefix) && localName == JsonGlobals.xmlnsPrefix && ns == xmlnsNamespace) { prefix = JsonGlobals.xmlnsPrefix; _isWritingXmlnsAttributeDefaultNs = true; } else { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), "ns"); } } if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if ((_nodeType != JsonNodeType.Element) && !_wroteServerTypeAttribute) { throw new XmlException(SR.JsonAttributeMustHaveElement); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartAttribute")); } if (prefix == JsonGlobals.xmlnsPrefix) { _isWritingXmlnsAttribute = true; } else if (localName == JsonGlobals.typeString) { if (_dataType != JsonDataType.None) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.typeString)); } _isWritingDataTypeAttribute = true; } else if (localName == JsonGlobals.serverTypeString) { if (_serverTypeValue != null) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.serverTypeString)); } if ((_dataType != JsonDataType.None) && (_dataType != JsonDataType.Object)) { throw new XmlException(SR.Format(SR.JsonServerTypeSpecifiedForInvalidDataType, JsonGlobals.serverTypeString, JsonGlobals.typeString, _dataType.ToString().ToLowerInvariant(), JsonGlobals.objectString)); } _isWritingServerTypeAttribute = true; } else if (localName == JsonGlobals.itemString) { if (WrittenNameWithMapping) { throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.itemString)); } if (!IsWritingNameWithMapping) { // Don't write attribute with local name "item" if <item> element is not open. // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.JsonEndElementNoOpenNodes); } _nameState |= NameState.IsWritingNameAttribute; } else { throw new ArgumentException(SR.Format(SR.JsonUnexpectedAttributeLocalName, localName), "localName"); } } public override void WriteStartDocument(bool standalone) { // In XML, writes the XML declaration with the version "1.0" and the standalone attribute. WriteStartDocument(); } public override void WriteStartDocument() { // In XML, writes the XML declaration with the version "1.0". if (IsClosed) { ThrowClosed(); } if (WriteState != WriteState.Start) { throw new XmlException(SR.Format(SR.JsonInvalidWriteState, "WriteStartDocument", WriteState.ToString())); } } public override void WriteStartElement(string prefix, string localName, string ns) { if (localName == null) { throw new ArgumentNullException("localName"); } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, "localName"); } if (!string.IsNullOrEmpty(prefix)) { if (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), "prefix"); } } if (!string.IsNullOrEmpty(ns)) { if (!TrySetWritingNameWithMapping(localName, ns)) { throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), "ns"); } } if (IsClosed) { ThrowClosed(); } if (HasOpenAttribute) { throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartElement")); } if ((_nodeType != JsonNodeType.None) && _depth == 0) { throw new XmlException(SR.JsonMultipleRootElementsNotAllowedOnWriter); } switch (_nodeType) { case JsonNodeType.None: { if (!localName.Equals(JsonGlobals.rootString)) { throw new XmlException(SR.Format(SR.JsonInvalidRootElementName, localName, JsonGlobals.rootString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.Element: { if ((_dataType != JsonDataType.Array) && (_dataType != JsonDataType.Object)) { throw new XmlException(SR.JsonNodeTypeArrayOrObjectNotSpecified); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } case JsonNodeType.EndElement: { if (_endElementBuffer) { _nodeWriter.WriteText(JsonGlobals.MemberSeparatorChar); } if (_indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (_nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals(JsonGlobals.itemString)) { throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString)); } EnterScope(JsonNodeType.Element); break; } default: throw new XmlException(SR.JsonInvalidStartElementCall); } _isWritingDataTypeAttribute = false; _isWritingServerTypeAttribute = false; _isWritingXmlnsAttribute = false; _wroteServerTypeAttribute = false; _serverTypeValue = null; _dataType = JsonDataType.None; _nodeType = JsonNodeType.Element; } public override void WriteString(string text) { if (HasOpenAttribute && (text != null)) { _attributeText += text; } else { if (text == null) { text = string.Empty; } // do work only when not indenting whitespaces if (!((_dataType == JsonDataType.Array || _dataType == JsonDataType.Object || _nodeType == JsonNodeType.EndElement) && XmlConverter.IsWhitespace(text))) { StartText(); WriteEscapedJsonString(text); } } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { WriteString(string.Concat(highChar, lowChar)); } public override void WriteValue(bool value) { StartText(); _nodeWriter.WriteBoolText(value); } public override void WriteValue(decimal value) { StartText(); _nodeWriter.WriteDecimalText(value); } public override void WriteValue(double value) { StartText(); _nodeWriter.WriteDoubleText(value); } public override void WriteValue(float value) { StartText(); _nodeWriter.WriteFloatText(value); } public override void WriteValue(int value) { StartText(); _nodeWriter.WriteInt32Text(value); } public override void WriteValue(long value) { StartText(); _nodeWriter.WriteInt64Text(value); } public override void WriteValue(Guid value) { StartText(); _nodeWriter.WriteGuidText(value); } public virtual void WriteValue(DateTime value) { StartText(); _nodeWriter.WriteDateTimeText(value); } public override void WriteValue(string value) { WriteString(value); } public override void WriteValue(TimeSpan value) { StartText(); _nodeWriter.WriteTimeSpanText(value); } public override void WriteValue(UniqueId value) { if (value == null) { throw new ArgumentNullException("value"); } StartText(); _nodeWriter.WriteUniqueIdText(value); } public override void WriteValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw new ArgumentNullException("value"); } if (value is Array) { WriteValue((Array)value); } else if (value is IStreamProvider) { WriteValue((IStreamProvider)value); } else { WritePrimitiveValue(value); } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", Justification = "This method is derived from the base")] public override void WriteWhitespace(string ws) { if (IsClosed) { ThrowClosed(); } if (ws == null) { throw new ArgumentNullException("ws"); } for (int i = 0; i < ws.Length; ++i) { char c = ws[i]; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { throw new ArgumentException(SR.Format(SR.JsonOnlyWhitespace, c.ToString(), "WriteWhitespace"), "ws"); } } WriteString(ws); } public override void WriteXmlAttribute(string localName, string value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } public override void WriteXmlnsAttribute(string prefix, string namespaceUri) { if (!IsWritingNameWithMapping) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute")); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) { if (!IsWritingNameWithMapping) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute")); } } internal static bool CharacterNeedsEscaping(char ch) { return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH || (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR))); } private static void ThrowClosed() { throw new InvalidOperationException(SR.JsonWriterClosed); } private void CheckText(JsonNodeType nextNodeType) { if (IsClosed) { ThrowClosed(); } if (_depth == 0) { throw new InvalidOperationException(SR.XmlIllegalOutsideRoot); } if ((nextNodeType == JsonNodeType.StandaloneText) && (_nodeType == JsonNodeType.QuotedText)) { throw new XmlException(SR.JsonCannotWriteStandaloneTextAfterQuotedText); } } private void EnterScope(JsonNodeType currentNodeType) { _depth++; if (_scopes == null) { _scopes = new JsonNodeType[4]; } else if (_scopes.Length == _depth) { JsonNodeType[] newScopes = new JsonNodeType[_depth * 2]; Array.Copy(_scopes, 0, newScopes, 0, _depth); _scopes = newScopes; } _scopes[_depth] = currentNodeType; } private JsonNodeType ExitScope() { JsonNodeType nodeTypeToReturn = _scopes[_depth]; _scopes[_depth] = JsonNodeType.None; _depth--; return nodeTypeToReturn; } private void InitializeWriter() { _nodeType = JsonNodeType.None; _dataType = JsonDataType.None; _isWritingDataTypeAttribute = false; _wroteServerTypeAttribute = false; _isWritingServerTypeAttribute = false; _serverTypeValue = null; _attributeText = null; if (_depth != 0) { _depth = 0; } if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize)) { _scopes = null; } // Can't let writeState be at Closed if reinitializing. _writeState = WriteState.Start; _endElementBuffer = false; _indentLevel = 0; } private static bool IsUnicodeNewlineCharacter(char c) { // Newline characters in JSON strings need to be encoded on the way out (DevDiv #665974) // See Unicode 6.2, Table 5-1 (http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) for the full list. // We only care about NEL, LS, and PS, since the other newline characters are all // control characters so are already encoded. return (c == '\u0085' || c == '\u2028' || c == '\u2029'); } private void StartText() { if (HasOpenAttribute) { throw new InvalidOperationException(SR.JsonMustUseWriteStringForWritingAttributeValues); } if ((_dataType == JsonDataType.None) && (_serverTypeValue != null)) { throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString)); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { // Don't write out any text content unless the local name has been written. // Not providing a better error message because localization deadline has passed. throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString)); } if ((_dataType == JsonDataType.String) || (_dataType == JsonDataType.None)) { CheckText(JsonNodeType.QuotedText); if (_nodeType != JsonNodeType.QuotedText) { WriteJsonQuote(); } _nodeType = JsonNodeType.QuotedText; } else if ((_dataType == JsonDataType.Number) || (_dataType == JsonDataType.Boolean)) { CheckText(JsonNodeType.StandaloneText); _nodeType = JsonNodeType.StandaloneText; } else { ThrowInvalidAttributeContent(); } } private void ThrowIfServerTypeWritten(string dataTypeSpecified) { if (_serverTypeValue != null) { throw new XmlException(SR.Format(SR.JsonInvalidDataTypeSpecifiedForServerType, JsonGlobals.typeString, dataTypeSpecified, JsonGlobals.serverTypeString, JsonGlobals.objectString)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message private void ThrowInvalidAttributeContent() { if (HasOpenAttribute) { throw new XmlException(SR.JsonInvalidMethodBetweenStartEndAttribute); } else { throw new XmlException(SR.Format(SR.JsonCannotWriteTextAfterNonTextAttribute, _dataType.ToString().ToLowerInvariant())); } } private bool TrySetWritingNameWithMapping(string localName, string ns) { if (localName.Equals(JsonGlobals.itemString) && ns.Equals(JsonGlobals.itemString)) { _nameState = NameState.IsWritingNameWithMapping; return true; } return false; } private void WriteDataTypeServerType() { if (_dataType != JsonDataType.None) { switch (_dataType) { case JsonDataType.Array: { EnterScope(JsonNodeType.Collection); _nodeWriter.WriteText(JsonGlobals.CollectionChar); _indentLevel++; break; } case JsonDataType.Object: { EnterScope(JsonNodeType.Object); _nodeWriter.WriteText(JsonGlobals.ObjectChar); _indentLevel++; break; } case JsonDataType.Null: { _nodeWriter.WriteText(JsonGlobals.nullString); break; } default: break; } if (_serverTypeValue != null) { // dataType must be object because we throw in all other case. WriteServerTypeAttribute(); } } } [SecuritySafeCritical] private unsafe void WriteEscapedJsonString(string str) { fixed (char* chars = str) { int i = 0; int j; for (j = 0; j < str.Length; j++) { char ch = chars[j]; if (ch <= FORWARD_SLASH) { if (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText(ch); i = j + 1; } else if (ch < WHITESPACE) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText('u'); _nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch)); i = j + 1; } } else if (ch == BACK_SLASH) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText(ch); i = j + 1; } else if ((ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR)) || IsUnicodeNewlineCharacter(ch)) { _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText('u'); _nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch)); i = j + 1; } } if (i < j) { _nodeWriter.WriteChars(chars + i, j - i); } } } private void WriteIndent() { for (int i = 0; i < _indentLevel; i++) { _nodeWriter.WriteText(_indentChars); } } private void WriteNewLine() { _nodeWriter.WriteText(CARRIAGE_RETURN); _nodeWriter.WriteText(NEWLINE); } private void WriteJsonElementName(string localName) { WriteJsonQuote(); WriteEscapedJsonString(localName); WriteJsonQuote(); _nodeWriter.WriteText(JsonGlobals.NameValueSeparatorChar); if (_indent) { _nodeWriter.WriteText(WHITESPACE); } } private void WriteJsonQuote() { _nodeWriter.WriteText(JsonGlobals.QuoteChar); } private void WritePrimitiveValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw new ArgumentNullException("value"); } if (value is ulong) { WriteValue((ulong)value); } else if (value is string) { WriteValue((string)value); } else if (value is int) { WriteValue((int)value); } else if (value is long) { WriteValue((long)value); } else if (value is bool) { WriteValue((bool)value); } else if (value is double) { WriteValue((double)value); } else if (value is DateTime) { WriteValue((DateTime)value); } else if (value is float) { WriteValue((float)value); } else if (value is decimal) { WriteValue((decimal)value); } else if (value is XmlDictionaryString) { WriteValue((XmlDictionaryString)value); } else if (value is UniqueId) { WriteValue((UniqueId)value); } else if (value is Guid) { WriteValue((Guid)value); } else if (value is TimeSpan) { WriteValue((TimeSpan)value); } else if (value.GetType().IsArray) { throw new ArgumentException(SR.JsonNestedArraysNotSupported, "value"); } else { base.WriteValue(value); } } private void WriteServerTypeAttribute() { string value = _serverTypeValue; JsonDataType oldDataType = _dataType; NameState oldNameState = _nameState; WriteStartElement(JsonGlobals.serverTypeString); WriteValue(value); WriteEndElement(); _dataType = oldDataType; _nameState = oldNameState; _wroteServerTypeAttribute = true; } private void WriteValue(ulong value) { StartText(); _nodeWriter.WriteUInt64Text(value); } private void WriteValue(Array array) { // This method is called only if WriteValue(object) is called with an array // The contract for XmlWriter.WriteValue(object) requires that this object array be written out as a string. // E.g. WriteValue(new int[] { 1, 2, 3}) should be equivalent to WriteString("1 2 3"). JsonDataType oldDataType = _dataType; // Set attribute mode to String because WritePrimitiveValue might write numerical text. // Calls to methods that write numbers can't be mixed with calls that write quoted text unless the attribute mode is explictly string. _dataType = JsonDataType.String; StartText(); for (int i = 0; i < array.Length; i++) { if (i != 0) { _nodeWriter.WriteText(JsonGlobals.WhitespaceChar); } WritePrimitiveValue(array.GetValue(i)); } _dataType = oldDataType; } private class JsonNodeWriter : XmlUTF8NodeWriter { [SecurityCritical] internal unsafe void WriteChars(char* chars, int charCount) { base.UnsafeWriteUTF8Chars(chars, charCount); } } } }
// Copyright (c) ZeroC, Inc. All rights reserved. using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace IceBuilder { [Guid(PropertyPageGUID)] public class PropertyPage : IPropertyPage2, IPropertyPage, IDisposable { public const string PropertyPageGUID = "1E2800FE-37C5-4FD3-BC2E-969342EE08AF"; public CSharpConfigurationView ConfigurationView { get; private set; } public IDisposable ProjectSubscription { get; private set; } public PropertyPage() => ConfigurationView = new CSharpConfigurationView(this); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (ConfigurationView != null) { ConfigurationView.Dispose(); ConfigurationView = null; } } public void Activate(IntPtr parentHandle, RECT[] pRect, int modal) { ThreadHelper.ThrowIfNotOnUIThread(); try { RECT rect = pRect[0]; ConfigurationView.Initialize(Control.FromHandle(parentHandle), Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom)); } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public void Apply() { ThreadHelper.ThrowIfNotOnUIThread(); try { Settings.OutputDir = ConfigurationView.OutputDir; Settings.IncludeDirectories = ConfigurationView.IncludeDirectories; Settings.AdditionalOptions = ConfigurationView.AdditionalOptions; Settings.Save(); ConfigurationView.Dirty = false; } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public void Deactivate() { ThreadHelper.ThrowIfNotOnUIThread(); try { if (ConfigurationView != null) { ConfigurationView.Dispose(); ConfigurationView = null; } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public void EditProperty(int DISPID) { } public void GetPageInfo(PROPPAGEINFO[] pageInfo) { ThreadHelper.ThrowIfNotOnUIThread(); try { PROPPAGEINFO proppageinfo; proppageinfo.cb = (uint)Marshal.SizeOf(typeof(PROPPAGEINFO)); proppageinfo.dwHelpContext = 0; proppageinfo.pszDocString = null; proppageinfo.pszHelpFile = null; proppageinfo.pszTitle = "Ice Builder"; proppageinfo.SIZE.cx = ConfigurationView.Size.Width; proppageinfo.SIZE.cy = ConfigurationView.Size.Height; pageInfo[0] = proppageinfo; } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public void Help(string pszHelpDir) { } public int IsPageDirty() => ConfigurationView.Dirty ? VSConstants.S_OK : VSConstants.S_FALSE; public void Move(RECT[] pRect) { ThreadHelper.ThrowIfNotOnUIThread(); try { Rectangle rect = Rectangle.FromLTRB(pRect[0].left, pRect[0].top, pRect[0].right, pRect[0].bottom); ConfigurationView.Location = new Point(rect.X, rect.Y); ConfigurationView.Size = new Size(rect.Width, rect.Height); } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public ProjectSettigns Settings { get; private set; } public IVsProject Project { get; private set; } public void SetObjects(uint cObjects, object[] objects) { ThreadHelper.ThrowIfNotOnUIThread(); try { if (objects != null && cObjects > 0) { if (objects[0] is IVsBrowseObject browse) { browse.GetProjectItem(out IVsHierarchy hier, out uint id); Project = hier as IVsProject; if (Project != null) { Settings = new ProjectSettigns(Project); Settings.Load(); ConfigurationView.LoadSettigns(Settings); ProjectSubscription = Project.OnProjectUpdate(() => { if (!ConfigurationView.Dirty) { Settings.Load(); ConfigurationView.LoadSettigns(Settings); } }); } } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } } public IPropertyPageSite PageSite { get; private set; } public void SetPageSite(IPropertyPageSite site) => PageSite = site; public const int SW_SHOW = 5; public const int SW_SHOWNORMAL = 1; public const int SW_HIDE = 0; public void Show(uint show) { switch (show) { case SW_HIDE: { ConfigurationView.Hide(); break; } case SW_SHOW: case SW_SHOWNORMAL: { ConfigurationView.Show(); break; } default: { break; } } } public int TranslateAccelerator(MSG[] pMsg) { Message message = Message.Create(pMsg[0].hwnd, (int)pMsg[0].message, pMsg[0].wParam, pMsg[0].lParam); int hr = ConfigurationView.ProcessAccelerator(ref message); pMsg[0].lParam = message.LParam; pMsg[0].wParam = message.WParam; return hr; } int IPropertyPage.Apply() { ThreadHelper.ThrowIfNotOnUIThread(); Apply(); return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; class TestException : Exception { int x; string y; public TestException() {} public TestException(int _x) { x = _x; } public TestException(string _y) { y = _y; } } class TestCases { static void Throw() => throw new TestException(); static void Throw(int x) => throw new TestException(x); static void Throw(string y) => throw new TestException(y); static int MayThrow(int x) { if (x > 0) { throw new TestException(x); } return x; } static int ReturnThrow() => throw new TestException(); public static int OneThrowHelper(int x) { if (x > 0) { Throw(); } return x; } public static void OneThrowHelperTail(int x) { if (x > 0) { Throw(); return; } } public static int OneMayThrowHelper(int x) { if (x > 0) { MayThrow(x); } return x; } public static int OneMayThrowHelperTail(int x) { if (x > 0) { MayThrow(x); return 0; } return x; } public static int OneReturnThrowHelper(int x) { if (x > 0) { return ReturnThrow(); } return x; } public static int OneReturnThrowHelperTail(int x) { if (x > 0) { return ReturnThrow(); } return x; } public static int TwoIdenticalThrowHelpers_If(int x) { if (x == 0) { Throw(); } if (x == 1) { Throw(); } return x; } public static void TwoIdenticalThrowHelpers_IfOneTail(int x) { if (x == 0) { Throw(); return; } if (x == 1) { Throw(); } } public static void TwoIdenticalThrowHelpers_IfTwoTail(int x) { if (x == 0) { Throw(); return; } if (x == 1) { Throw(); return; } } public static int ThreeIdenticalThrowHelpers_If(int x) { if (x == 0) { Throw(); } if (x == 1) { Throw(); } if (x == 2) { Throw(); } return x; } public static void ThreeIdenticalThrowHelpers_IfOneTail(int x) { if (x == 0) { Throw(); return; } if (x == 1) { Throw(); } if (x == 2) { Throw(); } } public static void ThreeIdenticalThrowHelpers_IfTwoTail(int x) { if (x == 0) { Throw(); return; } if (x == 1) { Throw(); return; } if (x == 2) { Throw(); } } public static void ThreeIdenticalThrowHelpers_IfThreeTail(int x) { if (x == 0) { Throw(); return; } if (x == 1) { Throw(); return; } if (x == 2) { Throw(); return; } } public static int TwoIdenticalThrowHelpers_Goto(int x) { if (x == 0) { goto L1; } if (x == 1) { goto L2; } return x; L1: Throw(); L2: Throw(); return x; } public static void TwoIdenticalThrowHelpers_GotoOneTail(int x) { if (x == 0) { goto L1; } if (x == 1) { goto L2; } return; L1: Throw(); L2: Throw(); } public static void TwoIdenticalThrowHelpers_GotoTwoTail(int x) { if (x == 0) { goto L1; } if (x == 1) { goto L2; } return; L1: Throw(); return; L2: Throw(); } public static int TwoIdenticalThrowHelpers_Switch(int x) { switch (x) { case 0: { Throw(); } break; case 1: { Throw(); } break; } return x; } public static void TwoIdenticalThrowHelpers_SwitchOneTail(int x) { switch (x) { case 0: { Throw(); return; } case 1: { Throw(); } break; } } public static void TwoIdenticalThrowHelpers_SwitchTwoTail(int x) { switch (x) { case 0: { Throw(); return; } case 1: { Throw(); return; } } } public static int TwoIdenticalThrowHelpers_SwitchGoto(int x) { switch (x) { case 0: { goto L1; } case 1: { goto L2; } } return x; L1: Throw(); L2: Throw(); return x; } public static void TwoIdenticalThrowHelpers_SwitchGotoOneTail(int x) { switch (x) { case 0: { goto L1; } case 1: { goto L2; } } return; L1: Throw(); L2: Throw(); } public static void TwoIdenticalThrowHelpers_SwitchGotoTwoTail(int x) { switch (x) { case 0: { goto L1; } case 1: { goto L2; } } return; L1: Throw(); return; L2: Throw(); } public static int TwoDifferentThrowHelpers(int x) { if (x == 0) { Throw(); } if (x == 1) { Throw(1); } return x; } public static int TwoIdenticalThrowHelpersDifferentArgs(int x) { if (x == 0) { Throw(0); } if (x == 1) { Throw(1); } return x; } public static int TwoIdenticalThrowHelpersSameArgTrees(int x, int[] y) { if (x == 0) { Throw(y[0]); } else if (x == 1) { Throw(y[0]); } return x; } public static int TwoIdenticalThrowHelpersDifferentArgTrees(int x, int[] y) { if (x == 0) { Throw(y[0]); } else if (x == 1) { Throw(y[1]); } return x; } static int testNumber = 0; static bool failed = false; static void Try(Func<int, int> f) { testNumber++; if (f(-1) != -1) { Console.WriteLine($"Test {testNumber} failed\n"); failed = true; } } static void Try(Func<int, int[], int> f) { testNumber++; int[] y = new int[0]; if (f(-1, y) != -1) { Console.WriteLine($"Test {testNumber} failed\n"); failed = true; } } static void Try(Action<int> f) { testNumber++; try { f(-1); } catch (TestException) { Console.WriteLine($"Test {testNumber} failed\n"); failed = true; } } public static int Main() { Try(OneThrowHelper); Try(OneThrowHelperTail); Try(OneMayThrowHelper); Try(OneMayThrowHelperTail); Try(OneReturnThrowHelper); Try(OneReturnThrowHelperTail); Try(TwoIdenticalThrowHelpers_If); Try(TwoIdenticalThrowHelpers_IfOneTail); Try(TwoIdenticalThrowHelpers_IfTwoTail); Try(TwoIdenticalThrowHelpers_Goto); Try(TwoIdenticalThrowHelpers_GotoOneTail); Try(TwoIdenticalThrowHelpers_GotoTwoTail); Try(TwoIdenticalThrowHelpers_Switch); Try(TwoIdenticalThrowHelpers_SwitchOneTail); Try(TwoIdenticalThrowHelpers_SwitchTwoTail); Try(TwoIdenticalThrowHelpers_SwitchGoto); Try(TwoIdenticalThrowHelpers_SwitchGotoOneTail); Try(TwoIdenticalThrowHelpers_SwitchGotoTwoTail); Try(TwoDifferentThrowHelpers); Try(TwoIdenticalThrowHelpersDifferentArgs); Try(ThreeIdenticalThrowHelpers_If); Try(ThreeIdenticalThrowHelpers_IfOneTail); Try(ThreeIdenticalThrowHelpers_IfTwoTail); Try(ThreeIdenticalThrowHelpers_IfThreeTail); Try(TwoIdenticalThrowHelpersSameArgTrees); Try(TwoIdenticalThrowHelpersDifferentArgTrees); Console.WriteLine(failed ? "" : $"All {testNumber} tests passed"); return failed ? -1 : 100; } }
using System; using System.Collections; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Cms; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Cms.Tests { [TestFixture] public class EnvelopedDataStreamTest { private const int BufferSize = 4000; private const string SignDN = "O=Bouncy Castle, C=AU"; private static IAsymmetricCipherKeyPair signKP; // private static X509Certificate signCert; //signCert = CmsTestUtil.MakeCertificate(_signKP, SignDN, _signKP, SignDN); // private const string OrigDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; // private static IAsymmetricCipherKeyPair origKP; //origKP = CmsTestUtil.MakeKeyPair(); // private static X509Certificate origCert; //origCert = CmsTestUtil.MakeCertificate(origKP, OrigDN, _signKP, SignDN); private const string ReciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; private static IAsymmetricCipherKeyPair reciKP; private static X509Certificate reciCert; private static IAsymmetricCipherKeyPair origECKP; private static IAsymmetricCipherKeyPair reciECKP; private static X509Certificate reciECCert; private static IAsymmetricCipherKeyPair SignKP { get { return signKP == null ? (signKP = CmsTestUtil.MakeKeyPair()) : signKP; } } private static IAsymmetricCipherKeyPair ReciKP { get { return reciKP == null ? (reciKP = CmsTestUtil.MakeKeyPair()) : reciKP; } } private static X509Certificate ReciCert { get { return reciCert == null ? (reciCert = CmsTestUtil.MakeCertificate(ReciKP, ReciDN, SignKP, SignDN)) : reciCert;} } private static IAsymmetricCipherKeyPair OrigECKP { get { return origECKP == null ? (origECKP = CmsTestUtil.MakeECDsaKeyPair()) : origECKP; } } private static IAsymmetricCipherKeyPair ReciECKP { get { return reciECKP == null ? (reciECKP = CmsTestUtil.MakeECDsaKeyPair()) : reciECKP; } } private static X509Certificate ReciECCert { get { return reciECCert == null ? (reciECCert = CmsTestUtil.MakeCertificate(ReciECKP, ReciDN, SignKP, SignDN)) : reciECCert;} } [Test] public void TestWorkingData() { byte[] keyData = Base64.Decode( "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKrAz/SQKrcQ" + "nj9IxHIfKDbuXsMqUpI06s2gps6fp7RDNvtUDDMOciWGFhD45YSy8GO0mPx3" + "Nkc7vKBqX4TLcqLUz7kXGOHGOwiPZoNF+9jBMPNROe/B0My0PkWg9tuq+nxN" + "64oD47+JvDwrpNOS5wsYavXeAW8Anv9ZzHLU7KwZAgMBAAECgYA/fqdVt+5K" + "WKGfwr1Z+oAHvSf7xtchiw/tGtosZ24DOCNP3fcTXUHQ9kVqVkNyzt9ZFCT3" + "bJUAdBQ2SpfuV4DusVeQZVzcROKeA09nPkxBpTefWbSDQGhb+eZq9L8JDRSW" + "HyYqs+MBoUpLw7GKtZiJkZyY6CsYkAnQ+uYVWq/TIQJBAP5zafO4HUV/w4KD" + "VJi+ua+GYF1Sg1t/dYL1kXO9GP1p75YAmtm6LdnOCas7wj70/G1YlPGkOP0V" + "GFzeG5KAmAUCQQCryvKU9nwWA+kypcQT9Yr1P4vGS0APYoBThnZq7jEPc5Cm" + "ZI82yseSxSeea0+8KQbZ5mvh1p3qImDLEH/iNSQFAkAghS+tboKPN10NeSt+" + "uiGRRWNbiggv0YJ7Uldcq3ZeLQPp7/naiekCRUsHD4Qr97OrZf7jQ1HlRqTu" + "eZScjMLhAkBNUMZCQnhwFAyEzdPkQ7LpU1MdyEopYmRssuxijZao5JLqQAGw" + "YCzXokGFa7hz72b09F4DQurJL/WuDlvvu4jdAkEAxwT9lylvfSfEQw4/qQgZ" + "MFB26gqB6Gqs1pHIZCzdliKx5BO3VDeUGfXMI8yOkbXoWbYx5xPid/+N8R//" + "+sxLBw=="); byte[] envData = Base64.Decode( "MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKEw1C" + "b3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBHjANBgkqhkiG9w0BAQEFAASB" + "gDmnaDZ0vDJNlaUSYyEXsgbaUH+itNTjCOgv77QTX2ImXj+kTctM19PQF2I1" + "0/NL0fjakvCgBTHKmk13a7jqB6cX3bysenHNrglHsgNGgeXQ7ggAq5fV/JQQ" + "T7rSxEtuwpbuHQnoVUZahOHVKy/a0uLr9iIh1A3y+yZTZaG505ZJMIAGCSqG" + "SIb3DQEHATAdBglghkgBZQMEAQIEENmkYNbDXiZxJWtq82qIRZKggAQgkOGr" + "1JcTsADStez1eY4+rO4DtyBIyUYQ3pilnbirfPkAAAAAAAAAAAAA"); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(envData); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc); ICollection c = recipients.GetRecipients(); // PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData); // KeyFactory keyFact = KeyFactory.GetInstance("RSA"); // Key priKey = keyFact.generatePrivate(keySpec); IAsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(keyData); byte[] data = Hex.Decode("57616c6c6157616c6c6157617368696e67746f6e"); foreach (RecipientInformation recipient in c) { Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id); CmsTypedStream recData = recipient.GetContentStream(priKey); byte[] compare = CmsTestUtil.StreamToByteArray(recData.ContentStream); Assert.IsTrue(Arrays.AreEqual(data, compare)); } } private void VerifyData( byte[] encodedBytes, string expectedOid, byte[] expectedData) { CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(encodedBytes); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, expectedOid); ICollection c = recipients.GetRecipients(); foreach (RecipientInformation recipient in c) { Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id); CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private); Assert.IsTrue(Arrays.AreEqual(expectedData, CmsTestUtil.StreamToByteArray( recData.ContentStream))); } } [Test] public void TestKeyTransAes128BufferedStream() { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } // // unbuffered // CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyTransRecipient(ReciCert); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.Aes128Cbc); for (int i = 0; i != 2000; i++) { outStream.WriteByte(data[i]); } outStream.Close(); VerifyData(bOut.ToArray(), CmsEnvelopedDataGenerator.Aes128Cbc, data); int unbufferedLength = bOut.ToArray().Length; // // Using buffered output - should be == to unbuffered // edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyTransRecipient(ReciCert); bOut.SetLength(0); outStream = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc); Streams.PipeAll(new MemoryStream(data, false), outStream); outStream.Close(); VerifyData(bOut.ToArray(), CmsEnvelopedDataGenerator.Aes128Cbc, data); Assert.AreEqual(unbufferedLength, bOut.ToArray().Length); } [Test] public void TestKeyTransAes128Buffered() { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } // // unbuffered // CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyTransRecipient(ReciCert); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.Aes128Cbc); for (int i = 0; i != 2000; i++) { outStream.WriteByte(data[i]); } outStream.Close(); VerifyData(bOut.ToArray(), CmsEnvelopedDataGenerator.Aes128Cbc, data); int unbufferedLength = bOut.ToArray().Length; // // buffered - less than default of 1000 // edGen = new CmsEnvelopedDataStreamGenerator(); edGen.SetBufferSize(300); edGen.AddKeyTransRecipient(ReciCert); bOut.SetLength(0); outStream = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc); for (int i = 0; i != 2000; i++) { outStream.WriteByte(data[i]); } outStream.Close(); VerifyData(bOut.ToArray(), CmsEnvelopedDataGenerator.Aes128Cbc, data); Assert.IsTrue(unbufferedLength < bOut.ToArray().Length); } [Test] public void TestKeyTransAes128Der() { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyTransRecipient(ReciCert); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.Aes128Cbc); for (int i = 0; i != 2000; i++) { outStream.WriteByte(data[i]); } outStream.Close(); // convert to DER byte[] derEncodedBytes = Asn1Object.FromByteArray(bOut.ToArray()).GetDerEncoded(); VerifyData(derEncodedBytes, CmsEnvelopedDataGenerator.Aes128Cbc, data); } [Test] public void TestKeyTransAes128Throughput() { byte[] data = new byte[40001]; for (int i = 0; i != data.Length; i++) { data[i] = (byte)(i & 0xff); } // // buffered // CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.SetBufferSize(BufferSize); edGen.AddKeyTransRecipient(ReciCert); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc); for (int i = 0; i != data.Length; i++) { outStream.WriteByte(data[i]); } outStream.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); ICollection c = recipients.GetRecipients(); IEnumerator e = c.GetEnumerator(); if (e.MoveNext()) { RecipientInformation recipient = (RecipientInformation) e.Current; Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id); CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private); Stream dataStream = recData.ContentStream; MemoryStream dataOut = new MemoryStream(); int len; byte[] buf = new byte[BufferSize]; int count = 0; while (count != 10 && (len = dataStream.Read(buf, 0, buf.Length)) > 0) { Assert.AreEqual(buf.Length, len); dataOut.Write(buf, 0, buf.Length); count++; } len = dataStream.Read(buf, 0, buf.Length); dataOut.Write(buf, 0, len); Assert.IsTrue(Arrays.AreEqual(data, dataOut.ToArray())); } else { Assert.Fail("recipient not found."); } } [Test] public void TestKeyTransAes128() { byte[] data = Encoding.Default.GetBytes("WallaWallaWashington"); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyTransRecipient(ReciCert); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.Aes128Cbc); outStream.Write(data, 0, data.Length); outStream.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc); ICollection c = recipients.GetRecipients(); foreach (RecipientInformation recipient in c) { Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id); CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); } ep.Close(); } [Test] public void TestAesKek() { byte[] data = Encoding.Default.GetBytes("WallaWallaWashington"); KeyParameter kek = CmsTestUtil.MakeAes192Key(); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); byte[] kekId = new byte[] { 1, 2, 3, 4, 5 }; edGen.AddKekRecipient("AES192", kek, kekId); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.DesEde3Cbc); outStream.Write(data, 0, data.Length); outStream.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.DesEde3Cbc); ICollection c = recipients.GetRecipients(); foreach (RecipientInformation recipient in c) { Assert.AreEqual(recipient.KeyEncryptionAlgOid, "2.16.840.1.101.3.4.1.25"); CmsTypedStream recData = recipient.GetContentStream(kek); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); } ep.Close(); } [Test] public void TestTwoAesKek() { byte[] data = Encoding.Default.GetBytes("WallaWallaWashington"); KeyParameter kek1 = CmsTestUtil.MakeAes192Key(); KeyParameter kek2 = CmsTestUtil.MakeAes192Key(); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); byte[] kekId1 = new byte[] { 1, 2, 3, 4, 5 }; byte[] kekId2 = new byte[] { 5, 4, 3, 2, 1 }; edGen.AddKekRecipient("AES192", kek1, kekId1); edGen.AddKekRecipient("AES192", kek2, kekId2); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.DesEde3Cbc); outStream.Write(data, 0, data.Length); outStream.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.DesEde3Cbc); RecipientID recSel = new RecipientID(); recSel.KeyIdentifier = kekId2; RecipientInformation recipient = recipients.GetFirstRecipient(recSel); Assert.AreEqual(recipient.KeyEncryptionAlgOid, "2.16.840.1.101.3.4.1.25"); CmsTypedStream recData = recipient.GetContentStream(kek2); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); ep.Close(); } [Test] public void TestECKeyAgree() { byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65"); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyAgreementRecipient( CmsEnvelopedDataGenerator.ECDHSha1Kdf, OrigECKP.Private, OrigECKP.Public, ReciECCert, CmsEnvelopedDataGenerator.Aes128Wrap); MemoryStream bOut = new MemoryStream(); Stream outStr = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc); outStr.Write(data, 0, data.Length); outStr.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc); RecipientID recSel = new RecipientID(); // recSel.SetIssuer(PrincipalUtilities.GetIssuerX509Principal(ReciECCert).GetEncoded()); recSel.Issuer = PrincipalUtilities.GetIssuerX509Principal(ReciECCert); recSel.SerialNumber = ReciECCert.SerialNumber; RecipientInformation recipient = recipients.GetFirstRecipient(recSel); CmsTypedStream recData = recipient.GetContentStream(ReciECKP.Private); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); ep.Close(); } [Test] public void TestOriginatorInfo() { CmsEnvelopedDataParser env = new CmsEnvelopedDataParser(CmsSampleMessages.originatorMessage); env.GetRecipientInfos(); Assert.AreEqual(CmsEnvelopedDataGenerator.DesEde3Cbc, env.EncryptionAlgOid); } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Burrows.Configuration; using Burrows.Endpoints; namespace Burrows.Services.Subscriptions.Server { using System; using System.Collections.Generic; using System.Linq; using Exceptions; using Logging; using Magnum.Extensions; using Messages; using Saga; using Saga.Configuration; using Subscriptions.Messages; public class SubscriptionService : Consumes<SubscriptionClientAdded>.All, Consumes<SubscriptionClientRemoved>.All, Consumes<SubscriptionAdded>.All, Consumes<SubscriptionRemoved>.All, IDisposable { private static readonly ILog _log = Logger.Get<SubscriptionService>(); private readonly ISagaRepository<SubscriptionClientSaga> _subscriptionClientSagas; private readonly ISagaRepository<SubscriptionSaga> _subscriptionSagas; IServiceBus _bus; bool _disposed; UnsubscribeAction _unsubscribeToken = () => false; public SubscriptionService(IServiceBus bus, ISagaRepository<SubscriptionSaga> subscriptionSagas, ISagaRepository<SubscriptionClientSaga> subscriptionClientSagas) { _bus = bus; _subscriptionSagas = subscriptionSagas; _subscriptionClientSagas = subscriptionClientSagas; } public void Consume(SubscriptionAdded message) { _log.Debug(() => string.Format("Subscription Added: {0} [{1}]", message.Subscription, message.Subscription.CorrelationId)); var add = new AddSubscription(message.Subscription); SendToClients(add); } public void Consume(SubscriptionClientAdded message) { _log.Debug(() => string.Format("Subscription Client Added: {0} [{1}]", message.ControlUri, message.ClientId)); var add = new AddSubscriptionClient(message.ClientId, message.ControlUri, message.DataUri); SendClientToClients(add); SendCacheUpdateToClient(message.ControlUri, message.ClientId); } public void Consume(SubscriptionClientRemoved message) { _log.Debug(() => string.Format("Subscription Client Removed: {0} [{1}]", message.ControlUri, message.CorrelationId)); var remove = new RemoveSubscriptionClient(message.CorrelationId, message.ControlUri, message.DataUri); SendClientToClients(remove); } public void Consume(SubscriptionRemoved message) { _log.Debug(() => string.Format("Subscription Removed: {0} [{1}]", message.Subscription, message.Subscription.CorrelationId)); var remove = new RemoveSubscription(message.Subscription); SendToClients(remove); } public void Dispose() { Dispose(true); } public void Start() { _log.InfoFormat("Subscription Service Starting: {0}", _bus.Endpoint.Address); _unsubscribeToken += _bus.SubscribeInstance(this); _unsubscribeToken += _bus.SubscribeSaga(_subscriptionClientSagas); _unsubscribeToken += _bus.SubscribeSaga(_subscriptionSagas); _log.Info("Subscription Service Started"); } public void Stop() { _log.Info("Subscription Service Stopping"); _unsubscribeToken(); _log.Info("Subscription Service Stopped"); } void Dispose(bool disposing) { if (_disposed) return; if (disposing) { try { _bus.Dispose(); _bus = null; } catch (Exception ex) { string message = "Error in shutting down the SubscriptionService: " + ex.Message; var exp = new ShutDownException(message, ex); _log.Error(message, exp); throw exp; } } _disposed = true; } void SendToClients<T>(T message) where T : SubscriptionChange { SubscriptionClientSaga forClient = _subscriptionClientSagas .Where(x => x.CorrelationId == message.Subscription.ClientId) .FirstOrDefault(); if (forClient == null) return; List<SubscriptionClientSaga> sagas = _subscriptionClientSagas .Where(x => x.CurrentState == SubscriptionClientSaga.Active) .Where(x => x.ControlUri != forClient.ControlUri) .ToList(); _log.DebugFormat("Sending {0}:{1} to {2} clients", typeof (T).Name, message.Subscription.MessageName, sagas.Count()); sagas.Each(client => { IEndpoint endpoint = _bus.GetEndpoint(client.ControlUri); endpoint.Send(message, x => x.SetSourceAddress(_bus.Endpoint.Address.Uri)); }); } void SendClientToClients<T>(T message) where T : SubscriptionClientMessageBase { IEnumerable<SubscriptionClientSaga> sagas = _subscriptionClientSagas .Where(x => x.CurrentState == SubscriptionClientSaga.Active) .Where(x => x.ControlUri != message.ControlUri); sagas.Each(client => { _log.DebugFormat("Sending {2} {0} to {1}", message.CorrelationId, client.ControlUri, typeof (T).Name); IEndpoint endpoint = _bus.GetEndpoint(client.ControlUri); endpoint.Send(message, x => x.SetSourceAddress(_bus.Endpoint.Address.Uri)); }); } void SendCacheUpdateToClient(Uri uri, Guid clientId) { IEndpoint endpoint = _bus.GetEndpoint(uri); IEnumerable<SubscriptionClientSaga> sagas = _subscriptionClientSagas .Where(x => x.CurrentState == SubscriptionClientSaga.Active && x.ControlUri != uri) .ToList(); sagas.Each(client => { _log.DebugFormat("Sending AddClient {0} to {1}", client.CorrelationId, uri); var message = new AddSubscriptionClient(client.CorrelationId, client.ControlUri, client.DataUri); endpoint.Send(message, x => x.SetSourceAddress(_bus.Endpoint.Address.Uri)); }); List<Guid> clients = sagas.Select(x => x.CorrelationId).ToList(); SubscriptionInformation[] subscriptions = _subscriptionSagas .Where(x => x.CurrentState == SubscriptionSaga.Active && clients.Contains(x.SubscriptionInfo.ClientId)) .Select(x => x.SubscriptionInfo).ToArray(); _log.InfoFormat("Sending {0} subscriptions to {1}", subscriptions.Length, uri); var response = new SubscriptionRefresh(subscriptions); endpoint.Send(response, x => x.SetSourceAddress(_bus.Endpoint.Address.Uri)); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Collections.Specialized; using System.Linq; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Xunit; namespace Avalonia.Controls.UnitTests { public class ContentControlTests { [Fact] public void Template_Should_Be_Instantiated() { var target = new ContentControl(); target.Content = "Foo"; target.Template = GetTemplate(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = ((IVisual)target).VisualChildren.Single(); Assert.IsType<Border>(child); child = child.VisualChildren.Single(); Assert.IsType<ContentPresenter>(child); child = child.VisualChildren.Single(); Assert.IsType<TextBlock>(child); } [Fact] public void Templated_Children_Should_Be_Styled() { var root = new TestRoot(); var target = new ContentControl(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); target.Content = "Foo"; target.Template = GetTemplate(); root.Child = target; target.ApplyTemplate(); styler.Verify(x => x.ApplyStyles(It.IsAny<ContentControl>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<Border>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<ContentPresenter>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once()); } [Fact] public void ContentPresenter_Should_Have_TemplatedParent_Set() { var target = new ContentControl(); var child = new Border(); target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var contentPresenter = child.GetVisualParent<ContentPresenter>(); Assert.Equal(target, contentPresenter.TemplatedParent); } [Fact] public void Content_Should_Have_TemplatedParent_Set_To_Null() { var target = new ContentControl(); var child = new Border(); target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Null(child.TemplatedParent); } [Fact] public void Control_Content_Should_Be_Logical_Child_Before_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; var child = new Control(); target.Content = child; Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Control_Content_Should_Be_Logical_Child_After_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; var child = new Control(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Should_Use_ContentTemplate_To_Create_Control() { var target = new ContentControl { Template = GetTemplate(), ContentTemplate = new FuncDataTemplate<string>(_ => new Canvas()), }; target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = target.Presenter.Child; Assert.IsType<Canvas>(child); } [Fact] public void DataTemplate_Created_Control_Should_Be_Logical_Child_After_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = target.Presenter.Child; Assert.NotNull(child); Assert.Equal(target, child.Parent); Assert.Equal(target, child.GetLogicalParent()); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Clearing_Content_Should_Clear_Logical_Child() { var target = new ContentControl(); var child = new Control(); target.Content = child; Assert.Equal(new[] { child }, target.GetLogicalChildren()); target.Content = null; Assert.Null(child.Parent); Assert.Null(child.GetLogicalParent()); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Setting_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child = new Control(); var called = false; ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.True(called); } [Fact] public void Clearing_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Content = null; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.True(called); } [Fact] public void Changing_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child1 = new Control(); var child2 = new Control(); var called = false; target.Template = GetTemplate(); target.Content = child1; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Content = child2; target.Presenter.ApplyTemplate(); Assert.True(called); } [Fact] public void Changing_Content_Should_Update_Presenter() { var target = new ContentControl(); target.Template = GetTemplate(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); target.Content = "Foo"; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Foo", ((TextBlock)target.Presenter.Child).Text); target.Content = "Bar"; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Bar", ((TextBlock)target.Presenter.Child).Text); } [Fact] public void DataContext_Should_Be_Set_For_DataTemplate_Created_Content() { var target = new ContentControl(); target.Template = GetTemplate(); target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Foo", target.Presenter.Child.DataContext); } [Fact] public void DataContext_Should_Not_Be_Set_For_Control_Content() { var target = new ContentControl(); target.Template = GetTemplate(); target.Content = new TextBlock(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Null(target.Presenter.Child.DataContext); } private FuncControlTemplate GetTemplate() { return new FuncControlTemplate<ContentControl>(parent => { return new Border { Background = new Media.SolidColorBrush(0xffffffff), Child = new ContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = parent[~ContentControl.ContentProperty], [~ContentPresenter.ContentTemplateProperty] = parent[~ContentControl.ContentTemplateProperty], } }; }); } } }
namespace BooCompiler.Tests { using NUnit.Framework; using Boo.Lang.Compiler; [TestFixture] public class CompilerWarningsTestFixture : AbstractCompilerTestCase { protected override CompilerPipeline SetUpCompilerPipeline() { CompilerPipeline pipeline = new Boo.Lang.Compiler.Pipelines.Compile(); pipeline.Add(new Boo.Lang.Compiler.Steps.PrintWarnings()); return pipeline; } [Test] public void BCW0001_10() { RunCompilerTestCase(@"BCW0001-10.boo"); } [Test] public void BCW0001_4() { RunCompilerTestCase(@"BCW0001-4.boo"); } [Test] public void BCW0002_1() { RunCompilerTestCase(@"BCW0002-1.boo"); } [Test] public void BCW0003_1() { RunCompilerTestCase(@"BCW0003-1.boo"); } [Test] public void BCW0003_2() { RunCompilerTestCase(@"BCW0003-2.boo"); } [Test] public void BCW0004_1() { RunCompilerTestCase(@"BCW0004-1.boo"); } [Test] public void BCW0004_2() { RunCompilerTestCase(@"BCW0004-2.boo"); } [Test] public void BCW0005_1() { RunCompilerTestCase(@"BCW0005-1.boo"); } [Test] public void BCW0006_1() { RunCompilerTestCase(@"BCW0006-1.boo"); } [Test] public void BCW0006_2() { RunCompilerTestCase(@"BCW0006-2.boo"); } [Test] public void BCW0007_1() { RunCompilerTestCase(@"BCW0007-1.boo"); } [Test] public void BCW0008_1() { RunCompilerTestCase(@"BCW0008-1.boo"); } [Test] public void BCW0011_1() { RunCompilerTestCase(@"BCW0011-1.boo"); } [Test] public void BCW0011_10() { RunCompilerTestCase(@"BCW0011-10.boo"); } [Test] public void BCW0011_11() { RunCompilerTestCase(@"BCW0011-11.boo"); } [Test] public void BCW0011_12() { RunCompilerTestCase(@"BCW0011-12.boo"); } [Test] public void BCW0011_13() { RunCompilerTestCase(@"BCW0011-13.boo"); } [Test] public void BCW0011_14() { RunCompilerTestCase(@"BCW0011-14.boo"); } [Test] public void BCW0011_15() { RunCompilerTestCase(@"BCW0011-15.boo"); } [Test] public void BCW0011_16() { RunCompilerTestCase(@"BCW0011-16.boo"); } [Test] public void BCW0011_17() { RunCompilerTestCase(@"BCW0011-17.boo"); } [Test] public void BCW0011_2() { RunCompilerTestCase(@"BCW0011-2.boo"); } [Test] public void BCW0011_3() { RunCompilerTestCase(@"BCW0011-3.boo"); } [Test] public void BCW0011_4() { RunCompilerTestCase(@"BCW0011-4.boo"); } [Test] public void BCW0011_5() { RunCompilerTestCase(@"BCW0011-5.boo"); } [Test] public void BCW0011_6() { RunCompilerTestCase(@"BCW0011-6.boo"); } [Test] public void BCW0011_7() { RunCompilerTestCase(@"BCW0011-7.boo"); } [Test] public void BCW0011_8() { RunCompilerTestCase(@"BCW0011-8.boo"); } [Test] public void BCW0011_9() { RunCompilerTestCase(@"BCW0011-9.boo"); } [Test] public void BCW0012_1() { RunCompilerTestCase(@"BCW0012-1.boo"); } [Test] public void BCW0013_1() { RunCompilerTestCase(@"BCW0013-1.boo"); } [Test] public void BCW0013_2() { RunCompilerTestCase(@"BCW0013-2.boo"); } [Test] public void BCW0013_3() { RunCompilerTestCase(@"BCW0013-3.boo"); } [Test] public void BCW0014_1() { RunCompilerTestCase(@"BCW0014-1.boo"); } [Test] public void BCW0014_2() { RunCompilerTestCase(@"BCW0014-2.boo"); } [Test] public void BCW0015_1() { RunCompilerTestCase(@"BCW0015-1.boo"); } [Test] public void BCW0015_2() { RunCompilerTestCase(@"BCW0015-2.boo"); } [Test] public void BCW0015_3() { RunCompilerTestCase(@"BCW0015-3.boo"); } [Test] public void BCW0015_4() { RunCompilerTestCase(@"BCW0015-4.boo"); } [Test] public void BCW0015_5() { RunCompilerTestCase(@"BCW0015-5.boo"); } [Test] public void BCW0016_1() { RunCompilerTestCase(@"BCW0016-1.boo"); } [Test] public void BCW0017_1() { RunCompilerTestCase(@"BCW0017-1.boo"); } [Test] public void BCW0018_1() { RunCompilerTestCase(@"BCW0018-1.boo"); } [Test] public void BCW0019_1() { RunCompilerTestCase(@"BCW0019-1.boo"); } [Test] public void BCW0020_1() { RunCompilerTestCase(@"BCW0020-1.boo"); } [Test] public void BCW0021_1() { RunCompilerTestCase(@"BCW0021-1.boo"); } [Test] public void BCW0022_1() { RunCompilerTestCase(@"BCW0022-1.boo"); } [Test] public void BCW0022_2() { RunCompilerTestCase(@"BCW0022-2.boo"); } [Test] public void BCW0023_1() { RunCompilerTestCase(@"BCW0023-1.boo"); } [Test] public void BCW0024_1() { RunCompilerTestCase(@"BCW0024-1.boo"); } [Test] public void BCW0025_1() { RunCompilerTestCase(@"BCW0025-1.boo"); } [Test] public void BCW0026_1() { RunCompilerTestCase(@"BCW0026-1.boo"); } [Test] public void BCW0027_1() { RunCompilerTestCase(@"BCW0027-1.boo"); } [Test] public void BCW0028_1() { RunCompilerTestCase(@"BCW0028-1.boo"); } [Test] public void BCW0028_2() { RunCompilerTestCase(@"BCW0028-2.boo"); } [Test] public void BCW0029_1() { RunCompilerTestCase(@"BCW0029-1.boo"); } [Test] public void no_unreacheable_code_warning_for_compiler_generated_code() { RunCompilerTestCase(@"no-unreacheable-code-warning-for-compiler-generated-code.boo"); } [Test] public void nowarn_1() { RunCompilerTestCase(@"nowarn-1.boo"); } [Test] public void nowarn_2() { RunCompilerTestCase(@"nowarn-2.boo"); } override protected string GetRelativeTestCasesPath() { return "warnings"; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class XInventoryServicesConnector : BaseServiceConnector, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Number of requests made to the remote inventory service. /// </summary> public int RequestsMade { get; private set; } private string m_ServerURI = String.Empty; private int m_maxRetries = 0; /// <summary> /// Timeout for remote requests. /// </summary> /// <remarks> /// In this case, -1 is default timeout (100 seconds), not infinite. /// </remarks> private int m_requestTimeoutSecs = -1; private string m_configName = "InventoryService"; private const double CACHE_EXPIRATION_SECONDS = 20.0; private static ExpiringCache<UUID, InventoryItemBase> m_ItemCache = new ExpiringCache<UUID,InventoryItemBase>(); public XInventoryServicesConnector() { } public XInventoryServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public XInventoryServicesConnector(IConfigSource source, string configName) : base(source, configName) { m_configName = configName; Initialise(source); } public XInventoryServicesConnector(IConfigSource source) : base(source, "InventoryService") { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig config = source.Configs[m_configName]; if (config == null) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: {0} missing from OpenSim.ini", m_configName); throw new Exception("Inventory connector init error"); } string serviceURI = config.GetString("InventoryServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService"); throw new Exception("Inventory connector init error"); } m_ServerURI = serviceURI; m_requestTimeoutSecs = config.GetInt("RemoteRequestTimeout", m_requestTimeoutSecs); m_maxRetries = config.GetInt("MaxRetries", m_maxRetries); StatsManager.RegisterStat( new Stat( "RequestsMade", "Requests made", "Number of requests made to the remove inventory service", "requests", "inventory", serviceURI, StatType.Pull, MeasuresOfInterest.AverageChangeOverTime, s => s.Value = RequestsMade, StatVerbosity.Debug)); } private bool CheckReturn(Dictionary<string, object> ret) { if (ret == null) return false; if (ret.Count == 0) return false; if (ret.ContainsKey("RESULT")) { if (ret["RESULT"] is string) { bool result; if (bool.TryParse((string)ret["RESULT"], out result)) return result; return false; } } return true; } public bool CreateUserInventory(UUID principalID) { Dictionary<string,object> ret = MakeRequest("CREATEUSERINVENTORY", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() } }); return CheckReturn(ret); } public List<InventoryFolderBase> GetInventorySkeleton(UUID principalID) { Dictionary<string,object> ret = MakeRequest("GETINVENTORYSKELETON", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() } }); if (!CheckReturn(ret)) return null; Dictionary<string, object> folders = (Dictionary<string, object>)ret["FOLDERS"]; List<InventoryFolderBase> fldrs = new List<InventoryFolderBase>(); try { foreach (Object o in folders.Values) fldrs.Add(BuildFolder((Dictionary<string, object>)o)); } catch (Exception e) { m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception unwrapping folder list: ", e); } return fldrs; } public InventoryFolderBase GetRootFolder(UUID principalID) { Dictionary<string,object> ret = MakeRequest("GETROOTFOLDER", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() } }); if (!CheckReturn(ret)) return null; return BuildFolder((Dictionary<string, object>)ret["folder"]); } public InventoryFolderBase GetFolderForType(UUID principalID, FolderType type) { Dictionary<string,object> ret = MakeRequest("GETFOLDERFORTYPE", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "TYPE", ((int)type).ToString() } }); if (!CheckReturn(ret)) return null; return BuildFolder((Dictionary<string, object>)ret["folder"]); } public InventoryCollection GetFolderContent(UUID principalID, UUID folderID) { InventoryCollection inventory = new InventoryCollection(); inventory.Folders = new List<InventoryFolderBase>(); inventory.Items = new List<InventoryItemBase>(); inventory.OwnerID = principalID; try { Dictionary<string,object> ret = MakeRequest("GETFOLDERCONTENT", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "FOLDER", folderID.ToString() } }); if (!CheckReturn(ret)) return null; Dictionary<string,object> folders = ret.ContainsKey("FOLDERS") ? (Dictionary<string,object>)ret["FOLDERS"] : null; Dictionary<string,object> items = ret.ContainsKey("ITEMS") ? (Dictionary<string, object>)ret["ITEMS"] : null; if (folders != null) foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o)); if (items != null) foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i inventory.Items.Add(BuildItem((Dictionary<string, object>)o)); } catch (Exception e) { m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolderContent: {0}", e.Message); } return inventory; } public virtual InventoryCollection[] GetMultipleFoldersContent(UUID principalID, UUID[] folderIDs) { InventoryCollection[] inventoryArr = new InventoryCollection[folderIDs.Length]; // m_log.DebugFormat("[XXX]: In GetMultipleFoldersContent {0}", String.Join(",", folderIDs)); try { Dictionary<string, object> resultSet = MakeRequest("GETMULTIPLEFOLDERSCONTENT", new Dictionary<string, object> { { "PRINCIPAL", principalID.ToString() }, { "FOLDERS", String.Join(",", folderIDs) }, { "COUNT", folderIDs.Length.ToString() } }); if (!CheckReturn(resultSet)) return null; int i = 0; foreach (KeyValuePair<string, object> kvp in resultSet) { InventoryCollection inventory = new InventoryCollection(); if (kvp.Key.StartsWith("F_")) { UUID fid = UUID.Zero; if (UUID.TryParse(kvp.Key.Substring(2), out fid) && fid == folderIDs[i]) { inventory.Folders = new List<InventoryFolderBase>(); inventory.Items = new List<InventoryItemBase>(); Dictionary<string, object> ret = (Dictionary<string, object>)kvp.Value; if (ret.ContainsKey("FID")) { if (!UUID.TryParse(ret["FID"].ToString(), out inventory.FolderID)) m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Could not parse folder id {0}", ret["FID"].ToString()); } else m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: FID key not present in response"); inventory.Version = -1; if (ret.ContainsKey("VERSION")) Int32.TryParse(ret["VERSION"].ToString(), out inventory.Version); if (ret.ContainsKey("OWNER")) UUID.TryParse(ret["OWNER"].ToString(), out inventory.OwnerID); //m_log.DebugFormat("[XXX]: Received {0} ({1}) {2} {3}", inventory.FolderID, fid, inventory.Version, inventory.OwnerID); Dictionary<string, object> folders = (Dictionary<string, object>)ret["FOLDERS"]; Dictionary<string, object> items = (Dictionary<string, object>)ret["ITEMS"]; foreach (Object o in folders.Values) // getting the values directly, we don't care about the keys folder_i { inventory.Folders.Add(BuildFolder((Dictionary<string, object>)o)); } foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i { inventory.Items.Add(BuildItem((Dictionary<string, object>)o)); } inventoryArr[i] = inventory; } else { m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Folder id does not match. Expected {0} got {1}", folderIDs[i], fid); m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: {0} {1}", String.Join(",", folderIDs), String.Join(",", resultSet.Keys)); } i += 1; } } } catch (Exception e) { m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetMultipleFoldersContent: {0}", e.Message); } return inventoryArr; } public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID) { Dictionary<string,object> ret = MakeRequest("GETFOLDERITEMS", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "FOLDER", folderID.ToString() } }); if (!CheckReturn(ret)) return null; Dictionary<string, object> items = (Dictionary<string, object>)ret["ITEMS"]; List<InventoryItemBase> fitems = new List<InventoryItemBase>(); foreach (Object o in items.Values) // getting the values directly, we don't care about the keys item_i fitems.Add(BuildItem((Dictionary<string, object>)o)); return fitems; } public bool AddFolder(InventoryFolderBase folder) { Dictionary<string,object> ret = MakeRequest("ADDFOLDER", new Dictionary<string,object> { { "ParentID", folder.ParentID.ToString() }, { "Type", folder.Type.ToString() }, { "Version", folder.Version.ToString() }, { "Name", folder.Name.ToString() }, { "Owner", folder.Owner.ToString() }, { "ID", folder.ID.ToString() } }); return CheckReturn(ret); } public bool UpdateFolder(InventoryFolderBase folder) { Dictionary<string,object> ret = MakeRequest("UPDATEFOLDER", new Dictionary<string,object> { { "ParentID", folder.ParentID.ToString() }, { "Type", folder.Type.ToString() }, { "Version", folder.Version.ToString() }, { "Name", folder.Name.ToString() }, { "Owner", folder.Owner.ToString() }, { "ID", folder.ID.ToString() } }); return CheckReturn(ret); } public bool MoveFolder(InventoryFolderBase folder) { Dictionary<string,object> ret = MakeRequest("MOVEFOLDER", new Dictionary<string,object> { { "ParentID", folder.ParentID.ToString() }, { "ID", folder.ID.ToString() }, { "PRINCIPAL", folder.Owner.ToString() } }); return CheckReturn(ret); } public bool DeleteFolders(UUID principalID, List<UUID> folderIDs) { List<string> slist = new List<string>(); foreach (UUID f in folderIDs) slist.Add(f.ToString()); Dictionary<string,object> ret = MakeRequest("DELETEFOLDERS", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "FOLDERS", slist } }); return CheckReturn(ret); } public bool PurgeFolder(InventoryFolderBase folder) { Dictionary<string,object> ret = MakeRequest("PURGEFOLDER", new Dictionary<string,object> { { "ID", folder.ID.ToString() } }); return CheckReturn(ret); } public bool AddItem(InventoryItemBase item) { if (item.Description == null) item.Description = String.Empty; if (item.CreatorData == null) item.CreatorData = String.Empty; if (item.CreatorId == null) item.CreatorId = String.Empty; Dictionary<string, object> ret = MakeRequest("ADDITEM", new Dictionary<string,object> { { "AssetID", item.AssetID.ToString() }, { "AssetType", item.AssetType.ToString() }, { "Name", item.Name.ToString() }, { "Owner", item.Owner.ToString() }, { "ID", item.ID.ToString() }, { "InvType", item.InvType.ToString() }, { "Folder", item.Folder.ToString() }, { "CreatorId", item.CreatorId.ToString() }, { "CreatorData", item.CreatorData.ToString() }, { "Description", item.Description.ToString() }, { "NextPermissions", item.NextPermissions.ToString() }, { "CurrentPermissions", item.CurrentPermissions.ToString() }, { "BasePermissions", item.BasePermissions.ToString() }, { "EveryOnePermissions", item.EveryOnePermissions.ToString() }, { "GroupPermissions", item.GroupPermissions.ToString() }, { "GroupID", item.GroupID.ToString() }, { "GroupOwned", item.GroupOwned.ToString() }, { "SalePrice", item.SalePrice.ToString() }, { "SaleType", item.SaleType.ToString() }, { "Flags", item.Flags.ToString() }, { "CreationDate", item.CreationDate.ToString() } }); return CheckReturn(ret); } public bool UpdateItem(InventoryItemBase item) { if (item.CreatorData == null) item.CreatorData = String.Empty; Dictionary<string,object> ret = MakeRequest("UPDATEITEM", new Dictionary<string,object> { { "AssetID", item.AssetID.ToString() }, { "AssetType", item.AssetType.ToString() }, { "Name", item.Name.ToString() }, { "Owner", item.Owner.ToString() }, { "ID", item.ID.ToString() }, { "InvType", item.InvType.ToString() }, { "Folder", item.Folder.ToString() }, { "CreatorId", item.CreatorId.ToString() }, { "CreatorData", item.CreatorData.ToString() }, { "Description", item.Description.ToString() }, { "NextPermissions", item.NextPermissions.ToString() }, { "CurrentPermissions", item.CurrentPermissions.ToString() }, { "BasePermissions", item.BasePermissions.ToString() }, { "EveryOnePermissions", item.EveryOnePermissions.ToString() }, { "GroupPermissions", item.GroupPermissions.ToString() }, { "GroupID", item.GroupID.ToString() }, { "GroupOwned", item.GroupOwned.ToString() }, { "SalePrice", item.SalePrice.ToString() }, { "SaleType", item.SaleType.ToString() }, { "Flags", item.Flags.ToString() }, { "CreationDate", item.CreationDate.ToString() } }); bool result = CheckReturn(ret); if (result) { m_ItemCache.AddOrUpdate(item.ID, item, CACHE_EXPIRATION_SECONDS); } return result; } public bool MoveItems(UUID principalID, List<InventoryItemBase> items) { List<string> idlist = new List<string>(); List<string> destlist = new List<string>(); foreach (InventoryItemBase item in items) { idlist.Add(item.ID.ToString()); destlist.Add(item.Folder.ToString()); } Dictionary<string,object> ret = MakeRequest("MOVEITEMS", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "IDLIST", idlist }, { "DESTLIST", destlist } }); return CheckReturn(ret); } public bool DeleteItems(UUID principalID, List<UUID> itemIDs) { List<string> slist = new List<string>(); foreach (UUID f in itemIDs) slist.Add(f.ToString()); Dictionary<string,object> ret = MakeRequest("DELETEITEMS", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "ITEMS", slist } }); return CheckReturn(ret); } public InventoryItemBase GetItem(UUID principalID, UUID itemID) { InventoryItemBase retrieved = null; if (m_ItemCache.TryGetValue(itemID, out retrieved)) { return retrieved; } try { Dictionary<string, object> ret = MakeRequest("GETITEM", new Dictionary<string, object> { { "ID", itemID.ToString() }, { "PRINCIPAL", principalID.ToString() } }); if (!CheckReturn(ret)) return null; retrieved = BuildItem((Dictionary<string, object>)ret["item"]); } catch (Exception e) { m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetItem: ", e); } m_ItemCache.AddOrUpdate(itemID, retrieved, CACHE_EXPIRATION_SECONDS); return retrieved; } public virtual InventoryItemBase[] GetMultipleItems(UUID principalID, UUID[] itemIDs) { //m_log.DebugFormat("[XXX]: In GetMultipleItems {0}", String.Join(",", itemIDs)); InventoryItemBase[] itemArr = new InventoryItemBase[itemIDs.Length]; // Try to get them from the cache List<UUID> pending = new List<UUID>(); InventoryItemBase item = null; int i = 0; foreach (UUID id in itemIDs) { if (m_ItemCache.TryGetValue(id, out item)) itemArr[i++] = item; else pending.Add(id); } if (pending.Count == 0) // we're done, everything was in the cache return itemArr; try { Dictionary<string, object> resultSet = MakeRequest("GETMULTIPLEITEMS", new Dictionary<string, object> { { "PRINCIPAL", principalID.ToString() }, { "ITEMS", String.Join(",", pending.ToArray()) }, { "COUNT", pending.Count.ToString() } }); if (!CheckReturn(resultSet)) { if (i == 0) return null; else return itemArr; } // carry over index i where we left above foreach (KeyValuePair<string, object> kvp in resultSet) { InventoryCollection inventory = new InventoryCollection(); if (kvp.Key.StartsWith("item_")) { if (kvp.Value is Dictionary<string, object>) { item = BuildItem((Dictionary<string, object>)kvp.Value); m_ItemCache.AddOrUpdate(item.ID, item, CACHE_EXPIRATION_SECONDS); itemArr[i++] = item; } else itemArr[i++] = null; } } } catch (Exception e) { m_log.WarnFormat("[XINVENTORY SERVICES CONNECTOR]: Exception in GetMultipleItems: {0}", e.Message); } return itemArr; } public InventoryFolderBase GetFolder(UUID principalID, UUID folderID) { try { Dictionary<string, object> ret = MakeRequest("GETFOLDER", new Dictionary<string, object> { { "ID", folderID.ToString() }, { "PRINCIPAL", principalID.ToString() } }); if (!CheckReturn(ret)) return null; return BuildFolder((Dictionary<string, object>)ret["folder"]); } catch (Exception e) { m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception in GetFolder: ", e); } return null; } public List<InventoryItemBase> GetActiveGestures(UUID principalID) { Dictionary<string,object> ret = MakeRequest("GETACTIVEGESTURES", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() } }); if (!CheckReturn(ret)) return null; List<InventoryItemBase> items = new List<InventoryItemBase>(); foreach (Object o in ((Dictionary<string,object>)ret["ITEMS"]).Values) items.Add(BuildItem((Dictionary<string, object>)o)); return items; } public int GetAssetPermissions(UUID principalID, UUID assetID) { Dictionary<string,object> ret = MakeRequest("GETASSETPERMISSIONS", new Dictionary<string,object> { { "PRINCIPAL", principalID.ToString() }, { "ASSET", assetID.ToString() } }); // We cannot use CheckReturn() here because valid values for RESULT are "false" (in the case of request failure) or an int if (ret == null) return 0; if (ret.ContainsKey("RESULT")) { if (ret["RESULT"] is string) { int intResult; if (int.TryParse ((string)ret["RESULT"], out intResult)) return intResult; } } return 0; } public bool HasInventoryForUser(UUID principalID) { return false; } // Helpers // private Dictionary<string,object> MakeRequest(string method, Dictionary<string,object> sendData) { // Add "METHOD" as the first key in the dictionary. This ensures that it will be // visible even when using partial logging ("debug http all 5"). Dictionary<string, object> temp = sendData; sendData = new Dictionary<string,object>{ { "METHOD", method } }; foreach (KeyValuePair<string, object> kvp in temp) sendData.Add(kvp.Key, kvp.Value); RequestsMade++; string reply = String.Empty; int retries = 0; do { reply = SynchronousRestFormsRequester.MakeRequest( "POST", m_ServerURI + "/xinventory", ServerUtils.BuildQueryString(sendData), m_requestTimeoutSecs, m_Auth); if (reply != String.Empty) break; retries++; } while (retries <= m_maxRetries); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse( reply); return replyData; } private InventoryFolderBase BuildFolder(Dictionary<string,object> data) { InventoryFolderBase folder = new InventoryFolderBase(); try { folder.ParentID = new UUID(data["ParentID"].ToString()); folder.Type = short.Parse(data["Type"].ToString()); folder.Version = ushort.Parse(data["Version"].ToString()); folder.Name = data["Name"].ToString(); folder.Owner = new UUID(data["Owner"].ToString()); folder.ID = new UUID(data["ID"].ToString()); } catch (Exception e) { m_log.Error("[XINVENTORY SERVICES CONNECTOR]: Exception building folder: ", e); } return folder; } private InventoryItemBase BuildItem(Dictionary<string,object> data) { InventoryItemBase item = new InventoryItemBase(); try { item.AssetID = new UUID(data["AssetID"].ToString()); item.AssetType = int.Parse(data["AssetType"].ToString()); item.Name = data["Name"].ToString(); item.Owner = new UUID(data["Owner"].ToString()); item.ID = new UUID(data["ID"].ToString()); item.InvType = int.Parse(data["InvType"].ToString()); item.Folder = new UUID(data["Folder"].ToString()); item.CreatorId = data["CreatorId"].ToString(); if (data.ContainsKey("CreatorData")) item.CreatorData = data["CreatorData"].ToString(); else item.CreatorData = String.Empty; item.Description = data["Description"].ToString(); item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); item.GroupID = new UUID(data["GroupID"].ToString()); item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); item.SalePrice = int.Parse(data["SalePrice"].ToString()); item.SaleType = byte.Parse(data["SaleType"].ToString()); item.Flags = uint.Parse(data["Flags"].ToString()); item.CreationDate = int.Parse(data["CreationDate"].ToString()); } catch (Exception e) { m_log.Error("[XINVENTORY CONNECTOR]: Exception building item: ", e); } return item; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using System.Runtime.CompilerServices; namespace NLog.UnitTests.LayoutRenderers { using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; public class CallSiteTests : NLogTestBase { [Fact] public void HiddenAssemblyTest() { const string code = @" namespace Foo { public class HiddenAssemblyLogger { public void LogDebug(NLog.Logger logger) { logger.Debug(""msg""); } } } "; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters(); // reference the NLog dll parameters.ReferencedAssemblies.Add("NLog.dll"); // the assembly should be generated in memory parameters.GenerateInMemory = true; // generate a dll instead of an executable parameters.GenerateExecutable = false; // compile code and generate assembly System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); Assert.False(results.Errors.HasErrors, "Compiler errors: " + string.Join(";", results.Errors)); // create nlog configuration LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); // create logger Logger logger = LogManager.GetLogger("A"); // load HiddenAssemblyLogger type Assembly compiledAssembly = results.CompiledAssembly; Type hiddenAssemblyLoggerType = compiledAssembly.GetType("Foo.HiddenAssemblyLogger"); Assert.NotNull(hiddenAssemblyLoggerType); // load methodinfo MethodInfo logDebugMethod = hiddenAssemblyLoggerType.GetMethod("LogDebug"); Assert.NotNull(logDebugMethod); // instantiate the HiddenAssemblyLogger from previously generated assembly object instance = Activator.CreateInstance(hiddenAssemblyLoggerType); // Add the previously generated assembly to the "blacklist" LogManager.AddHiddenAssembly(compiledAssembly); // call the log method logDebugMethod.Invoke(instance, new object[] { logger }); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LineNumberTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); #if !NET4_5 && !MONO #line 100000 #endif logger.Debug("msg"); var linenumber = GetPrevLineNumber(); string lastMessage = GetDebugLastMessage("debug"); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf("callsitetests.cs:" + linenumber, StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #if !NET4_5 && !MONO #line default #endif } [Fact] public void MethodNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } [Fact] public void MethodNameInChainTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg2"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug2", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg2"); } [Fact] public void ClassNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "ftAlignRightTest msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "htAlignRightTest msg"); } [Fact] public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg"); } [Fact] public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); Action action = () => logger.Debug("msg"); action.Invoke(); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>")); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.Contains("+<>")); } } [Fact] public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } [Fact] public void CheckStackTraceUsageForTwoRules() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules msg"); } [Fact] public void CheckStackTraceUsageForTwoRules_chained() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForTwoRules_chained msg"); } [Fact] public void CheckStackTraceUsageForMultipleRules() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${callsite} ${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug' /> <logger name='*' minlevel='Debug' writeTo='debug,debug2' /> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug2", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CheckStackTraceUsageForMultipleRules msg"); } #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } #if ASYNC_SUPPORTED [Fact] public void Show_correct_method_with_async() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async2() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod2a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod2a() { await AsyncMethod2b(); } private async Task AsyncMethod2b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async3() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod3b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod3a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod3a() { var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); AsyncMethod3b(); } private void AsyncMethod3b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } [Fact] public void CallSiteShouldWorkForAsyncMethodsWithReturnValue() { var callSite = GetAsyncCallSite().GetAwaiter().GetResult(); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.GetAsyncCallSite", callSite); } public async Task<string> GetAsyncCallSite() { Type loggerType = typeof(Logger); var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType); var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType); var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); logEvent.SetStackTrace(stacktrace, index); await Task.Delay(0); Layout l = "${callsite}"; var callSite = l.Render(logEvent); return callSite; } #endif [Fact] public void Show_correct_method_for_moveNext() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); MoveNext(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private void MoveNext() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); } [Fact] public void Should_preserve_correct_callsite_information() { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var target = new MemoryTarget(); config.AddTarget("target", target); // Step 3. Set target properties target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}"; // Step 4. Define rules var rule = new LoggingRule("*", LogLevel.Debug, target); config.LoggingRules.Add(rule); var factory = new NLogFactory(config); WriteLogMessage(factory); var logMessage = target.Logs[0]; Assert.Contains("CallSiteTests.WriteLogMessage", logMessage); } [MethodImpl(MethodImplOptions.NoInlining)] private void WriteLogMessage(NLogFactory factory) { var logger = factory.Create("MyLoggerName"); logger.Debug("something"); } /// <summary> /// /// </summary> public class NLogFactory { internal const string defaultConfigFileName = "nlog.config"; /// <summary> /// Initializes a new instance of the <see cref="NLogFactory" /> class. /// </summary> /// <param name="loggingConfiguration"> The NLog Configuration </param> public NLogFactory(LoggingConfiguration loggingConfiguration) { LogManager.Configuration = loggingConfiguration; } /// <summary> /// Creates a logger with specified <paramref name="name" />. /// </summary> /// <param name="name"> The name. </param> /// <returns> </returns> public NLogLogger Create(string name) { var log = LogManager.GetLogger(name); return new NLogLogger(log); } } /// <summary> /// If some calls got inlined, we can't find LoggerType anymore. We should fallback if loggerType can be found /// /// Example of those stacktraces: /// at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) in c:\temp\NLog\src\NLog\LoggerImpl.cs:line 68 /// at NLog.UnitTests.LayoutRenderers.NLogLogger.ErrorWithoutLoggerTypeArg(String message) in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 989 /// at NLog.UnitTests.LayoutRenderers.CallSiteTests.TestCallsiteWhileCallsGotInlined() in c:\temp\NLog\tests\NLog.UnitTests\LayoutRenderers\CallSiteTests.cs:line 893 /// /// </summary> [Fact] public void CallSiteShouldWorkEvenInlined() { Type loggerType = typeof(Logger); var stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType); var index = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType); var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1"); logEvent.SetStackTrace(stacktrace, index); Layout l = "${callsite}"; var callSite = l.Render(logEvent); Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite); } } /// <summary> /// Implementation of <see cref="ILogger" /> for NLog. /// </summary> public class NLogLogger { /// <summary> /// Initializes a new instance of the <see cref="NLogLogger" /> class. /// </summary> /// <param name="logger"> The logger. </param> public NLogLogger(Logger logger) { Logger = logger; } /// <summary> /// Gets or sets the logger. /// </summary> /// <value> The logger. </value> protected internal Logger Logger { get; set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> A <see cref="string" /> that represents this instance. </returns> public override string ToString() { return Logger.ToString(); } /// <summary> /// Logs a debug message. /// </summary> /// <param name="message"> The message to log </param> public void Debug(string message) { Log(LogLevel.Debug, message); } public void Log(LogLevel logLevel, string message) { Logger.Log(typeof(NLogLogger), new LogEventInfo(logLevel, Logger.Name, message)); } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <[email protected]> * Rudi Pettazzi <[email protected]> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; namespace Ude.Core { public abstract class HebrewModel : SequenceModel { //Model Table: //total sequences: 100% //first 512 sequences: 98.4004% //first 1024 sequences: 1.5981% //rest sequences: 0.087% //negative sequences: 0.0015% private readonly static byte[] HEBREW_LANG_MODEL = { 0,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,2,1,2,0,1,0,0, 3,0,3,1,0,0,1,3,2,0,1,1,2,0,2,2,2,1,1,1,1,2,1,1,1,2,0,0,2,2,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2, 1,2,1,2,1,2,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2, 1,2,1,3,1,1,0,0,2,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,1,2,2,1,3, 1,2,1,1,2,2,0,0,2,2,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,2,3,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,2,2,1,2,2,2,2, 1,2,1,1,2,2,0,1,2,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,2,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,2,2, 0,2,1,2,2,2,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,2,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,2,0,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,1,2,1,1,1, 0,1,1,1,1,1,3,0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0, 0,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,1,2,3,3,2,3,3,3,3,2,3,2,1,2,0,2,1,2, 0,2,0,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,1,2,2,3,3,2,3,2,3,2,2,3,1,2,2,0,2,2,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,2,2,3,3,3,3,1,3,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,2,3,2,2,2,1,2,2,0,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,1,3,2,3,3,2,3,3,2,2,1,2,2,2,2,2,2, 0,2,1,2,1,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,3,2,3,3,3,3,3,2,2,2,2,2,2,2,1, 0,2,0,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,1,2,3,3,3,3,3,3,3,2,3,2,3,2,1,2,3,0,2,1,2,2, 0,2,1,1,2,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,2,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,1,3,1,2,2,2,1,2,3,3,1,2,1,2,2,2,2, 0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,1,3,3,3,1,2,2,2,2,1,1,2,2,2,2,2,2, 0,2,0,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,1,2,3,2,3,2,2,2,2,1,2,1,1,1,2,2, 0,2,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0, 1,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,2,3,1,2,2,2,2,3,2,3,1,1,2,2,1,2,2,1,1,0,2,2,2,2, 0,1,0,1,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,2,2,1,2,2,2,2,2,2,2,1,2,2,1,2,2,1,1,1,1,1,1,1,1,2,1,1,0,3,3,3, 0,3,0,2,2,2,2,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2,2,2,1,1,1,2,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,0,0,0,0, 0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,0,2,1,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,3,1,1,2,2,2,2,2,1,2,2,2,1,1,2,2,2,2,2,2,2,1,2,2,1,0,1,1,1,1,0, 0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,1,1,1,1,2,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0, 2,1,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2,1,2,1,1,1,1,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,1,2,1,1,1,2,1,2,1,2,0,1,0,1, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,2,1,2,1,1,0,1,0,1, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,0, 0,1,1,1,2,1,2,2,2,0,2,0,2,0,1,1,2,1,1,1,1,2,1,0,1,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,0,0,1,0,1,2,2,0,1,0,0,1,1,2,2,1,2,0,2,0,0,0,1,2,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,2,1,2,0,2,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,1,2,2,0,0,1,0,0,0,1,0,0,1, 1,1,2,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,2,1, 0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,2,1,1,2,0,1,0,0,0,1,1,0,1, 1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,0,0,2,1,1,2,0,2,0,0,0,1,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,2,2,1,2,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,2,1,1,1,0,2,1,1,0,0,0,2,1,0,1, 1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,0,2,1,1,0,1,0,0,0,1,1,0,1, 2,2,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,0,1,2,1,0,2,0,0,0,1,1,0,1, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 0,1,0,0,2,0,2,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1, 1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,2,1,1,1,1,1,0,1,0,0,0,0,1,0,1, 0,1,1,1,2,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,0, }; public HebrewModel(byte[] charToOrderMap, string name) : base(charToOrderMap, HEBREW_LANG_MODEL, 0.984004f, false, name) { } } public class Win1255Model : HebrewModel { /* 255: Control characters that usually does not exist in any text 254: Carriage/Return 253: symbol (punctuation) that does not belong to word 252: 0 - 9 */ //Windows-1255 language model //Character Mapping Table: private readonly static byte[] WIN1255_CHAR_TO_ORDER_MAP = { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 +253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 69, 91, 79, 80, 92, 89, 97, 90, 68,111,112, 82, 73, 95, 85, //40 78,121, 86, 71, 67,102,107, 84,114,103,115,253,253,253,253,253, //50 253, 50, 74, 60, 61, 42, 76, 70, 64, 53,105, 93, 56, 65, 54, 49, //60 66,110, 51, 43, 44, 63, 81, 77, 98, 75,108,253,253,253,253,253, //70 124,202,203,204,205, 40, 58,206,207,208,209,210,211,212,213,214, 215, 83, 52, 47, 46, 72, 32, 94,216,113,217,109,218,219,220,221, 34,116,222,118,100,223,224,117,119,104,125,225,226, 87, 99,227, 106,122,123,228, 55,229,230,101,231,232,120,233, 48, 39, 57,234, 30, 59, 41, 88, 33, 37, 36, 31, 29, 35,235, 62, 28,236,126,237, 238, 38, 45,239,240,241,242,243,127,244,245,246,247,248,249,250, 9, 8, 20, 16, 3, 2, 24, 14, 22, 1, 25, 15, 4, 11, 6, 23, 12, 19, 13, 26, 18, 27, 21, 17, 7, 10, 5,251,252,128, 96,253, }; public Win1255Model() : base(WIN1255_CHAR_TO_ORDER_MAP, "windows-1255") { } } }
using YAF.Lucene.Net.Support; using System; using System.Diagnostics; namespace YAF.Lucene.Net.Util.Packed { /* * 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 DataInput = YAF.Lucene.Net.Store.DataInput; using IndexInput = YAF.Lucene.Net.Store.IndexInput; /// <summary> /// Reader for sequences of <see cref="long"/>s written with <see cref="BlockPackedWriter"/>. /// <para/> /// @lucene.internal /// </summary> /// <seealso cref="BlockPackedWriter"/> public sealed class BlockPackedReaderIterator { internal static long ZigZagDecode(long n) { return (((long)((ulong)n >> 1)) ^ -(n & 1)); } // same as DataInput.ReadVInt64 but supports negative values /// <summary> /// NOTE: This was readVLong() in Lucene. /// </summary> internal static long ReadVInt64(DataInput @in) { byte b = @in.ReadByte(); if ((sbyte)b >= 0) { return b; } long i = b & 0x7FL; b = @in.ReadByte(); i |= (b & 0x7FL) << 7; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 14; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 21; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 28; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 35; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 42; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 49; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0xFFL) << 56; return i; } internal DataInput @in; internal readonly int packedIntsVersion; internal long valueCount; internal readonly int blockSize; internal readonly long[] values; internal readonly Int64sRef valuesRef; internal byte[] blocks; internal int off; internal long ord; /// <summary> /// Sole constructor. </summary> /// <param name="blockSize"> The number of values of a block, must be equal to the /// block size of the <see cref="BlockPackedWriter"/> which has /// been used to write the stream. </param> public BlockPackedReaderIterator(DataInput @in, int packedIntsVersion, int blockSize, long valueCount) { PackedInt32s.CheckBlockSize(blockSize, AbstractBlockPackedWriter.MIN_BLOCK_SIZE, AbstractBlockPackedWriter.MAX_BLOCK_SIZE); this.packedIntsVersion = packedIntsVersion; this.blockSize = blockSize; this.values = new long[blockSize]; this.valuesRef = new Int64sRef(this.values, 0, 0); Reset(@in, valueCount); } /// <summary> /// Reset the current reader to wrap a stream of <paramref name="valueCount"/> /// values contained in <paramref name="in"/>. The block size remains unchanged. /// </summary> public void Reset(DataInput @in, long valueCount) { this.@in = @in; Debug.Assert(valueCount >= 0); this.valueCount = valueCount; off = blockSize; ord = 0; } /// <summary> /// Skip exactly <paramref name="count"/> values. </summary> public void Skip(long count) { Debug.Assert(count >= 0); if (ord + count > valueCount || ord + count < 0) { throw new System.IO.EndOfStreamException(); } // 1. skip buffered values int skipBuffer = (int)Math.Min(count, blockSize - off); off += skipBuffer; ord += skipBuffer; count -= skipBuffer; if (count == 0L) { return; } // 2. skip as many blocks as necessary Debug.Assert(off == blockSize); while (count >= blockSize) { int token = @in.ReadByte() & 0xFF; int bitsPerValue = (int)((uint)token >> AbstractBlockPackedWriter.BPV_SHIFT); if (bitsPerValue > 64) { throw new System.IO.IOException("Corrupted"); } if ((token & AbstractBlockPackedWriter.MIN_VALUE_EQUALS_0) == 0) { ReadVInt64(@in); } long blockBytes = PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, blockSize, bitsPerValue); SkipBytes(blockBytes); ord += blockSize; count -= blockSize; } if (count == 0L) { return; } // 3. skip last values Debug.Assert(count < blockSize); Refill(); ord += count; off += (int)count; } private void SkipBytes(long count) { if (@in is IndexInput) { IndexInput iin = (IndexInput)@in; iin.Seek(iin.GetFilePointer() + count); } else { if (blocks == null) { blocks = new byte[blockSize]; } long skipped = 0; while (skipped < count) { int toSkip = (int)Math.Min(blocks.Length, count - skipped); @in.ReadBytes(blocks, 0, toSkip); skipped += toSkip; } } } /// <summary> /// Read the next value. </summary> public long Next() { if (ord == valueCount) { throw new System.IO.EndOfStreamException(); } if (off == blockSize) { Refill(); } long value = values[off++]; ++ord; return value; } /// <summary> /// Read between <c>1</c> and <paramref name="count"/> values. </summary> public Int64sRef Next(int count) { Debug.Assert(count > 0); if (ord == valueCount) { throw new System.IO.EndOfStreamException(); } if (off == blockSize) { Refill(); } count = Math.Min(count, blockSize - off); count = (int)Math.Min(count, valueCount - ord); valuesRef.Offset = off; valuesRef.Length = count; off += count; ord += count; return valuesRef; } private void Refill() { int token = @in.ReadByte() & 0xFF; bool minEquals0 = (token & AbstractBlockPackedWriter.MIN_VALUE_EQUALS_0) != 0; int bitsPerValue = (int)((uint)token >> AbstractBlockPackedWriter.BPV_SHIFT); if (bitsPerValue > 64) { throw new System.IO.IOException("Corrupted"); } long minValue = minEquals0 ? 0L : ZigZagDecode(1L + ReadVInt64(@in)); Debug.Assert(minEquals0 || minValue != 0); if (bitsPerValue == 0) { Arrays.Fill(values, minValue); } else { PackedInt32s.IDecoder decoder = PackedInt32s.GetDecoder(PackedInt32s.Format.PACKED, packedIntsVersion, bitsPerValue); int iterations = blockSize / decoder.ByteValueCount; int blocksSize = iterations * decoder.ByteBlockCount; if (blocks == null || blocks.Length < blocksSize) { blocks = new byte[blocksSize]; } int valueCount = (int)Math.Min(this.valueCount - ord, blockSize); int blocksCount = (int)PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, valueCount, bitsPerValue); @in.ReadBytes(blocks, 0, blocksCount); decoder.Decode(blocks, 0, values, 0, iterations); if (minValue != 0) { for (int i = 0; i < valueCount; ++i) { values[i] += minValue; } } } off = 0; } /// <summary> /// Return the offset of the next value to read. </summary> public long Ord { get { return ord; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using System.Text; using Orleans.Configuration; namespace Orleans.Runtime.MembershipService { internal class MembershipOracleData { private readonly Dictionary<SiloAddress, MembershipEntry> localTable; // all silos not including current silo private Dictionary<SiloAddress, SiloStatus> localTableCopy; // a cached copy of a local table, including current silo, for fast access private Dictionary<SiloAddress, SiloStatus> localTableCopyOnlyActive; // a cached copy of a local table, for fast access, including only active nodes and current silo (if active) private Dictionary<SiloAddress, string> localNamesTableCopy; // a cached copy of a map from SiloAddress to Silo Name, not including current silo, for fast access private List<SiloAddress> localMultiClusterGatewaysCopy; // a cached copy of the silos that are designated gateways private readonly List<ISiloStatusListener> statusListeners; private readonly ILogger logger; private IntValueStatistic clusterSizeStatistic; private StringValueStatistic clusterStatistic; internal readonly DateTime SiloStartTime; internal readonly SiloAddress MyAddress; internal readonly int MyProxyPort; internal readonly string MyHostname; internal SiloStatus CurrentStatus { get; private set; } // current status of this silo. internal string SiloName { get; } // name of this silo. private readonly bool multiClusterActive; // set by configuration if multicluster is active private readonly int maxMultiClusterGateways; // set by configuration private UpdateFaultCombo myFaultAndUpdateZones; internal MembershipOracleData(ILocalSiloDetails siloDetails, ILogger log, MultiClusterOptions multiClusterOptions) { logger = log; localTable = new Dictionary<SiloAddress, MembershipEntry>(); localTableCopy = new Dictionary<SiloAddress, SiloStatus>(); localTableCopyOnlyActive = new Dictionary<SiloAddress, SiloStatus>(); localNamesTableCopy = new Dictionary<SiloAddress, string>(); localMultiClusterGatewaysCopy = new List<SiloAddress>(); statusListeners = new List<ISiloStatusListener>(); SiloStartTime = DateTime.UtcNow; MyAddress = siloDetails.SiloAddress; MyHostname = siloDetails.DnsHostName; MyProxyPort = siloDetails.GatewayAddress?.Endpoint?.Port ?? 0; SiloName = siloDetails.Name; this.multiClusterActive = multiClusterOptions.HasMultiClusterNetwork; this.maxMultiClusterGateways = multiClusterOptions.MaxMultiClusterGateways; CurrentStatus = SiloStatus.Created; clusterSizeStatistic = IntValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER_SIZE, () => localTableCopyOnlyActive.Count); clusterStatistic = StringValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER, () => { List<string> list = localTableCopyOnlyActive.Keys.Select(addr => addr.ToLongString()).ToList(); list.Sort(); return Utils.EnumerableToString(list); }); } // ONLY access localTableCopy and not the localTable, to prevent races, as this method may be called outside the turn. internal SiloStatus GetApproximateSiloStatus(SiloAddress siloAddress) { var status = SiloStatus.None; if (siloAddress.Equals(MyAddress)) { status = CurrentStatus; } else { if (!localTableCopy.TryGetValue(siloAddress, out status)) { if (CurrentStatus == SiloStatus.Active) if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100209, "-The given siloAddress {0} is not registered in this MembershipOracle.", siloAddress.ToLongString()); status = SiloStatus.None; } } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateSiloStatus returned {0} for silo: {1}", status, siloAddress.ToLongString()); return status; } // ONLY access localTableCopy or localTableCopyOnlyActive and not the localTable, to prevent races, as this method may be called outside the turn. internal Dictionary<SiloAddress, SiloStatus> GetApproximateSiloStatuses(bool onlyActive = false) { Dictionary<SiloAddress, SiloStatus> dict = onlyActive ? localTableCopyOnlyActive : localTableCopy; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateSiloStatuses returned {0} silos: {1}", dict.Count, Utils.DictionaryToString(dict)); return dict; } internal List<SiloAddress> GetApproximateMultiClusterGateways() { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-GetApproximateMultiClusterGateways returned {0} silos: {1}", localMultiClusterGatewaysCopy.Count, string.Join(",", localMultiClusterGatewaysCopy)); return localMultiClusterGatewaysCopy; } internal bool TryGetSiloName(SiloAddress siloAddress, out string siloName) { if (siloAddress.Equals(MyAddress)) { siloName = SiloName; return true; } return localNamesTableCopy.TryGetValue(siloAddress, out siloName); } internal bool SubscribeToSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } internal bool UnSubscribeFromSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } internal void UpdateMyStatusLocal(SiloStatus status) { if (CurrentStatus == status) return; // make copies var tmpLocalTableCopy = GetSiloStatuses(st => true, true); // all the silos including me. var tmpLocalTableCopyOnlyActive = GetSiloStatuses(st => st == SiloStatus.Active, true); // only active silos including me. var tmpLocalTableNamesCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me. CurrentStatus = status; tmpLocalTableCopy[MyAddress] = status; if (status == SiloStatus.Active) { tmpLocalTableCopyOnlyActive[MyAddress] = status; } else if (tmpLocalTableCopyOnlyActive.ContainsKey(MyAddress)) { tmpLocalTableCopyOnlyActive.Remove(MyAddress); } localTableCopy = tmpLocalTableCopy; localTableCopyOnlyActive = tmpLocalTableCopyOnlyActive; localNamesTableCopy = tmpLocalTableNamesCopy; if (this.multiClusterActive) localMultiClusterGatewaysCopy = DetermineMultiClusterGateways(); NotifyLocalSubscribers(MyAddress, CurrentStatus); } private SiloStatus GetSiloStatus(SiloAddress siloAddress) { if (siloAddress.Equals(MyAddress)) return CurrentStatus; MembershipEntry data; return !localTable.TryGetValue(siloAddress, out data) ? SiloStatus.None : data.Status; } internal MembershipEntry GetSiloEntry(SiloAddress siloAddress) { return localTable[siloAddress]; } internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself) { Dictionary<SiloAddress, SiloStatus> dict = localTable.Where( pair => filter(pair.Value.Status)).ToDictionary(pair => pair.Key, pair => pair.Value.Status); if (includeMyself && filter(CurrentStatus)) // add myself dict.Add(MyAddress, CurrentStatus); return dict; } internal MembershipEntry CreateNewMembershipEntry(SiloStatus myStatus) { return CreateNewMembershipEntry(SiloName, MyAddress, MyProxyPort, MyHostname, myStatus, SiloStartTime); } private static MembershipEntry CreateNewMembershipEntry(string siloName, SiloAddress myAddress, int proxyPort, string myHostname, SiloStatus myStatus, DateTime startTime) { var assy = Assembly.GetEntryAssembly() ?? typeof(MembershipOracleData).Assembly; var roleName = assy.GetName().Name; var entry = new MembershipEntry { SiloAddress = myAddress, HostName = myHostname, SiloName = siloName, Status = myStatus, ProxyPort = proxyPort, RoleName = roleName, SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(), StartTime = startTime, IAmAliveTime = DateTime.UtcNow }; return entry; } internal void UpdateMyFaultAndUpdateZone(MembershipEntry entry) { this.myFaultAndUpdateZones = new UpdateFaultCombo(entry.UpdateZone, entry.FaultZone); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"-Updated my FaultZone={entry.FaultZone} UpdateZone={entry.UpdateZone}"); if (this.multiClusterActive) localMultiClusterGatewaysCopy = DetermineMultiClusterGateways(); } internal bool TryUpdateStatusAndNotify(MembershipEntry entry) { if (!TryUpdateStatus(entry)) return false; localTableCopy = GetSiloStatuses(status => true, true); // all the silos including me. localTableCopyOnlyActive = GetSiloStatuses(status => status == SiloStatus.Active, true); // only active silos including me. localNamesTableCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.SiloName); // all the silos excluding me. if (this.multiClusterActive) localMultiClusterGatewaysCopy = DetermineMultiClusterGateways(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("-Updated my local view of {0} status. It is now {1}.", entry.SiloAddress.ToLongString(), GetSiloStatus(entry.SiloAddress)); NotifyLocalSubscribers(entry.SiloAddress, entry.Status); return true; } // return true if the status changed private bool TryUpdateStatus(MembershipEntry updatedSilo) { MembershipEntry currSiloData = null; if (!localTable.TryGetValue(updatedSilo.SiloAddress, out currSiloData)) { // an optimization - if I learn about dead silo and I never knew about him before, I don't care, can just ignore him. if (updatedSilo.Status == SiloStatus.Dead) return false; localTable.Add(updatedSilo.SiloAddress, updatedSilo); return true; } if (currSiloData.Status == updatedSilo.Status) return false; currSiloData.Update(updatedSilo); return true; } private void NotifyLocalSubscribers(SiloAddress siloAddress, SiloStatus newStatus) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("-NotifyLocalSubscribers about {0} status {1}", siloAddress.ToLongString(), newStatus); List<ISiloStatusListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (ISiloStatusListener listener in copy) { try { listener.SiloStatusChangeNotification(siloAddress, newStatus); } catch (Exception exc) { logger.Error(ErrorCode.MembershipLocalSubscriberException, String.Format("Local ISiloStatusListener {0} has thrown an exception when was notified about SiloStatusChangeNotification about silo {1} new status {2}", listener.GetType().FullName, siloAddress.ToLongString(), newStatus), exc); } } } // deterministic function for designating the silos that should act as multi-cluster gateways private List<SiloAddress> DetermineMultiClusterGateways() { // function should never be called if we are not in a multicluster if (! this.multiClusterActive) throw new OrleansException("internal error: should not call this function without multicluster network"); List<SiloAddress> result; // take all the active silos if their count does not exceed the desired number of gateways if (localTableCopyOnlyActive.Count <= this.maxMultiClusterGateways) { result = localTableCopyOnlyActive.Keys.ToList(); } else { result = DeterministicBalancedChoice<SiloAddress, UpdateFaultCombo>( localTableCopyOnlyActive.Keys, this.maxMultiClusterGateways, (SiloAddress a) => a.Equals(MyAddress) ? this.myFaultAndUpdateZones : new UpdateFaultCombo(localTable[a]), logger); } if (logger.IsEnabled(LogLevel.Debug)) { var gateways = string.Join(", ", result.Select(silo => silo.ToString())); logger.Debug($"-DetermineMultiClusterGateways {gateways}"); } return result; } // pick a specified number of elements from a set of candidates // - in a balanced way (try to pick evenly from groups) // - in a deterministic way (using sorting order on candidates and keys) internal static List<T> DeterministicBalancedChoice<T, K>(IEnumerable<T> candidates, int count, Func<T, K> group, ILogger logger = null) where T:IComparable where K:IComparable { // organize candidates by groups var groups = new Dictionary<K, List<T>>(); var keys = new List<K>(); int numcandidates = 0; foreach (var c in candidates) { var key = group(c); List<T> list; if (!groups.TryGetValue(key, out list)) { groups[key] = list = new List<T>(); keys.Add(key); } list.Add(c); numcandidates++; } if (numcandidates < count) throw new ArgumentException("not enough candidates"); // sort the keys and the groups to guarantee deterministic result keys.Sort(); foreach(var kvp in groups) kvp.Value.Sort(); // for debugging, trace all the gateway candidates if (logger != null && logger.IsEnabled(LogLevel.Trace)) { var b = new StringBuilder(); foreach (var k in keys) { b.Append(k); b.Append(':'); foreach (var s in groups[k]) { b.Append(' '); b.Append(s); } } logger.Trace($"-DeterministicBalancedChoice candidates {b}"); } // pick round-robin from groups var result = new List<T>(); for (int i = 0; result.Count < count; i++) { var list = groups[keys[i % keys.Count]]; var col = i / keys.Count; if (col < list.Count) result.Add(list[col]); } return result; } internal struct UpdateFaultCombo : IComparable { public readonly int UpdateZone; public readonly int FaultZone; public UpdateFaultCombo(int updateZone, int faultZone) { UpdateZone = updateZone; FaultZone = faultZone; } public UpdateFaultCombo(MembershipEntry e) { UpdateZone = e.UpdateZone; FaultZone = e.FaultZone; } public int CompareTo(object x) { var other = (UpdateFaultCombo)x; int comp = UpdateZone.CompareTo(other.UpdateZone); if (comp != 0) return comp; return FaultZone.CompareTo(other.FaultZone); } public override string ToString() { return $"({UpdateZone},{FaultZone})"; } } public override string ToString() { return string.Format("CurrentSiloStatus = {0}, {1} silos: {2}.", CurrentStatus, localTableCopy.Count, Utils.EnumerableToString(localTableCopy, pair => String.Format("SiloAddress={0} Status={1}", pair.Key.ToLongString(), pair.Value))); } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using Apache.Http; using Apache.Http.Auth; using Apache.Http.Client; using Apache.Http.Client.Methods; using Apache.Http.Client.Protocol; using Apache.Http.Conn; using Apache.Http.Entity; using Apache.Http.Impl.Auth; using Apache.Http.Impl.Client; using Apache.Http.Protocol; using Couchbase.Lite; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Support { public class RemoteRequest : Runnable { protected internal ScheduledExecutorService workExecutor; protected internal readonly HttpClientFactory clientFactory; protected internal string method; protected internal Uri url; protected internal object body; protected internal RemoteRequestCompletionBlock onCompletion; protected internal IDictionary<string, object> requestHeaders; public RemoteRequest(ScheduledExecutorService workExecutor, HttpClientFactory clientFactory , string method, Uri url, object body, IDictionary<string, object> requestHeaders , RemoteRequestCompletionBlock onCompletion) { this.clientFactory = clientFactory; this.method = method; this.url = url; this.body = body; this.onCompletion = onCompletion; this.workExecutor = workExecutor; this.requestHeaders = requestHeaders; } public virtual void Run() { HttpClient httpClient = clientFactory.GetHttpClient(); ClientConnectionManager manager = httpClient.GetConnectionManager(); HttpRequestMessage request = CreateConcreteRequest(); PreemptivelySetAuthCredentials(httpClient); request.AddHeader("Accept", "multipart/related, application/json"); AddRequestHeaders(request); SetBody(request); ExecuteRequest(httpClient, request); } protected internal virtual void AddRequestHeaders(HttpRequestMessage request) { foreach (string requestHeaderKey in requestHeaders.Keys) { request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString ()); } } protected internal virtual HttpRequestMessage CreateConcreteRequest() { HttpRequestMessage request = null; if (Sharpen.Runtime.EqualsIgnoreCase(method, "GET")) { request = new HttpGet(url.ToExternalForm()); } else { if (Sharpen.Runtime.EqualsIgnoreCase(method, "PUT")) { request = new HttpPut(url.ToExternalForm()); } else { if (Sharpen.Runtime.EqualsIgnoreCase(method, "POST")) { request = new HttpPost(url.ToExternalForm()); } } } return request; } private void SetBody(HttpRequestMessage request) { // set body if appropriate if (body != null && request is HttpEntityEnclosingRequestBase) { byte[] bodyBytes = null; try { bodyBytes = Manager.GetObjectMapper().WriteValueAsBytes(body); } catch (Exception e) { Log.E(Database.Tag, "Error serializing body of request", e); } ByteArrayEntity entity = new ByteArrayEntity(bodyBytes); entity.SetContentType("application/json"); ((HttpEntityEnclosingRequestBase)request).SetEntity(entity); } } protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request) { object fullBody = null; Exception error = null; try { HttpResponse response = httpClient.Execute(request); // add in cookies to global store try { if (httpClient is DefaultHttpClient) { DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient; CouchbaseLiteHttpClientFactory.Instance.AddCookies(defaultHttpClient.GetCookieStore ().GetCookies()); } } catch (Exception e) { Log.E(Database.Tag, "Unable to add in cookies to global store", e); } StatusLine status = response.GetStatusLine(); if (status.GetStatusCode() >= 300) { Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode ())); Log.E(Database.Tag, "Request was for: " + request.ToString()); Log.E(Database.Tag, "Status reason: " + status.GetReasonPhrase()); error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase( )); } else { HttpEntity temp = response.GetEntity(); if (temp != null) { InputStream stream = null; try { stream = temp.GetContent(); fullBody = Manager.GetObjectMapper().ReadValue<object>(stream); } finally { try { stream.Close(); } catch (IOException) { } } } } } catch (ClientProtocolException e) { Log.E(Database.Tag, "client protocol exception", e); error = e; } catch (IOException e) { Log.E(Database.Tag, "io exception", e); error = e; } RespondWithResult(fullBody, error); } protected internal virtual void PreemptivelySetAuthCredentials(HttpClient httpClient ) { // if the URL contains user info AND if this a DefaultHttpClient // then preemptively set the auth credentials if (url.GetUserInfo() != null) { if (url.GetUserInfo().Contains(":") && !url.GetUserInfo().Trim().Equals(":")) { string[] userInfoSplit = url.GetUserInfo().Split(":"); Credentials creds = new UsernamePasswordCredentials(URIUtils.Decode(userInfoSplit [0]), URIUtils.Decode(userInfoSplit[1])); if (httpClient is DefaultHttpClient) { DefaultHttpClient dhc = (DefaultHttpClient)httpClient; MessageProcessingHandler preemptiveAuth = new _MessageProcessingHandler_185(creds ); dhc.AddRequestInterceptor(preemptiveAuth, 0); } } else { Log.W(Database.Tag, "RemoteRequest Unable to parse user info, not setting credentials" ); } } } private sealed class _MessageProcessingHandler_185 : MessageProcessingHandler { public _MessageProcessingHandler_185(Credentials creds) { this.creds = creds; } /// <exception cref="Apache.Http.HttpException"></exception> /// <exception cref="System.IO.IOException"></exception> public void Process(HttpWebRequest request, HttpContext context) { AuthState authState = (AuthState)context.GetAttribute(ClientContext.TargetAuthState ); CredentialsProvider credsProvider = (CredentialsProvider)context.GetAttribute(ClientContext .CredsProvider); HttpHost targetHost = (HttpHost)context.GetAttribute(ExecutionContext.HttpTargetHost ); if (authState.GetAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.GetHostName(), targetHost.GetPort( )); authState.SetAuthScheme(new BasicScheme()); authState.SetCredentials(creds); } } private readonly Credentials creds; } public virtual void RespondWithResult(object result, Exception error) { if (workExecutor != null) { workExecutor.Submit(new _Runnable_219(this, result, error)); } else { // don't let this crash the thread Log.E(Database.Tag, "work executor was null!!!"); } } private sealed class _Runnable_219 : Runnable { public _Runnable_219(RemoteRequest _enclosing, object result, Exception error) { this._enclosing = _enclosing; this.result = result; this.error = error; } public void Run() { try { this._enclosing.onCompletion.OnCompletion(result, error); } catch (Exception e) { Log.E(Database.Tag, "RemoteRequestCompletionBlock throw Exception", e); } } private readonly RemoteRequest _enclosing; private readonly object result; private readonly Exception error; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param012.param012 { // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(23,23\).*CS0649</Expects> public struct myStruct { public int Field; } public class Foo { public void Method(params int[] x) { } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; try { f.Method(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.Method(params int[])")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param014.param014 { // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct myStruct { public int Field; } public class Foo { public void Method(params int[] x) { } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; dynamic d2 = 3; try { f.Method(d2, d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.Method(params int[])")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param022.param022 { // <Title>Make sure that the cache is not blown away by the rules the binder generates</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success><Expects> // <Code> using System; public class A { public Action Baz { get; set; } } public class C { public void Baz() { Program.Status = 1; } } public class D<T> { public T Baz; } public struct E { public dynamic Baz; } public class F : I { public void Baz() { System.Console.WriteLine("E.Baz"); Program.Status = 1; } public Action Bar { get; set; } public dynamic Foo { get; set; } } public interface I { void Baz(); Action Bar { get; set; } dynamic Foo { get; set; } } public class Program { public static int Status = 0; private static void CallBaz(dynamic x) { x.Baz(); } private static void CallBar(dynamic x) { x.Bar(); } private static void CallFoo(dynamic x) { x.Foo(); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var a = new C(); var b = new { Baz = new Action(() => Program.Status = 1) } ; var d = new D<Func<int>>() { Baz = new Func<int>(() => Program.Status = 1) } ; var e = new E() { Baz = new Action(() => Program.Status = 1) } ; var x = new { Baz = (Action)delegate { Program.Status = 1; } } ; var f = new F(); int rez = 0; int tests = 0; tests++; Program.Status = 0; x.Baz(); rez += Program.Status; f.Bar = f.Baz; f.Foo = (Action)f.Baz; I i = f; tests++; Program.Status = 0; CallBar(i); rez += Program.Status; tests++; Program.Status = 0; CallFoo(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(d); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(e); rez += Program.Status; tests++; Program.Status = 0; CallBaz(d); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.nullable001.nullable001 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new Test(); int? x = 5; int rez = d.M(x) == 1 ? 0 : 1; //we pass in the compile time type x = null; rez += d.M(x) == 1 ? 0 : 1; //we pass in the compile time type x = 5; dynamic dyn = x; rez += d.M(dyn) == 2 ? 0 : 1; //we boxed the int -> runtime type is int x = null; dyn = x; rez += d.M(dyn) == 1 ? 0 : 1; //we are passing in null -> the only overload is the nullable one return rez > 0 ? 1 : 0; } public int M(int? x) { return 1; } public int M(int x) { return 2; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr001.regr001 { // <Title>Overload resolution of methods involving pointer types</Title> // <Description> // Method overload resolution with dynamic argument resolving to array parameter with the corresponding pointer type as the parameter for the other method // </Description> //<Expects Status=warning>\(19,9\).*CS0169</Expects> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //using System; //enum color { Red, Blue, Green }; //public struct S //{ //int i; //} //class Program //{ //unsafe public static int Test1(char* c) //{ //return 1; //} //public static int Test1(char[] c) //{ //return 0; //} //unsafe public static int Test2(int* c) //{ //return 1; //} //public static int Test2(int[] c) //{ //return 0; //} //unsafe public static int Test3(byte* c) //{ //return 1; //} //public static int Test3(byte[] c) //{ //return 0; //} //unsafe public static int Test4(sbyte* c) //{ //return 1; //} //public static int Test4(sbyte[] c) //{ //return 0; //} //unsafe public static int Test5(short* c) //{ //return 1; //} //public static int Test5(short[] c) //{ //return 0; //} //unsafe public static int Test6(ushort* c) //{ //return 1; //} //public static int Test6(ushort[] c) //{ //return 0; //} //unsafe public static int Test7(uint* c) //{ //return 1; //} //public static int Test7(uint[] c) //{ //return 0; //} //unsafe public static int Test8(long* c) //{ //return 1; //} //public static int Test8(long[] c) //{ //return 0; //} //unsafe public static int Test9(ulong* c) //{ //return 1; //} //public static int Test9(ulong[] c) //{ //return 0; //} //unsafe public static int Test10(float* c) //{ //return 1; //} //public static int Test10(float[] c) //{ //return 0; //} //unsafe public static int Test11(double* c) //{ //return 1; //} //public static int Test11(double[] c) //{ //return 0; //} //unsafe public static int Test12(decimal* c) //{ //return 1; //} //public static int Test12(decimal[] c) //{ //return 0; //} //unsafe public static int Test13(bool* c) //{ //return 1; //} //public static int Test13(bool[] c) //{ //return 0; //} //unsafe public static int Test14(color* c) //{ //return 1; //} //public static int Test14(color[] c) //{ //return 0; //} //unsafe public static int Test15(S* c) //{ //return 1; //} //public static int Test15(S[] c) //{ //return 0; //} //[Test][Priority(Priority.Priority2)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static int MainMethod() //{ //dynamic c1 = "Testing".ToCharArray(); //if (Test1(c1) == 1) return 1; //dynamic c2 = new int[] { 4, 5, 6 }; //if (Test2(c2) == 1) return 1; //dynamic c3 = new byte[] { 4, 5, 6 }; //if (Test3(c3) == 1) return 1; //dynamic c4 = new sbyte[] { 4, 5, 6 }; //if (Test4(c4) == 1) return 1; //dynamic c5 = new short[] { 4, 5, 6 }; //if (Test5(c5) == 1) return 1; //dynamic c6 = new ushort[] { 4, 5, 6 }; //if (Test6(c6) == 1) return 1; //dynamic c7 = new uint[] { 4, 5, 6 }; //if (Test7(c7) == 1) return 1; //dynamic c8 = new long[] { 4, 5, 6 }; //if (Test8(c8) == 1) return 1; //dynamic c9 = new ulong[] { 4, 5, 6 }; //if (Test9(c9) == 1) return 1; //dynamic c10 = new float[] { 4.5f, 5.6f, 6.7f }; //if (Test10(c10) == 1) return 1; //dynamic c11 = new double[] { 4.5d, 5.4d, 6.9d }; //if (Test11(c11) == 1) return 1; //dynamic c12 = new decimal[] { 4.5m, 5.3m, 6.8m }; //if (Test12(c12) == 1) return 1; //dynamic c13 = new bool[] { true }; //if (Test13(c13) == 1) return 1; //dynamic c14 = new color[] { }; //if (Test14(c14) == 1) return 1; //dynamic c15 = new S[] { }; //if (Test15(c15) == 1) return 1; //return 0; //} //} // </Code> } #if CAP_PointerType namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr002.regr002 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr002.regr002; // <Title>Overload resolution of methods involving pointer types</Title> // <Description> // Method overload resolution with dynamic argument resolving to array parameter with the corresponding pointer type as the parameter for the other method // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Program { [Test] [Priority(Priority.Priority2)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); } public static int MainMethod() { var c = "abc".ToCharArray(); var a = new string(c); var b = new string((dynamic)c); return 0; } } // </Code> } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XmlDiff; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; namespace XLinqTests { public class SaveWithWriter : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+SaveWithWriter // Test Case #region Constants private const string BaseSaveFileName = "baseSave.xml"; private const string TestSaveFileName = "testSave"; private const string xml = "<PurchaseOrder><Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item></PurchaseOrder>"; private const string xmlForXElementWriteContent = "<Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item>"; #endregion #region Fields private readonly XmlDiff _diff; #endregion #region Constructors and Destructors public SaveWithWriter() { _diff = new XmlDiff(); } #endregion #region Public Methods and Operators public static string[] GetExpectedXml() { string[] xml = { "text", "", " ", "<!--comment1 comment1 -->", "<!---->", "<!-- -->", "<?pi1 pi1 pi1 ?>", "<?pi1?>", "<?pi1 ?>", "<![CDATA[cdata cdata ]]>", "<![CDATA[]]>", "<![CDATA[ ]]>", "<elem attr=\"val\">text<!--comm--><?pi hffgg?><![CDATA[jfggr]]></elem>" }; return xml; } public static object[] GetObjects() { object[] objects = { new XText("text"), new XText(""), new XText(" "), new XComment("comment1 comment1 "), new XComment(""), new XComment(" "), new XProcessingInstruction("pi1", "pi1 pi1 "), new XProcessingInstruction("pi1", ""), new XProcessingInstruction("pi1", " "), new XCData("cdata cdata "), new XCData(""), new XCData(" "), new XElement("elem", new XAttribute("attr", "val"), new XText("text"), new XComment("comm"), new XProcessingInstruction("pi", "hffgg"), new XCData("jfggr")) }; return objects; } public override void AddChildren() { AddChild(new TestVariation(writer_5) { Attribute = new VariationAttribute("Write and valIdate XDocumentType") { Priority = 0 } }); AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("WriteTo after WriteState = Error") { Param = "WriteTo", Priority = 2 } }); AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("Save after WriteState = Error") { Param = "Save", Priority = 2 } }); AddChild(new TestVariation(writer_20) { Attribute = new VariationAttribute("XDocument: Null parameters for Save") { Priority = 1 } }); AddChild(new TestVariation(writer_21) { Attribute = new VariationAttribute("XElement: Null parameters for Save") { Priority = 1 } }); AddChild(new TestVariation(writer_23) { Attribute = new VariationAttribute("XDocument: Null parameters for WriteTo") { Priority = 1 } }); AddChild(new TestVariation(writer_24) { Attribute = new VariationAttribute("XElement: Null parameters for WriteTo") { Priority = 1 } }); } public Encoding[] GetEncodings() { Encoding[] encodings = { Encoding.UTF8 //Encoding.Unicode, //Encoding.BigEndianUnicode, }; return encodings; } //[Variation(Priority = 2, Desc = "Save after WriteState = Error", Param = "Save")] //[Variation(Priority = 2, Desc = "WriteTo after WriteState = Error", Param = "WriteTo")] public void writer_18() { var doc = new XDocument(); foreach (Encoding encoding in GetEncodings()) { foreach (XmlWriter w in GetXmlWriters(encoding)) { try { if (Variation.Param.ToString() == "Save") { doc.Save(w); } else { doc.WriteTo(w); } throw new TestException(TestResult.Failed, ""); } catch (Exception ex) { if (!(ex is InvalidOperationException) && !(ex is ArgumentException)) { throw; } TestLog.Equals(w.WriteState, WriteState.Error, "Error in WriteState"); try { if (Variation.Param.ToString() == "Save") { doc.Save(w); } else { doc.WriteTo(w); } throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } finally { w.Dispose(); } } } } //[Variation(Priority = 1, Desc = "XDocument: Null parameters for Save")] public void writer_20() { var doc = new XDocument(new XElement("PurchaseOrder")); //save with TextWriter try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //save with XmlWriter try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } } //[Variation(Priority = 1, Desc = "XElement: Null parameters for Save")] public void writer_21() { var doc = new XElement(new XElement("PurchaseOrder")); //save with TextWriter try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } //save with XmlWriter try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 1, Desc = "XDocument: Null parameters for WriteTo")] public void writer_23() { var doc = new XDocument(new XElement("PurchaseOrder")); try { doc.WriteTo(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 1, Desc = "XElement: Null parameters for WriteTo")] public void writer_24() { var doc = new XElement(new XElement("PurchaseOrder")); try { doc.WriteTo(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 0, Desc = "Write and valIdate XDocumentType")] public void writer_5() { string expectedXml = "<!DOCTYPE root PUBLIC \"\" \"\"[<!ELEMENT root ANY>]>"; var doc = new XDocumentType("root", "", "", "<!ELEMENT root ANY>"); TestToStringAndXml(doc, expectedXml); var ws = new XmlWriterSettings(); ws.ConformanceLevel = ConformanceLevel.Document; ws.OmitXmlDeclaration = true; // Set to true when FileIO is ok ws.CloseOutput = false; // Use a file to replace this when FileIO is ok var m = new MemoryStream(); using (XmlWriter wr = XmlWriter.Create(m, ws)) { doc.WriteTo(wr); } m.Position = 0; using (TextReader r = new StreamReader(m)) { string actualXml = r.ReadToEnd(); TestLog.Compare(expectedXml, actualXml, "XDocumentType writeTo method failed"); } } #endregion // // helpers // #region Methods private string GenerateTestFileName(int index) { string filename = String.Format("{0}{1}.xml", TestSaveFileName, index); try { FilePathUtil.getStream(filename); } catch (Exception) { FilePathUtil.addStream(filename, new MemoryStream()); } return filename; } private List<XmlWriter> GetXmlWriters(Encoding encoding) { return GetXmlWriters(encoding, ConformanceLevel.Document); } private List<XmlWriter> GetXmlWriters(Encoding encoding, ConformanceLevel conformanceLevel) { var xmlWriters = new List<XmlWriter>(); int count = 0; var s = new XmlWriterSettings(); s.CheckCharacters = true; s.Encoding = encoding; var ws = new XmlWriterSettings(); ws.CheckCharacters = false; // Set it to true when FileIO is ok ws.CloseOutput = false; ws.Encoding = encoding; s.ConformanceLevel = conformanceLevel; ws.ConformanceLevel = conformanceLevel; TextWriter tw = new StreamWriter(FilePathUtil.getStream(GenerateTestFileName(count++))); xmlWriters.Add(new CoreXml.Test.XLinq.CustomWriter(tw, ws)); // CustomWriter xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), s)); // Factory XmlWriter xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), ws)); // Factory Writer return xmlWriters; } private void SaveBaseline(string xml) { var ms = new MemoryStream(); var sw = new StreamWriter(ms); sw.Write(xml); sw.Flush(); FilePathUtil.addStream(BaseSaveFileName, ms); } private void SaveWithFile(Object doc) { string file0 = GenerateTestFileName(0); string file1 = GenerateTestFileName(1); string file2 = GenerateTestFileName(2); foreach (Encoding encoding in GetEncodings()) { if (doc is XDocument) { ((XDocument)doc).Save(FilePathUtil.getStream(file0)); ((XDocument)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting); ((XDocument)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None); } else if (doc is XElement) { ((XElement)doc).Save(FilePathUtil.getStream(file0)); ((XElement)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting); ((XElement)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "Save failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "Save(preserveWhitespace true) failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "Save(preserveWhitespace false) " + encoding); } } private void SaveWithTextWriter(Object doc) { string file0 = GenerateTestFileName(0); string file1 = GenerateTestFileName(1); string file2 = GenerateTestFileName(2); foreach (Encoding encoding in GetEncodings()) { using (TextWriter w0 = new StreamWriter(FilePathUtil.getStream(file0))) using (TextWriter w1 = new StreamWriter(FilePathUtil.getStream(file1))) using (TextWriter w2 = new StreamWriter(FilePathUtil.getStream(file2))) { if (doc is XDocument) { ((XDocument)doc).Save(w0); ((XDocument)doc).Save(w1, SaveOptions.DisableFormatting); ((XDocument)doc).Save(w2, SaveOptions.None); } else if (doc is XElement) { ((XElement)doc).Save(w0); ((XElement)doc).Save(w1, SaveOptions.DisableFormatting); ((XElement)doc).Save(w2, SaveOptions.None); } else { TestLog.Compare(false, "Wrong object"); } w0.Dispose(); w1.Dispose(); w2.Dispose(); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "TextWriter failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "TextWriter(preserveWhtsp=true) failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "TextWriter(preserveWhtsp=false) failed:encoding " + encoding); } } } private void SaveWithXmlWriter(Object doc) { foreach (Encoding encoding in GetEncodings()) { List<XmlWriter> xmlWriters = GetXmlWriters(encoding); try { for (int i = 0; i < xmlWriters.Count; ++i) { if (doc is XDocument) { ((XDocument)doc).Save(xmlWriters[i]); } else if (doc is XElement) { ((XElement)doc).Save(xmlWriters[i]); } else { TestLog.Compare(false, "Wrong object"); } xmlWriters[i].Dispose(); if (doc is XDocument) { ((XDocument)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i))); } else if (doc is XElement) { ((XElement)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i))); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Skip("ReEnable this when FileIO is OK"); } } finally { for (int i = 0; i < xmlWriters.Count; ++i) { xmlWriters[i].Dispose(); } } } } private void TestToStringAndXml(Object doc, string expectedXml) { string toString = doc.ToString(); string xml = String.Empty; if (doc is XDocument) { xml = ((XDocument)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XElement) { xml = ((XElement)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XText) { xml = ((XText)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XCData) { xml = ((XCData)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XComment) { xml = ((XComment)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XProcessingInstruction) { xml = ((XProcessingInstruction)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XDocumentType) { xml = ((XDocumentType)doc).ToString(SaveOptions.DisableFormatting); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Compare(toString, expectedXml, "Test ToString failed"); TestLog.Compare(xml, expectedXml, "Test .ToString(SaveOptions.DisableFormatting) failed"); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.POIFS.Common; using NPOI.POIFS.Dev; using NPOI.POIFS.Properties; using NPOI.Util; using System.IO; using System.Collections.Generic; using System; using System.Text; using System.Collections; using NPOI.POIFS.EventFileSystem; namespace NPOI.POIFS.FileSystem { /** * This class manages a document in the NIO POIFS filesystem. * This is the {@link NPOIFSFileSystem} version. */ public class NPOIFSDocument : POIFSViewable { private DocumentProperty _property; private NPOIFSFileSystem _filesystem; private NPOIFSStream _stream; private int _block_size; /** * Constructor for an existing Document */ public NPOIFSDocument(DocumentNode document) : this((DocumentProperty)document.Property, ((DirectoryNode)document.Parent).NFileSystem) { } /** * Constructor for an existing Document */ public NPOIFSDocument(DocumentProperty property, NPOIFSFileSystem filesystem) { this._property = property; this._filesystem = filesystem; if (property.Size < POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE) { _stream = new NPOIFSStream(_filesystem.GetMiniStore(), property.StartBlock); _block_size = _filesystem.GetMiniStore().GetBlockStoreBlockSize(); } else { _stream = new NPOIFSStream(_filesystem, property.StartBlock); _block_size = _filesystem.GetBlockStoreBlockSize(); } } /** * Constructor for a new Document * * @param name the name of the POIFSDocument * @param stream the InputStream we read data from */ public NPOIFSDocument(String name, NPOIFSFileSystem filesystem, Stream stream) { this._filesystem = filesystem; // sotre it int length = Store(stream); // Build the property for it this._property = new DocumentProperty(name, length); _property.StartBlock = _stream.GetStartBlock(); } private int Store(Stream inStream) { int bigBlockSize = POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE; //BufferedStream bis = new BufferedStream(stream, bigBlockSize + 1); //bis.mark(bigBlockSize); //// Buffer the contents into memory. This is a bit icky... //// TODO Replace with a buffer up to the mini stream size, then streaming write //byte[] contents; //if (stream is MemoryStream) //{ // MemoryStream bais = (MemoryStream)stream; // contents = new byte[bais.Length]; // bais.Read(contents, 0, contents.Length); //} //else //{ // MemoryStream baos = new MemoryStream(); // IOUtils.Copy(stream, baos); // contents = baos.ToArray(); //} // Do we need to store as a mini stream or a full one? if (inStream.Length < bigBlockSize) { _stream = new NPOIFSStream(_filesystem.GetMiniStore()); _block_size = _filesystem.GetMiniStore().GetBlockStoreBlockSize(); } else { _stream = new NPOIFSStream(_filesystem); _block_size = _filesystem.GetBlockStoreBlockSize(); } // start from the beginning //bis.Seek(0, SeekOrigin.Begin); // Store it Stream outStream = _stream.GetOutputStream(); byte[] buf = new byte[1024]; int length = 0; //for (int readBytes; (readBytes = bis.Read(buf, 0, buf.Length)) != 0; length += readBytes) //{ // outStream.Write(buf, 0, readBytes); //} for (int readBytes = 0; ; ) { readBytes = inStream.Read(buf, 0, buf.Length); if (readBytes <= 0) break; length += readBytes; outStream.Write(buf, 0, readBytes); } // Pad to the end of the block with -1s int usedInBlock = length % _block_size; if (usedInBlock != 0 && usedInBlock != _block_size) { int toBlockEnd = _block_size - usedInBlock; byte[] padding = new byte[toBlockEnd]; Arrays.Fill(padding, (byte)0xFF); outStream.Write(padding, 0, padding.Length); } // Tidy and return the length outStream.Close(); return length; } public NPOIFSDocument(String name, int size, NPOIFSFileSystem filesystem, POIFSWriterListener Writer) { this._filesystem = filesystem; if (size < POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE) { _stream = new NPOIFSStream(filesystem.GetMiniStore()); _block_size = _filesystem.GetMiniStore().GetBlockStoreBlockSize(); } else { _stream = new NPOIFSStream(filesystem); _block_size = _filesystem.GetBlockStoreBlockSize(); } Stream innerOs = _stream.GetOutputStream(); DocumentOutputStream os = new DocumentOutputStream(innerOs, size); POIFSDocumentPath path = new POIFSDocumentPath(name.Split(new string[] { "\\\\" }, StringSplitOptions.RemoveEmptyEntries)); String docName = path.GetComponent(path.Length - 1); POIFSWriterEvent event1 = new POIFSWriterEvent(os, path, docName, size); Writer.ProcessPOIFSWriterEvent(event1); innerOs.Close(); // And build the property for it this._property = new DocumentProperty(name, size); _property.StartBlock = (/*setter*/_stream.GetStartBlock()); } /** * Frees the underlying stream and property */ internal void Free() { _stream.Free(); _property.StartBlock = (POIFSConstants.END_OF_CHAIN); } internal NPOIFSFileSystem FileSystem { get { return _filesystem; } } public int GetDocumentBlockSize() { return _block_size; } public IEnumerator<ByteBuffer> GetBlockIterator() { if (Size > 0) { return _stream.GetBlockIterator(); } else { //List<byte[]> empty = Collections.emptyList(); List<ByteBuffer> empty = new List<ByteBuffer>(); return empty.GetEnumerator(); } } /** * @return size of the document */ public int Size { get { return _property.Size; } } public void ReplaceContents(Stream stream) { Free(); int size = Store(stream); _property.StartBlock = (_stream.GetStartBlock()); _property.UpdateSize(size); } /** * @return the instance's DocumentProperty */ public DocumentProperty DocumentProperty { get { return _property; } } /** * Get an array of objects, some of which may implement POIFSViewable * * @return an array of Object; may not be null, but may be empty */ protected Object[] GetViewableArray() { String result = "<NO DATA>"; if (Size > 0) { // Get all the data into a single array byte[] data = new byte[Size]; int offset = 0; foreach (ByteBuffer buffer in _stream) { int length = Math.Min(_block_size, data.Length - offset); buffer.Read(data, offset, length); offset += length; } result = HexDump.Dump(data, 0, 0); } return new String[] { result }; } /** * Get an Iterator of objects, some of which may implement POIFSViewable * * @return an Iterator; may not be null, but may have an empty back end * store */ protected IEnumerator GetViewableIterator() { // return Collections.EMPTY_LIST.iterator(); return null; } /** * Provides a short description of the object, to be used when a * POIFSViewable object has not provided its contents. * * @return short description */ protected String GetShortDescription() { StringBuilder buffer = new StringBuilder(); buffer.Append("Document: \"").Append(_property.Name).Append("\""); buffer.Append(" size = ").Append(Size); return buffer.ToString(); } #region POIFSViewable Members public bool PreferArray { get { return true; } } public string ShortDescription { get { return GetShortDescription(); } } public Array ViewableArray { get { return GetViewableArray(); } } public IEnumerator ViewableIterator { get { return GetViewableIterator(); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class HasManyConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => SpecificationExtensions.ShouldEqual(x.Access, "field")); } [Test] public void BatchSizeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.BatchSize(10)); Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cache.ReadOnly()); Convention(x => x.Cache.ReadWrite()); VerifyModel(x => x.Cache.Usage.ShouldEqual("read-only")); } [Test] public void CascadeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cascade.All()); Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("all")); } [Test] public void CheckConstraintShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Check("constraint = 1")); Convention(x => x.Check("constraint = 0")); VerifyModel(x => x.Check.ShouldEqual("constraint = 1")); } [Test] public void CollectionTypeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.CollectionType<int>()); Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(int))); } [Test] public void FetchShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Fetch.Join()); Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("join")); } [Test] public void GenericShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Generic()); Convention(x => x.Not.Generic()); VerifyModel(x => x.Generic.ShouldBeTrue()); } [Test] public void InverseShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Inverse()); Convention(x => x.Not.Inverse()); VerifyModel(x => x.Inverse.ShouldBeTrue()); } [Test] public void KeyColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.KeyColumn("name")); Convention(x => x.Key.Column("xxx")); VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("name")); } [Test] public void ElementColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Element("name")); Convention(x => x.Element.Column("xxx")); VerifyModel(x => x.Element.Columns.First().Name.ShouldEqual("name")); } [Test] public void ElementTypeShouldntBeOverwrittenUsingGeneric() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type<int>()); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ElementTypeShouldntBeOverwrittenUsingTypeOf() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type(typeof(int))); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ElementTypeShouldntBeOverwrittenUsingString() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type(typeof(int).AssemblyQualifiedName)); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.Children, x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void OptimisticLockShouldntBeOverwritten() { Mapping(x => x.Children, x => x.OptimisticLock()); Convention(x => x.Not.OptimisticLock()); VerifyModel(x => x.OptimisticLock.ShouldEqual(true)); } [Test] public void PersisterShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Persister<CustomPersister>()); Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void SchemaShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Schema("dbo")); Convention(x => x.Schema("test")); VerifyModel(x => x.Schema.ShouldEqual("dbo")); } [Test] public void WhereShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Where("x = 1")); Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("x = 1")); } [Test] public void ForeignKeyShouldntBeOverwritten() { Mapping(x => x.Children, x => x.ForeignKeyConstraintName("key")); Convention(x => x.Key.ForeignKey("xxx")); VerifyModel(x => x.Key.ForeignKey.ShouldEqual("key")); } [Test] public void PropertyRefShouldntBeOverwritten() { Mapping(x => x.Children, x => x.PropertyRef("ref")); Convention(x => x.Key.PropertyRef("xxx")); VerifyModel(x => x.Key.PropertyRef.ShouldEqual("ref")); } [Test] public void TableNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Table("table")); Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("table")); } [Test] public void NotFoundShouldntBeOverwritten() { Mapping(x => x.Children, x => x.NotFound.Exception()); Convention(x => x.Relationship.NotFound.Ignore()); VerifyModel(x => x.Relationship.NotFound.ShouldEqual("exception")); } #region Helpers private void Convention(Action<IOneToManyCollectionInstance> convention) { model.Conventions.Add(new OneToManyCollectionConventionBuilder().Always(convention)); } private void Mapping<TChild>(Expression<Func<ExampleInheritedClass, IEnumerable<TChild>>> property, Action<OneToManyPart<TChild>> mappingDefinition) { var classMap = new ClassMap<ExampleInheritedClass>(); classMap.Id(x => x.Id); var map = classMap.HasMany(property); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleInheritedClass); } private void VerifyModel(Action<CollectionMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .Collections.First(); modelVerification(modelInstance); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class TotalClassifierTests : AbstractCSharpClassifierTests { internal override async Task<IEnumerable<ClassifiedSpan>> GetClassificationSpansAsync( string code, TextSpan textSpan, CSharpParseOptions options) { using (var workspace = TestWorkspace.CreateCSharp(code, options)) { var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var syntaxTree = await document.GetSyntaxTreeAsync(); var service = document.GetLanguageService<IClassificationService>(); var classifiers = service.GetDefaultSyntaxClassifiers(); var extensionManager = workspace.Services.GetService<IExtensionManager>(); var semanticClassifications = new List<ClassifiedSpan>(); var syntacticClassifications = new List<ClassifiedSpan>(); await service.AddSemanticClassificationsAsync(document, textSpan, extensionManager.CreateNodeExtensionGetter(classifiers, c => c.SyntaxNodeTypes), extensionManager.CreateTokenExtensionGetter(classifiers, c => c.SyntaxTokenKinds), semanticClassifications, CancellationToken.None); service.AddSyntacticClassifications(syntaxTree, textSpan, syntacticClassifications, CancellationToken.None); var classificationsSpans = new HashSet<TextSpan>(); // Add all the semantic classifications in. var allClassifications = new List<ClassifiedSpan>(semanticClassifications); classificationsSpans.AddRange(allClassifications.Select(t => t.TextSpan)); // Add the syntactic classifications. But only if they don't conflict with a semantic // classification. allClassifications.AddRange( from t in syntacticClassifications where !classificationsSpans.Contains(t.TextSpan) select t); return allClassifications; } } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForNamespace() { await TestAsync( @"using var = System;", Keyword("using"), Identifier("var"), Operators.Equals, Identifier("System"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification), WorkItem(547068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547068")] public async Task Bug17819() { await TestAsync( @"_ _() { } ///<param name='_ }", Identifier("_"), Identifier("_"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("param"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("name"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("'"), Identifier("_"), Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForClass() { await TestAsync( @"using var = System.Math;", Keyword("using"), Class("var"), Operators.Equals, Identifier("System"), Operators.Dot, Class("Math"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForDelegate() { await TestAsync( @"using var = System.Action;", Keyword("using"), Delegate("var"), Operators.Equals, Identifier("System"), Operators.Dot, Delegate("Action"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForStruct() { await TestAsync( @"using var = System.DateTime;", Keyword("using"), Struct("var"), Operators.Equals, Identifier("System"), Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForEnum() { await TestAsync( @"using var = System.DayOfWeek;", Keyword("using"), Enum("var"), Operators.Equals, Identifier("System"), Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsUsingAliasForInterface() { await TestAsync( @"using var = System.IDisposable;", Keyword("using"), Interface("var"), Operators.Equals, Identifier("System"), Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task VarAsConstructorName() { await TestAsync( @"class var { var() { } }", Keyword("class"), Class("var"), Punctuation.OpenCurly, Identifier("var"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task UsingAliasGlobalNamespace() { await TestAsync( @"using IO = global::System.IO;", Keyword("using"), Identifier("IO"), Operators.Equals, Keyword("global"), Operators.Text("::"), Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task PartialDynamicWhere() { var code = @"partial class partial<where> where where : partial<where> { static dynamic dynamic<partial>() { return dynamic<dynamic>(); } } "; await TestAsync(code, Keyword("partial"), Keyword("class"), Class("partial"), Punctuation.OpenAngle, TypeParameter("where"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("where"), Punctuation.Colon, Class("partial"), Punctuation.OpenAngle, TypeParameter("where"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("static"), Keyword("dynamic"), Identifier("dynamic"), Punctuation.OpenAngle, TypeParameter("partial"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("return"), Identifier("dynamic"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] public async Task VarInForeach() { await TestInMethodAsync(@"foreach (var v in args) { }", Keyword("foreach"), Punctuation.OpenParen, Keyword("var"), Identifier("v"), Keyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task ValueInSetterAndAnonymousTypePropertyName() { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Identifier("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Identifier("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestValueInEvent() { await TestInClassAsync( @"event int Bar { add { this.value = value; } remove { this.value = value; } }", Keyword("event"), Keyword("int"), Identifier("Bar"), Punctuation.OpenCurly, Keyword("add"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("remove"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestValueInProperty() { await TestInClassAsync( @"int Foo { get { this.value = value; } set { this.value = value; } }", Keyword("int"), Identifier("Foo"), Punctuation.OpenCurly, Keyword("get"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task ValueFieldInSetterAccessedThroughThis() { await TestInClassAsync( @"int P { set { this.value = value; } }", Keyword("int"), Identifier("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("this"), Operators.Dot, Identifier("value"), Operators.Equals, Keyword("value"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task NewOfInterface() { await TestInMethodAsync( @"object o = new System.IDisposable();", Keyword("object"), Identifier("o"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Interface("IDisposable"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [WorkItem(545611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545611")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarConstructor() { await TestAsync( @"class var { void Main() { new var(); } }", Keyword("class"), Class("var"), Punctuation.OpenCurly, Keyword("void"), Identifier("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("new"), Class("var"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(545609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545609")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarTypeParameter() { await TestAsync( @"class X { void Foo<var>() { var x; } }", Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Identifier("Foo"), Punctuation.OpenAngle, TypeParameter("var"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, TypeParameter("var"), Identifier("x"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(545610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarAttribute1() { await TestAsync( @"using System; [var] class var : Attribute { }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Punctuation.OpenBracket, Class("var"), Punctuation.CloseBracket, Keyword("class"), Class("var"), Punctuation.Colon, Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(545610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545610")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestVarAttribute2() { await TestAsync( @"using System; [var] class varAttribute : Attribute { }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Punctuation.OpenBracket, Class("var"), Punctuation.CloseBracket, Keyword("class"), Class("varAttribute"), Punctuation.Colon, Class("Attribute"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(546170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546170")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestStandaloneTypeName() { await TestAsync( @"using System; class C { static void Main() { var tree = Console } }", Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Identifier("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Identifier("tree"), Operators.Equals, Class("Console"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(546403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546403")] [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task TestNamespaceClassAmbiguities() { await TestAsync( @"class C { } namespace C { }", Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("namespace"), Identifier("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task NameAttributeValue() { await TestAsync( @"class Program<T> { /// <param name=""x""/> void Foo(int x) { } }", Keyword("class"), Class("Program"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("param"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("name"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("x"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("void"), Identifier("Foo"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task Cref1() { await TestAsync( @"/// <see cref=""Program{T}""/> class Program<T> { void Foo() { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Class("Program"), Punctuation.OpenCurly, TypeParameter("T"), Punctuation.CloseCurly, XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Program"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("void"), Identifier("Foo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task CrefNamespaceIsNotClass() { await TestAsync( @"/// <see cref=""N""/> namespace N { class Program { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("N"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("namespace"), Identifier("N"), Punctuation.OpenCurly, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Fact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task InterfacePropertyWithSameNameShouldBePreferredToType() { await TestAsync( @"interface IFoo { int IFoo { get; set; } void Bar(int x = IFoo); }", Keyword("interface"), Interface("IFoo"), Punctuation.OpenCurly, Keyword("int"), Identifier("IFoo"), Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Operators.Equals, Identifier("IFoo"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [WorkItem(633, "https://github.com/dotnet/roslyn/issues/633")] [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public async Task XmlDocCref() { await TestAsync( @"/// <summary> /// <see cref=""MyClass.MyClass(int)""/> /// </summary> class MyClass { public MyClass(int x) { } }", XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Class("MyClass"), Operators.Dot, Identifier("MyClass"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("MyClass"), Punctuation.OpenCurly, Keyword("public"), Identifier("MyClass"), Punctuation.OpenParen, Keyword("int"), Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly ); } } }
// 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.Security.Principal; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP will send default credentials based on manifest settings")] [PlatformSpecific(TestPlatforms.Windows)] public abstract class DefaultCredentialsTest : HttpClientHandlerTestBase { private static bool DomainJoinedTestsEnabled => !string.IsNullOrEmpty(Configuration.Http.DomainJoinedHttpHost); private static bool DomainProxyTestsEnabled => !string.IsNullOrEmpty(Configuration.Http.DomainJoinedProxyHost); // Enable this to test against local HttpListener over loopback // Note this doesn't work as expected with WinHttpHandler, because WinHttpHandler will always authenticate the // current user against a loopback server using NTLM or Negotiate. private static bool LocalHttpListenerTestsEnabled = false; public static bool ServerAuthenticationTestsEnabled => (LocalHttpListenerTestsEnabled || DomainJoinedTestsEnabled); private static string s_specificUserName = Configuration.Security.ActiveDirectoryUserName; private static string s_specificPassword = Configuration.Security.ActiveDirectoryUserPassword; private static string s_specificDomain = Configuration.Security.ActiveDirectoryName; private readonly NetworkCredential _specificCredential = new NetworkCredential(s_specificUserName, s_specificPassword, s_specificDomain); private static Uri s_authenticatedServer = DomainJoinedTestsEnabled ? new Uri($"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/negotiate/showidentity.ashx") : null; private readonly ITestOutputHelper _output; public DefaultCredentialsTest(ITestOutputHelper output) { _output = output; } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_DefaultValue_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_SetFalse_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_SetTrue_ConnectAsCurrentIdentity(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = true; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task Credentials_SetToWrappedDefaultCredential_ConnectAsCurrentIdentity(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.Credentials = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task Credentials_SetToBadCredential_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.Credentials = new NetworkCredential("notarealuser", "123456"); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task Credentials_SetToSpecificCredential_ConnectAsSpecificIdentity(bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; handler.Credentials = _specificCredential; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); VerifyAuthentication(responseBody, true, s_specificDomain + "\\" + s_specificUserName); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithNoCredentials_ProxyAuthenticationRequired() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(null); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithDefaultCredentials_OK() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(CredentialCache.DefaultCredentials); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithWrappedDefaultCredentials_OK() { ICredentials wrappedCreds = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(wrappedCreds); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } public static IEnumerable<object[]> AuthenticatedServers() { // Note that localhost will not actually use the proxy, but there's no harm in testing it. foreach (bool b in new bool[] { true, false }) { if (LocalHttpListenerTestsEnabled) { yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NtlmOnly.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NegotiateOnly.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NegotiateAndNtlm.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.BasicAndNtlm.Uri, b }; } if (!string.IsNullOrEmpty(Configuration.Http.DomainJoinedHttpHost)) { yield return new object[] { $"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/negotiate/showidentity.ashx", b }; yield return new object[] { $"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/multipleschemes/showidentity.ashx", b }; } } } private void VerifyAuthentication(string response, bool authenticated, string user) { // Convert all strings to lowercase to compare. Windows treats domain and username as case-insensitive. response = response.ToLower(); user = user.ToLower(); _output.WriteLine(response); if (!authenticated) { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "false"), "authenticated == false"); } else { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "true"), "authenticated == true"); Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "user", user), $"user == {user}"); } } private class CredentialWrapper : ICredentials { public ICredentials InnerCredentials { get; set; } public NetworkCredential GetCredential(Uri uri, string authType) => InnerCredentials?.GetCredential(uri, authType); } private class AuthenticatedProxy : IWebProxy { ICredentials _credentials; Uri _proxyUri; public AuthenticatedProxy(ICredentials credentials) { _credentials = credentials; string host = Configuration.Http.DomainJoinedProxyHost; Assert.False(string.IsNullOrEmpty(host), "DomainJoinedProxyHost must specify proxy hostname"); string portString = Configuration.Http.DomainJoinedProxyPort; Assert.False(string.IsNullOrEmpty(portString), "DomainJoinedProxyPort must specify proxy port number"); int port; Assert.True(int.TryParse(portString, out port), "DomainJoinedProxyPort must be a valid port number"); _proxyUri = new Uri(string.Format("http://{0}:{1}", host, port)); } public ICredentials Credentials { get { return _credentials; } set { throw new NotImplementedException(); } } public Uri GetProxy(Uri destination) { return _proxyUri; } public bool IsBypassed(Uri host) { return false; } } private sealed class HttpListenerAuthenticatedLoopbackServer { private readonly HttpListener _listener; private readonly string _uri; public static readonly HttpListenerAuthenticatedLoopbackServer NtlmOnly = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8080/", AuthenticationSchemes.Ntlm); public static readonly HttpListenerAuthenticatedLoopbackServer NegotiateOnly = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8081/", AuthenticationSchemes.Negotiate); public static readonly HttpListenerAuthenticatedLoopbackServer NegotiateAndNtlm = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8082/", AuthenticationSchemes.Negotiate | AuthenticationSchemes.Ntlm); public static readonly HttpListenerAuthenticatedLoopbackServer BasicAndNtlm = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8083/", AuthenticationSchemes.Basic | AuthenticationSchemes.Ntlm); // Don't construct directly, use instances above private HttpListenerAuthenticatedLoopbackServer(string uri, AuthenticationSchemes authenticationSchemes) { _uri = uri; _listener = new HttpListener(); _listener.Prefixes.Add(uri); _listener.AuthenticationSchemes = authenticationSchemes; _listener.Start(); Task.Run(() => ProcessRequests()); } public string Uri => _uri; private async void ProcessRequests() { while (true) { var context = await _listener.GetContextAsync(); // Send a response in the JSON format that the client expects string username = context.User.Identity.Name; await context.Response.OutputStream.WriteAsync(System.Text.Encoding.UTF8.GetBytes($"{{\"authenticated\": \"true\", \"user\": \"{username}\" }}")); context.Response.Close(); } } } } }
using AdventureGrainInterfaces; using Orleans; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdventureGrains { public class PlayerGrain : Orleans.Grain, IPlayerGrain { IRoomGrain roomGrain; // Current room List<Thing> things = new List<Thing>(); // Things that the player is carrying bool killed = false; PlayerInfo myInfo; public override Task OnActivateAsync() { this.myInfo = new PlayerInfo { Key = this.GetPrimaryKey(), Name = "nobody" }; return base.OnActivateAsync(); } Task<string> IPlayerGrain.Name() { return Task.FromResult(myInfo.Name); } Task<IRoomGrain> IPlayerGrain.RoomGrain() { return Task.FromResult(roomGrain); } async Task IPlayerGrain.Die() { // Drop everything var tasks = new List<Task<string>>(); foreach (var thing in new List<Thing>(things)) { tasks.Add(this.Drop(thing)); } await Task.WhenAll(tasks); // Exit the game if (this.roomGrain != null) { await this.roomGrain.Exit(myInfo); this.roomGrain = null; killed = true; } } async Task<string> Drop(Thing thing) { if ( killed ) return await CheckAlive(); if (thing != null) { this.things.Remove(thing); await this.roomGrain.Drop(thing); return "Okay."; } else return "I don't understand."; } async Task<string> Take(Thing thing) { if (killed) return await CheckAlive(); if (thing != null) { this.things.Add(thing); await this.roomGrain.Take(thing); return "Okay."; } else return "I don't understand."; } Task IPlayerGrain.SetName(string name) { this.myInfo.Name = name; return TaskDone.Done; } Task IPlayerGrain.SetRoomGrain(IRoomGrain room) { this.roomGrain = room; return room.Enter(myInfo); } async Task<string> Go(string direction) { IRoomGrain destination = await this.roomGrain.ExitTo(direction); StringBuilder description = new StringBuilder(); if (destination != null) { await this.roomGrain.Exit(myInfo); await destination.Enter(myInfo); this.roomGrain = destination; var desc = await destination.Description(myInfo); if (desc != null) description.Append(desc); } else { description.Append("You cannot go in that direction."); } if (things.Count > 0) { description.AppendLine("You are holding the following items:"); foreach (var thing in things) { description.AppendLine(thing.Name); } } return description.ToString(); } async Task<string> CheckAlive() { if (!killed) return null; // Go to room '-2', which is the place of no return. var room = GrainFactory.GetGrain<IRoomGrain>(-2); return await room.Description(myInfo); } async Task<string> Kill(string target) { if (things.Count == 0) return "With what? Your bare hands?"; var player = await this.roomGrain.FindPlayer(target); if (player != null) { var weapon = things.Where(t => t.Category == "weapon").FirstOrDefault(); if (weapon != null) { await GrainFactory.GetGrain<IPlayerGrain>(player.Key).Die(); return target + " is now dead."; } return "With what? Your bare hands?"; } var monster = await this.roomGrain.FindMonster(target); if (monster != null) { var weapons = monster.KilledBy.Join(things, id => id, t => t.Id, (id, t) => t); if (weapons.Count() > 0) { await GrainFactory.GetGrain<IMonsterGrain>(monster.Id).Kill(this.roomGrain); return target + " is now dead."; } return "With what? Your bare hands?"; } return "I can't see " + target + " here. Are you sure?"; } private string RemoveStopWords(string s) { string[] stopwords = new string[] { " on ", " the ", " a " }; StringBuilder sb = new StringBuilder(s); foreach (string word in stopwords) { sb.Replace(word, " "); } return sb.ToString(); } private Thing FindMyThing(string name) { return things.Where(x => x.Name == name).FirstOrDefault(); } private string Rest(string[] words) { StringBuilder sb = new StringBuilder(); for (int i = 1; i < words.Length; i++) sb.Append(words[i] + " "); return sb.ToString().Trim().ToLower(); } async Task<string> IPlayerGrain.Play(string command) { Thing thing; command = RemoveStopWords(command); string[] words = command.Split(' '); string verb = words[0].ToLower(); if (killed && verb != "end") return await CheckAlive(); switch (verb) { case "look": return await this.roomGrain.Description(myInfo); case "go": if (words.Length == 1) return "Go where?"; return await Go(words[1]); case "north": case "south": case "east": case "west": return await Go(verb); case "kill": if (words.Length == 1) return "Kill what?"; var target = command.Substring(verb.Length + 1); return await Kill(target); case "drop": thing = FindMyThing(Rest(words)); return await Drop(thing); case "take": thing = await roomGrain.FindThing(Rest(words)); return await Take(thing); case "inv": case "inventory": return "You are carrying: " + string.Join(" ", things.Select(x => x.Name)); case "end": return ""; } return "I don't understand."; } } }
// NpgsqlPromotableSinglePhaseNotification.cs // // Author: // Josh Cooley <[email protected]> // // Copyright (C) 2007, The Npgsql Development Team // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.Reflection; using System.Transactions; namespace Revenj.DatabasePersistence.Postgres.Npgsql { internal class NpgsqlPromotableSinglePhaseNotification : IPromotableSinglePhaseNotification { private readonly NpgsqlConnection _connection; private IsolationLevel _isolationLevel; private NpgsqlTransaction _npgsqlTx; private NpgsqlTransactionCallbacks _callbacks; private INpgsqlResourceManager _rm; private bool _inTransaction; public NpgsqlPromotableSinglePhaseNotification(NpgsqlConnection connection) { _connection = connection; } public void Enlist(Transaction tx) { if (tx != null) { _isolationLevel = tx.IsolationLevel; if (!tx.EnlistPromotableSinglePhase(this)) { // must already have a durable resource // start transaction _npgsqlTx = _connection.BeginTransaction(ConvertIsolationLevel(_isolationLevel)); _inTransaction = true; _rm = CreateResourceManager(); _callbacks = new NpgsqlTransactionCallbacks(_connection); _rm.Enlist(_callbacks, TransactionInterop.GetTransmitterPropagationToken(tx)); // enlisted in distributed transaction // disconnect and cleanup local transaction _npgsqlTx.Cancel(); _npgsqlTx.Dispose(); _npgsqlTx = null; } } } /// <summary> /// Used when a connection is closed /// </summary> public void Prepare() { if (_inTransaction) { // may not be null if Promote or Enlist is called first if (_callbacks == null) { _callbacks = new NpgsqlTransactionCallbacks(_connection); } _callbacks.PrepareTransaction(); if (_npgsqlTx != null) { // cancel the NpgsqlTransaction since this will // be handled by a two phase commit. _npgsqlTx.Cancel(); _npgsqlTx.Dispose(); _npgsqlTx = null; } } } #region IPromotableSinglePhaseNotification Members public void Initialize() { _npgsqlTx = _connection.BeginTransaction(ConvertIsolationLevel(_isolationLevel)); _inTransaction = true; } public void Rollback(SinglePhaseEnlistment singlePhaseEnlistment) { // try to rollback the transaction with either the // ADO.NET transaction or the callbacks that managed the // two phase commit transaction. if (_npgsqlTx != null) { _npgsqlTx.Rollback(); _npgsqlTx.Dispose(); _npgsqlTx = null; singlePhaseEnlistment.Aborted(); } else if (_callbacks != null) { if (_rm != null) { _rm.RollbackWork(_callbacks.GetName()); singlePhaseEnlistment.Aborted(); } else { _callbacks.RollbackTransaction(); singlePhaseEnlistment.Aborted(); } _callbacks = null; } _inTransaction = false; } public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { if (_npgsqlTx != null) { _npgsqlTx.Commit(); _npgsqlTx.Dispose(); _npgsqlTx = null; singlePhaseEnlistment.Committed(); } else if (_callbacks != null) { if (_rm != null) { _rm.CommitWork(_callbacks.GetName()); singlePhaseEnlistment.Committed(); } else { _callbacks.CommitTransaction(); singlePhaseEnlistment.Committed(); } _callbacks = null; } _inTransaction = false; } #endregion #region ITransactionPromoter Members public byte[] Promote() { _rm = CreateResourceManager(); // may not be null if Prepare or Enlist is called first if (_callbacks == null) { _callbacks = new NpgsqlTransactionCallbacks(_connection); } byte[] token = _rm.Promote(_callbacks); // mostly likely case for this is the transaction has been prepared. if (_npgsqlTx != null) { // cancel the NpgsqlTransaction since this will // be handled by a two phase commit. _npgsqlTx.Cancel(); _npgsqlTx.Dispose(); _npgsqlTx = null; } return token; } #endregion private static INpgsqlResourceManager _resourceManager; private static System.Runtime.Remoting.Lifetime.ClientSponsor _sponser; private static INpgsqlResourceManager CreateResourceManager() { // TODO: create network proxy for resource manager if (_resourceManager == null) { _sponser = new System.Runtime.Remoting.Lifetime.ClientSponsor(); AppDomain rmDomain = AppDomain.CreateDomain("NpgsqlResourceManager", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation); _resourceManager = (INpgsqlResourceManager) rmDomain.CreateInstanceAndUnwrap(typeof(NpgsqlResourceManager).Assembly.FullName, typeof(NpgsqlResourceManager).FullName); _sponser.Register((MarshalByRefObject)_resourceManager); } return _resourceManager; } private static System.Data.IsolationLevel ConvertIsolationLevel(IsolationLevel _isolationLevel) { switch (_isolationLevel) { case IsolationLevel.Chaos: return System.Data.IsolationLevel.Chaos; case IsolationLevel.ReadCommitted: return System.Data.IsolationLevel.ReadCommitted; case IsolationLevel.ReadUncommitted: return System.Data.IsolationLevel.ReadUncommitted; case IsolationLevel.RepeatableRead: return System.Data.IsolationLevel.RepeatableRead; case IsolationLevel.Serializable: return System.Data.IsolationLevel.Serializable; case IsolationLevel.Snapshot: return System.Data.IsolationLevel.Snapshot; case IsolationLevel.Unspecified: default: return System.Data.IsolationLevel.Unspecified; } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using MessageTemplates; /// <summary> /// Dictionary that combines the standard <see cref="LogEventInfo.Properties" /> with the /// MessageTemplate-properties extracted from the <see cref="LogEventInfo.Message" />. /// /// The <see cref="MessageProperties" /> are returned as the first items /// in the collection, and in positional order. /// </summary> [DebuggerDisplay("Count = {Count}")] internal sealed class PropertiesDictionary : IDictionary<object, object>, IEnumerable<MessageTemplateParameter> { private struct PropertyValue { /// <summary> /// Value of the property /// </summary> public readonly object Value; /// <summary> /// Is this a property of the message? /// </summary> public readonly bool IsMessageProperty; /// <summary> /// /// </summary> /// <param name="value">Value of the property</param> /// <param name="isMessageProperty">Is this a property of the message?</param> public PropertyValue(object value, bool isMessageProperty) { Value = value; IsMessageProperty = isMessageProperty; } } /// <summary> /// The properties of the logEvent /// </summary> private Dictionary<object, PropertyValue> _eventProperties; /// <summary> /// The properties extracted from the message /// </summary> private IList<MessageTemplateParameter> _messageProperties; private DictionaryCollection _keyCollection; private DictionaryCollection _valueCollection; private IDictionary _eventContextAdapter; /// <summary> /// Wraps the list of message-template-parameters into the IDictionary-interface /// </summary> /// <param name="messageParameters">Message-template-parameters</param> public PropertiesDictionary(IList<MessageTemplateParameter> messageParameters = null) { if (messageParameters?.Count > 0) { MessageProperties = messageParameters; } } #if !NET3_5 && !NET4_0 && !SILVERLIGHT /// <summary> /// Transforms the list of event-properties into IDictionary-interface /// </summary> /// <param name="eventProperties">Message-template-parameters</param> public PropertiesDictionary(IReadOnlyList<KeyValuePair<object, object>> eventProperties) { var propertyCount = eventProperties.Count; if (propertyCount > 0) { _eventProperties = new Dictionary<object, PropertyValue>(propertyCount); for (int i = 0; i < propertyCount; ++i) { var property = eventProperties[i]; _eventProperties[property.Key] = new PropertyValue(property.Value, false); } } } #endif private bool IsEmpty => (_eventProperties == null || _eventProperties.Count == 0) && (_messageProperties == null || _messageProperties.Count == 0); public IDictionary EventContext => _eventContextAdapter ?? (_eventContextAdapter = new DictionaryAdapter<object, object>(this)); private Dictionary<object, PropertyValue> EventProperties { get { if (_eventProperties == null) { System.Threading.Interlocked.CompareExchange(ref _eventProperties, BuildEventProperties(_messageProperties), null); } return _eventProperties; } } public IList<MessageTemplateParameter> MessageProperties { get => _messageProperties ?? ArrayHelper.Empty<MessageTemplateParameter>(); internal set => _messageProperties = SetMessageProperties(value, _messageProperties); } private IList<MessageTemplateParameter> SetMessageProperties(IList<MessageTemplateParameter> newMessageProperties, IList<MessageTemplateParameter> oldMessageProperties) { if (_eventProperties == null && VerifyUniqueMessageTemplateParametersFast(newMessageProperties)) { return newMessageProperties; } else { if (_eventProperties == null) { _eventProperties = new Dictionary<object, PropertyValue>(newMessageProperties.Count); } if (oldMessageProperties != null && _eventProperties.Count > 0) { RemoveOldMessageProperties(oldMessageProperties); } if (newMessageProperties != null && (_eventProperties.Count > 0 || !InsertMessagePropertiesIntoEmptyDictionary(newMessageProperties, _eventProperties))) { return CreateUniqueMessagePropertiesListSlow(newMessageProperties, _eventProperties); } else { return newMessageProperties; } } } private void RemoveOldMessageProperties(IList<MessageTemplateParameter> oldMessageProperties) { for (int i = 0; i < oldMessageProperties.Count; ++i) { if (_eventProperties.TryGetValue(oldMessageProperties[i].Name, out var propertyValue) && propertyValue.IsMessageProperty) { _eventProperties.Remove(oldMessageProperties[i].Name); } } } private static Dictionary<object, PropertyValue> BuildEventProperties(IList<MessageTemplateParameter> messageProperties) { if (messageProperties?.Count > 0) { var eventProperties = new Dictionary<object, PropertyValue>(messageProperties.Count); if (!InsertMessagePropertiesIntoEmptyDictionary(messageProperties, eventProperties)) { CreateUniqueMessagePropertiesListSlow(messageProperties, eventProperties); // Should never happen } return eventProperties; } else { return new Dictionary<object, PropertyValue>(); } } /// <inheritDoc/> public object this[object key] { get { if (!IsEmpty && EventProperties.TryGetValue(key, out var valueItem)) { return valueItem.Value; } throw new KeyNotFoundException(); } set => EventProperties[key] = new PropertyValue(value, false); } /// <inheritDoc/> public ICollection<object> Keys => KeyCollection; /// <inheritDoc/> public ICollection<object> Values => ValueCollection; private DictionaryCollection KeyCollection { get { if (_keyCollection != null) return _keyCollection; if (IsEmpty) return EmptyKeyCollection; return _keyCollection ?? (_keyCollection = new DictionaryCollection(this, true)); } } private DictionaryCollection ValueCollection { get { if (_valueCollection != null) return _valueCollection; if (IsEmpty) return EmptyValueCollection; return _valueCollection ?? (_valueCollection = new DictionaryCollection(this, false)); } } private static readonly DictionaryCollection EmptyKeyCollection = new DictionaryCollection(new PropertiesDictionary(), true); private static readonly DictionaryCollection EmptyValueCollection = new DictionaryCollection(new PropertiesDictionary(), false); /// <inheritDoc/> public int Count => (_eventProperties?.Count) ?? (_messageProperties?.Count) ?? 0; /// <inheritDoc/> public bool IsReadOnly => false; /// <inheritDoc/> public void Add(object key, object value) { EventProperties.Add(key, new PropertyValue(value, false)); } /// <inheritDoc/> public void Add(KeyValuePair<object, object> item) { Add(item.Key, item.Value); } /// <inheritDoc/> public void Clear() { _eventProperties?.Clear(); if (_messageProperties != null) _messageProperties = ArrayHelper.Empty<MessageTemplateParameter>(); } /// <inheritDoc/> public bool Contains(KeyValuePair<object, object> item) { if (!IsEmpty) { if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false)))) return true; if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true)))) return true; } return false; } /// <inheritDoc/> public bool ContainsKey(object key) { if (!IsEmpty) { return EventProperties.ContainsKey(key); } return false; } /// <inheritDoc/> public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (!IsEmpty) { foreach (var propertyItem in this) { array[arrayIndex++] = propertyItem; } } } /// <inheritDoc/> public IEnumerator<KeyValuePair<object, object>> GetEnumerator() { if (IsEmpty) return System.Linq.Enumerable.Empty<KeyValuePair<object, object>>().GetEnumerator(); return new DictionaryEnumerator(this); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { if (IsEmpty) return ArrayHelper.Empty<KeyValuePair<object, object>>().GetEnumerator(); return new DictionaryEnumerator(this); } /// <inheritDoc/> public bool Remove(object key) { if (!IsEmpty) { return EventProperties.Remove(key); } return false; } /// <inheritDoc/> public bool Remove(KeyValuePair<object, object> item) { if (!IsEmpty) { if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false)))) return true; if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true)))) return true; } return false; } /// <inheritDoc/> public bool TryGetValue(object key, out object value) { if (!IsEmpty) { if (_eventProperties is null && key is string keyString && _messageProperties?.Count < 5) { for (int i = 0; i < _messageProperties.Count; ++i) { if (keyString.Equals(_messageProperties[i].Name, StringComparison.Ordinal)) { value = _messageProperties[i].Value; return true; } } } else if (EventProperties.TryGetValue(key, out var valueItem)) { value = valueItem.Value; return true; } } value = null; return false; } /// <summary> /// Check if the message-template-parameters can be used directly without allocating a dictionary /// </summary> /// <param name="parameterList">Message-template-parameters</param> /// <returns>Are all parameter names unique (true / false)</returns> private static bool VerifyUniqueMessageTemplateParametersFast(IList<MessageTemplateParameter> parameterList) { if (parameterList == null || parameterList.Count == 0) return true; if (parameterList.Count > 10) return false; for (int i = 0; i < parameterList.Count - 1; ++i) { for (int j = i + 1; j < parameterList.Count; ++j) { if (parameterList[i].Name == parameterList[j].Name) return false; } } return true; } /// <summary> /// Attempt to insert the message-template-parameters into an empty dictionary /// </summary> /// <param name="messageProperties">Message-template-parameters</param> /// <param name="eventProperties">The initially empty dictionary</param> /// <returns>Message-template-parameters was inserted into dictionary without trouble (true/false)</returns> private static bool InsertMessagePropertiesIntoEmptyDictionary(IList<MessageTemplateParameter> messageProperties, Dictionary<object, PropertyValue> eventProperties) { try { for (int i = 0; i < messageProperties.Count; ++i) { eventProperties.Add(messageProperties[i].Name, new PropertyValue(messageProperties[i].Value, true)); } return true; // We are done } catch (ArgumentException) { // Duplicate keys found, lets try again for (int i = 0; i < messageProperties.Count; ++i) { //remove the duplicates eventProperties.Remove(messageProperties[i].Name); } return false; } } /// <summary> /// Attempt to override the existing dictionary values using the message-template-parameters /// </summary> /// <param name="messageProperties">Message-template-parameters</param> /// <param name="eventProperties">The already filled dictionary</param> /// <returns>List of unique message-template-parameters</returns> private static IList<MessageTemplateParameter> CreateUniqueMessagePropertiesListSlow(IList<MessageTemplateParameter> messageProperties, Dictionary<object, PropertyValue> eventProperties) { List<MessageTemplateParameter> messagePropertiesUnique = null; for (int i = 0; i < messageProperties.Count; ++i) { if (eventProperties.TryGetValue(messageProperties[i].Name, out var valueItem) && valueItem.IsMessageProperty) { if (messagePropertiesUnique == null) { messagePropertiesUnique = new List<MessageTemplateParameter>(messageProperties.Count); for (int j = 0; j < i; ++j) { messagePropertiesUnique.Add(messageProperties[j]); } } continue; // Skip already exists } eventProperties[messageProperties[i].Name] = new PropertyValue(messageProperties[i].Value, true); messagePropertiesUnique?.Add(messageProperties[i]); } return messagePropertiesUnique ?? messageProperties; } IEnumerator<MessageTemplateParameter> IEnumerable<MessageTemplateParameter>.GetEnumerator() { return new ParameterEnumerator(this); } private abstract class DictionaryEnumeratorBase : IDisposable { private readonly PropertiesDictionary _dictionary; private int? _messagePropertiesEnumerator; private bool _eventEnumeratorCreated; private Dictionary<object, PropertyValue>.Enumerator _eventEnumerator; protected DictionaryEnumeratorBase(PropertiesDictionary dictionary) { _dictionary = dictionary; } protected KeyValuePair<object, object> CurrentProperty { get { if (_messagePropertiesEnumerator.HasValue) { var property = _dictionary._messageProperties[_messagePropertiesEnumerator.Value]; return new KeyValuePair<object, object>(property.Name, property.Value); } if (_eventEnumeratorCreated) return new KeyValuePair<object, object>(_eventEnumerator.Current.Key, _eventEnumerator.Current.Value.Value); throw new InvalidOperationException(); } } protected MessageTemplateParameter CurrentParameter { get { if (_messagePropertiesEnumerator.HasValue) { return _dictionary._messageProperties[_messagePropertiesEnumerator.Value]; } if (_eventEnumeratorCreated) { string parameterName = XmlHelper.XmlConvertToString(_eventEnumerator.Current.Key ?? string.Empty) ?? string.Empty; return new MessageTemplateParameter(parameterName, _eventEnumerator.Current.Value.Value, null, CaptureType.Unknown); } throw new InvalidOperationException(); } } public bool MoveNext() { if (_messagePropertiesEnumerator.HasValue) { if (_messagePropertiesEnumerator.Value + 1 < _dictionary._messageProperties.Count) { // Move forward to a key that is not overriden _messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(_messagePropertiesEnumerator.Value + 1); if (_messagePropertiesEnumerator.HasValue) return true; _messagePropertiesEnumerator = _dictionary._eventProperties.Count - 1; } if (HasEventProperties(_dictionary)) { _messagePropertiesEnumerator = null; _eventEnumerator = _dictionary._eventProperties.GetEnumerator(); _eventEnumeratorCreated = true; return MoveNextValidEventProperty(); } return false; } if (_eventEnumeratorCreated) { return MoveNextValidEventProperty(); } if (HasMessageProperties(_dictionary)) { // Move forward to a key that is not overriden _messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(0); if (_messagePropertiesEnumerator.HasValue) { return true; } } if (HasEventProperties(_dictionary)) { _eventEnumerator = _dictionary._eventProperties.GetEnumerator(); _eventEnumeratorCreated = true; return MoveNextValidEventProperty(); } return false; } private static bool HasMessageProperties(PropertiesDictionary propertiesDictionary) { return propertiesDictionary._messageProperties != null && propertiesDictionary._messageProperties.Count > 0; } private static bool HasEventProperties(PropertiesDictionary propertiesDictionary) { return propertiesDictionary._eventProperties != null && propertiesDictionary._eventProperties.Count > 0; } private bool MoveNextValidEventProperty() { while (_eventEnumerator.MoveNext()) { if (!_eventEnumerator.Current.Value.IsMessageProperty) return true; } return false; } private int? FindNextValidMessagePropertyIndex(int startIndex) { if (_dictionary._eventProperties == null) return startIndex; for (int i = startIndex; i < _dictionary._messageProperties.Count; ++i) { if (_dictionary._eventProperties.TryGetValue(_dictionary._messageProperties[i].Name, out var valueItem) && valueItem.IsMessageProperty) { return i; } } return null; } public void Dispose() { // Nothing to do } public void Reset() { _messagePropertiesEnumerator = null; _eventEnumeratorCreated = false; _eventEnumerator = default(Dictionary<object, PropertyValue>.Enumerator); } } private class ParameterEnumerator : DictionaryEnumeratorBase, IEnumerator<MessageTemplateParameter> { /// <inheritDoc/> public MessageTemplateParameter Current => CurrentParameter; /// <inheritDoc/> object IEnumerator.Current => CurrentParameter; public ParameterEnumerator(PropertiesDictionary dictionary) : base(dictionary) { } } private class DictionaryEnumerator : DictionaryEnumeratorBase, IEnumerator<KeyValuePair<object, object>> { /// <inheritDoc/> public KeyValuePair<object, object> Current => CurrentProperty; /// <inheritDoc/> object IEnumerator.Current => CurrentProperty; public DictionaryEnumerator(PropertiesDictionary dictionary) : base(dictionary) { } } [DebuggerDisplay("Count = {Count}")] private class DictionaryCollection : ICollection<object> { private readonly PropertiesDictionary _dictionary; private readonly bool _keyCollection; public DictionaryCollection(PropertiesDictionary dictionary, bool keyCollection) { _dictionary = dictionary; _keyCollection = keyCollection; } /// <inheritDoc/> public int Count => _dictionary.Count; /// <inheritDoc/> public bool IsReadOnly => true; /// <summary>Will always throw, as collection is readonly</summary> public void Add(object item) { throw new NotSupportedException(); } /// <summary>Will always throw, as collection is readonly</summary> public void Clear() { throw new NotSupportedException(); } /// <summary>Will always throw, as collection is readonly</summary> public bool Remove(object item) { throw new NotSupportedException(); } /// <inheritDoc/> public bool Contains(object item) { if (_keyCollection) { return _dictionary.ContainsKey(item); } if (!_dictionary.IsEmpty) { if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, false))) return true; if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, true))) return true; } return false; } /// <inheritDoc/> public void CopyTo(object[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (!_dictionary.IsEmpty) { foreach (var propertyItem in _dictionary) { array[arrayIndex++] = _keyCollection ? propertyItem.Key : propertyItem.Value; } } } /// <inheritDoc/> public IEnumerator<object> GetEnumerator() { return new DictionaryCollectionEnumerator(_dictionary, _keyCollection); } /// <inheritDoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class DictionaryCollectionEnumerator : DictionaryEnumeratorBase, IEnumerator<object> { private readonly bool _keyCollection; public DictionaryCollectionEnumerator(PropertiesDictionary dictionary, bool keyCollection) : base(dictionary) { _keyCollection = keyCollection; } /// <inheritDoc/> public object Current => _keyCollection ? CurrentProperty.Key : CurrentProperty.Value; } } } }
using System; #if V1 using IList_ServiceElement = System.Collections.IList; using System.Collections; #else using IList_ServiceElement = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceElement>; using System.Collections.Generic; #endif using System.Text; namespace InTheHand.Net.Bluetooth { /// <summary> /// Holds an SDP data element. /// </summary> /// - /// <remarks> /// <para>A Service Element hold the data in a SDP Service Record. It can /// hold various types of data, being like the &#x2018;variant&#x2019; type in some /// environments. Each <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> in /// a <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> holds its content in a /// Service Element. /// </para> /// <para>The types currently defined in the Service Discovery specification /// include unsigned and signed integers /// of various sizes (8-bit, 16-bit etc), UUIDs in the full 128-bit form or /// in the 16 and 32-bit forms, TextString, Url etc. An element can itself /// also contain a list of element, either as a &#x2018;sequence&#x2019; or an /// &#x2018;alternative&#x2019;, and thus an attribute can contain a tree of values, /// e.g. as used by the /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute. /// </para> /// <para>The type that an element is holding can be accessed with the /// <see cref="P:InTheHand.Net.Bluetooth.ServiceElement.ElementTypeDescriptor"/> and /// <see cref="P:InTheHand.Net.Bluetooth.ServiceElement.ElementType"/> properties which /// are of type <see cref="T:InTheHand.Net.Bluetooth.ElementTypeDescriptor"/> and /// <see cref="T:InTheHand.Net.Bluetooth.ElementType"/> respectively, the former being /// the &#x2018;major&#x2019; type e.g. /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.UnsignedInteger"/>, and /// the latter the &#x2018;minor&#x2019; type e.g. /// <see cref="F:InTheHand.Net.Bluetooth.ElementType.UInt16"/>. /// </para> /// <para>The element's value can be accessed in various ways, either directly /// in its internal form through its <see cref="P:InTheHand.Net.Bluetooth.ServiceElement.Value"/> /// property. It has return type <see cref="T:System.Object"/> so the value /// will have to be cast before use, see the <c>UInt16</c> example below. There /// are also a number of type-specific methods, e.g. /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsElementArray"/>, /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUuid"/>, /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsString(System.Text.Encoding)"/> /// etc. Each will throw an <see cref="T:System.InvalidOperationException"/> /// if the element is not of a suitable type. The complete set is:</para> /// <list type="table"> /// <listheader><term><see cref="T:InTheHand.Net.Bluetooth.ElementType"/></term> /// <description>Access method, or .NET Type for direct access</description> /// </listheader> /// <item><term><c>Nil</c></term> /// <description><see langword="null"/></description></item> /// /// <item><term><c>Uint8</c></term><description><see cref="T:System.Byte"/></description></item> /// <item><term><c>Uint16</c></term><description><see cref="T:System.UInt16"/></description></item> /// <item><term><c>Uint32</c></term><description><see cref="T:System.UInt32"/></description></item> /// <item><term><c>Uint64</c></term><description>Currently unsupported.</description></item> /// <item><term><c>Uint128</c></term><description>Currently unsupported.</description></item> /// /// <item><term><c>Int8</c></term><description><see cref="T:System.SByte"/></description></item> /// <item><term><c>Int16</c></term><description><see cref="T:System.Int16"/></description></item> /// <item><term><c>Int32</c></term><description><see cref="T:System.Int32"/></description></item> /// <item><term><c>Int64</c></term><description>Currently unsupported.</description></item> /// <item><term><c>Int128</c></term><description>Currently unsupported.</description></item> /// /// <item><term><c>Uuid16</c></term><description>Via <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUuid"/>, or as <see cref="T:System.UInt16"/></description></item> /// <item><term><c>Uuid32</c></term><description>Via <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUuid"/>, or as <see cref="T:System.UInt16"/></description></item> /// <item><term><c>Uuid128</c></term><description>Via <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUuid"/></description></item> /// /// <item><term><c>TextString</c></term><description>With /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsString(System.Text.Encoding)"/> /// or <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsStringUtf8"/> etc. /// The underlying value can be an array of bytes, or as a <see cref="T:System.String"/> /// the <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordParser"/> will set an /// array of bytes, whereas a manually created record will likely contain a /// <see cref="T:System.String"/>. /// </description></item> /// /// <item><term><c>Boolean</c></term><description><see cref="T:System.Boolean"/></description></item> /// /// <item><term><c>ElementSequence</c></term><description>With /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsElementArray"/> or /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsElementList"/> /// </description></item> /// <item><term><c>ElementSequence</c></term><description>-"-</description></item> /// /// <item><term><c>Url</c></term><description>Via <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUri"/>, /// can be stored interally as <see cref="T:System.Uri"/> or as an array of bytes /// </description></item> /// </list> /// /// <para>Note that there are no access /// methods for the numeric type for instance so the /// <see cref="P:InTheHand.Net.Bluetooth.ServiceElement.Value"/> property will have /// to be used e.g. /// <code lang="C#"> /// // ElementType is UInt16 /// ushort x = (ushort)element.Value; /// </code> /// or /// <code lang="C#"> /// // ElementType is UInt16 /// Dim x As UShort = CUShort(element.Value); /// </code> /// </para> /// <para>Additional type-specific methods can be added as required, in fact the /// full set of 19+ could be added, it just requires implementation and test&#x2026; /// </para> /// </remarks> public sealed class ServiceElement { //-------------------------------------------------------------- ElementType m_type; ElementTypeDescriptor m_etd; object m_rawValue; // private const bool _strictStringDecoding = true; //-------------------------------------------------------------- #if V1 /* #endif #pragma warning disable 618 #if V1 */ #endif /// <overloads> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> class. /// </overloads> /// - /// <summary> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> class. /// </summary> /// - /// <remarks> /// <para>The type of the object passed in the <paramref name="value"/> parameter /// <strong>must</strong> suit the type of the element. For instance if the element type is /// <see cref="F:InTheHand.Net.Bluetooth.ElementType.UInt8"/> then the object /// passed in must be a <see cref="T:System.Byte"/>, if the element type is /// <see cref="F:InTheHand.Net.Bluetooth.ElementType.TextString"/> then the object /// must either be a <see cref="T:System.String"/> or the string encoded as /// an array of <see cref="T:System.Byte"/>, /// and if the element type is <see cref="F:InTheHand.Net.Bluetooth.ElementType.Uuid16"/> /// then the object passed in must be a <see cref="T:System.UInt16"/>, /// etc. /// For the full list of types see the class level documentation /// (<see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>). /// </para> /// <para>For numerical element types the /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.CreateNumericalServiceElement(InTheHand.Net.Bluetooth.ElementType,System.Object)"/> /// factory method will accept any integer type and attempt to convert it to the /// required type before creating the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>, /// for example for element type <see cref="F:InTheHand.Net.Bluetooth.ElementType.UInt8"/> /// it will accept an <see cref="T:System.Int32"/> parameter and convert /// it to a <see cref="T:System.Byte"/> internally. /// </para> /// </remarks> /// - /// <param name="type">The type of the element as an ElementType. /// </param> /// <param name="value">The value for the new element, /// <strong>must</strong> suit the type of the element. /// See the remarks for more information. /// </param> /// - /// <example> /// <code lang="C#"> /// ServiceElement e /// e = new ServiceElement(ElementType.TextString, "Hello world"); /// e = new ServiceElement(ElementType.TextString, new byte[] { (byte)'h', (byte)'i', }); /// e = new ServiceElement(ElementType.Uuid16, (UInt16)0x1101); /// /// /// int i = 10; /// int j = -1; /// /// // Error, Int32 not suitable for element type UInt8. /// ServiceElement e0 = new ServiceElement(ElementType.UInt8, i); /// /// // Success, Byte value 10 stored. /// ServiceElement e1 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, i); /// /// // Error, -1 not in range of type Byte. /// ServiceElement e2 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, j); /// </code> /// </example> public ServiceElement(ElementType type, Object value) : this(GetEtdForType(type), type, value) { } #if V1 /* #endif #pragma warning restore 618 #if V1 */ #endif private static ElementTypeDescriptor GetEtdForType(ElementType type) { return ServiceRecordParser.GetEtdForType(type); } /// <summary> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> class. /// </summary> /// - /// <param name="type">The type of the element as an ElementType. /// Should be either <c>ElementSequence</c>/<c>ElementAlternative</c> types. /// </param> /// <param name="childElements">A list of elements. /// </param> public ServiceElement(ElementType type, IList_ServiceElement childElements) : this(type, (object)childElements) { } /// <summary> /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> class. /// </summary> /// - /// <param name="type">The type of the element as an ElementType. /// Should be either <c>ElementSequence</c>/<c>ElementAlternative</c> types. /// </param> /// <param name="childElements">A list of elements. /// </param> public ServiceElement(ElementType type, params ServiceElement[] childElements) : this(checkTypeSuitsElementParamsArray(type, childElements), (object)childElements) { } private static ElementType checkTypeSuitsElementParamsArray(ElementType typePassThru, ServiceElement[] childElements) { // Throw a more specific error about the params array when the value is null. // As error would be thrown by SetValue, but we can report a more helpful message. if (childElements == null) { // Caller passed a literal null, so could be aiming for other ElementType // so can't complain that we need to be a Seq/Alt type. } else { // if (typePassThru != ElementType.ElementSequence && typePassThru != ElementType.ElementAlternative) { throw new ArgumentException(ErrorMsgSeqAltTypeNeedElementArray); } } return typePassThru; } //-------------------------------------------------------------- /// <summary> /// Obsolete, use <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.#ctor(InTheHand.Net.Bluetooth.ElementType,System.Object)"/> instead. /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> class. /// </summary> internal ServiceElement(ElementTypeDescriptor etd, ElementType type, Object value) { ServiceRecordParser.VerifyTypeMatchesEtd(etd, type); m_type = type; m_etd = etd; SetValue(value); } internal void SetValue(Object value) { ElementTypeDescriptor etd = m_etd; ElementType type = m_type; // if (value == null) { if (etd == ElementTypeDescriptor.ElementSequence || etd == ElementTypeDescriptor.ElementAlternative) { throw new ArgumentNullException("value", "Type DataElementSequence and DataElementAlternative need an list of AttributeValue."); } else if (etd == ElementTypeDescriptor.Nil) { } else if (etd == ElementTypeDescriptor.Unknown) { } else { throw new ArgumentNullException("value", "Null not valid for type: '" + type + "'."); } } else { // Check iff type=seq/alt then value is IList<ServiceElement> #if V1 #if DEBUG //Type t1 = value.GetType(); //string st1 = t1.Name; //Type t2 = null; //string st2 = null; //string j = null; //try { // Array a = (Array)value; // object item = a.GetValue(0); // t2 = value.GetType(); // st2 = t2.Name; //} catch (Exception) { // j = string.Empty; //} //Console.WriteLine("" + st1 + " / " + st2 + " " + j); #endif IList asElementList; // Parser passes in an ArrayList asElementList = value as ArrayList; if (asElementList == null) { // .ctor(ElementType type, params ServiceElement[] childElements) asElementList = value as ServiceElement[]; } if (asElementList != null) { // Ensure that the above casting won't pick up the byte[] for TextString etc. System.Diagnostics.Debug.Assert(!(value is byte[])); foreach (object item in asElementList) { //System.Diagnostics.Debug.Assert(item is ServiceElement); if (!(item is ServiceElement)) { throw new ArgumentException(ErrorMsgListContainsNotElement); } } } #else IList<ServiceElement> asElementList = value as IList<ServiceElement>; #endif if (etd == ElementTypeDescriptor.ElementSequence || etd == ElementTypeDescriptor.ElementAlternative) { if (asElementList == null) { throw new ArgumentException("Type ElementSequence and ElementAlternative need an list of ServiceElement."); } } else { if (asElementList != null) { throw new ArgumentException("Type ElementSequence and ElementAlternative must be used for an list of ServiceElement."); } } //-------- bool validTypeForType; if (type == ElementType.Nil) { validTypeForType = value == null; } else if (etd == ElementTypeDescriptor.UnsignedInteger || etd == ElementTypeDescriptor.TwosComplementInteger) { switch (type) { case ElementType.UInt8: validTypeForType = value is Byte; break; case ElementType.Int8: validTypeForType = value is SByte; break; case ElementType.UInt16: validTypeForType = value is UInt16; break; case ElementType.Int16: validTypeForType = value is Int16; break; case ElementType.UInt32: validTypeForType = value is UInt32; break; case ElementType.Int32: validTypeForType = value is Int32; break; case ElementType.UInt64: validTypeForType = value is UInt64; break; case ElementType.Int64: validTypeForType = value is Int64; break; case ElementType.UInt128: case ElementType.Int128: const int NumBytesIn128bits = 16; byte[] arr = value as byte[]; if (arr != null && arr.Length == NumBytesIn128bits) { validTypeForType = true; } else { // HACK UNTESTED validTypeForType = false; throw new ArgumentException( "Element type '" + type + "' needs a length 16 byte array."); } break; default: System.Diagnostics.Debug.Fail("Unexpected numerical type"); validTypeForType = false; break; }//switch } else if (type == ElementType.Uuid16) { validTypeForType = value is UInt16; validTypeForType = value is UInt16; } else if (type == ElementType.Uuid32) { validTypeForType = value is UInt16 || value is Int16 || value is UInt32 || value is Int32 ; } else if (type == ElementType.Uuid128) { validTypeForType = value is Guid; } else if (type == ElementType.TextString) { validTypeForType = value is byte[] || value is String; } else if (type == ElementType.Boolean) { validTypeForType = value is Boolean; } else if (type == ElementType.ElementSequence || type == ElementType.ElementAlternative) { validTypeForType = asElementList != null; } else { // if (type == ElementType.Url) System.Diagnostics.Debug.Assert(type == ElementType.Url); validTypeForType = value is byte[] || value is Uri || value is string; } if (!validTypeForType) { throw new ArgumentException("CLR type '" + value.GetType().Name + "' not valid type for element type '" + type + "'."); } } m_rawValue = value; } //-------------------------------------------------------------- /// <summary> /// Create an instance of <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> /// but internally converting the numeric value to the required type. /// </summary> /// - /// <remarks> /// <para>As noted in the constructor documentation /// (<see cref="M:InTheHand.Net.Bluetooth.ServiceElement.#ctor(InTheHand.Net.Bluetooth.ElementType,System.Object)"/>) /// the type of the value supplied <strong>must</strong> exactly match the element's natural type, /// the contructor will return an error if that is not the case. This method /// will instead attempt to convert the value to the required type. It uses /// the <see cref="T:System.IConvertible"/> interface to do the conversion, for /// instance if the element type is <c>Uint16</c> then it will cast the input value /// to <see cref="T:System.IConvertible"/> and call /// <see cref="M:System.IConvertible.ToUInt16(System.IFormatProvider)"/> on it. /// If the value is not convertible to the element type then an /// <see cref="T:System.ArgumentOutOfRangeException"/> will be thrown see below. /// </para> /// <para>For instance, passing in an C# <c>int</c> / Visual Basic <c>Integer</c> /// to the constructor will fail for element types <see cref="F:InTheHand.Net.Bluetooth.ElementType.UInt8"/> /// etc, however by using this method it will succeed if the value is in the /// correct range. /// For example /// <code lang="C#"> /// int i = 10; /// int j = -1; /// /// // Error, Int32 not suitable for element type UInt8. /// ServiceElement e0 = new ServiceElement(ElementType.UInt8, i); /// /// // Success, Byte value 10 stored. /// ServiceElement e1 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, i); /// /// // Error, -1 not in range of type Byte. /// ServiceElement e2 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, j); /// </code> /// The last example failing with: /// <code lang="none"> /// System.ArgumentOutOfRangeException: Value '-1' of type 'System.Int32' not valid for element type UInt16. /// ---> System.OverflowException: Value was either too large or too small for a UInt16. /// at System.Convert.ToUInt16(Int32 value) /// at System.Int32.System.IConvertible.ToUInt16(IFormatProvider provider) /// at InTheHand.Net.Bluetooth.ServiceElement.ConvertNumericalValue(ElementType elementType, Object value) /// --- End of inner exception stack trace --- /// at InTheHand.Net.Bluetooth.ServiceElement.ConvertNumericalValue(ElementType elementType, Object value) /// at InTheHand.Net.Bluetooth.ServiceElement.CreateNumericalServiceElement(ElementType elementType, Object value) /// at MiscFeatureTestCs.Main(String[] args) /// </code> /// </para> /// </remarks> /// - /// <param name="elementType">The type of the element as an ElementType. /// Should be one of the <c>UnsignedInteger</c>/<c>TwosComplementInteger</c> types. /// </param> /// <param name="value">The value for the new element, /// should be a numerical type. /// </param> /// - /// <returns>The new element. /// </returns> /// - /// <exception cref="T:System.ArgumentException"> /// The <paramref name="elementType"/> is not a numerical type. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The value wasn&#x2019;t convertible to the required type, e.g. if -1 is /// passed for element type UInt8, as shown above. /// </exception> public static ServiceElement CreateNumericalServiceElement(ElementType elementType, object value) { ElementTypeDescriptor etd = GetEtdForType(elementType); if (!(etd == ElementTypeDescriptor.UnsignedInteger || etd == ElementTypeDescriptor.TwosComplementInteger)) { throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, ErrorMsgFmtCreateNumericalGivenNonNumber, etd/*, (int)etd, elementType, (int)elementType*/)); } object valueConverted = ConvertNumericalValue(elementType, value); return new ServiceElement(elementType, valueConverted); } private static object ConvertNumericalValue(ElementType elementType, object value) { object naturalTypedValue = null; Exception innerEx; // if (value is Byte || value is Int16 || value is Int32 || value is Int64 || value is SByte || value is UInt16 || value is UInt32 || value is UInt64 || value is Enum) { try { IConvertible cble = (IConvertible)value; IFormatProvider fp = System.Globalization.CultureInfo.InvariantCulture; switch (elementType) { case ElementType.UInt8: naturalTypedValue = cble.ToByte(fp); break; case ElementType.Int8: naturalTypedValue = cble.ToSByte(fp); break; //-- case ElementType.UInt16: naturalTypedValue = cble.ToUInt16(fp); break; case ElementType.Int16: naturalTypedValue = cble.ToInt16(fp); break; //-- case ElementType.UInt64: naturalTypedValue = cble.ToUInt64(fp); break; case ElementType.Int64: naturalTypedValue = cble.ToInt64(fp); break; //-- case ElementType.UInt32: naturalTypedValue = cble.ToUInt32(fp); break; default: //case ElementType.Int32: System.Diagnostics.Debug.Assert(elementType == ElementType.Int32, "Unexpected numeric type"); naturalTypedValue = cble.ToInt32(fp); break; } return naturalTypedValue; } catch (OverflowException ex) { innerEx = ex; //} catch (InvalidCastException ex) { // innerEx = ex; } } else { innerEx = null; } throw ServiceRecordParser.new_ArgumentOutOfRangeException( String.Format(System.Globalization.CultureInfo.InvariantCulture, "Value '{1}' of type '{2}' not valid for element type {0}.", elementType, value, value.GetType()), innerEx); } //-------------------------------------------------------------- /// <summary> /// Gets the type of the element as an <see cref="T:InTheHand.Net.Bluetooth.ElementType"/>. /// </summary> public ElementType ElementType { [System.Diagnostics.DebuggerStepThrough] get { return m_type; } } /// <summary> /// Gets the SDP Element Type Descriptor of the element /// as an <see cref="T:InTheHand.Net.Bluetooth.ElementTypeDescriptor"/>. /// </summary> public ElementTypeDescriptor ElementTypeDescriptor { [System.Diagnostics.DebuggerStepThrough] get { return m_etd; } } //------------------------ /// <summary> /// Gets the value of the element as the .NET type it is stored as. /// </summary> /// <remarks> /// In most cases the type-specific property should be used instead, e.g /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsElementList"/>, /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUri"/>, /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsUuid"/>, etc. /// </remarks> public Object Value { [System.Diagnostics.DebuggerStepThrough] get { return m_rawValue; } } /// <summary> /// Gets the value as a list of <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>. /// </summary> /// - /// <returns>The list of elements as an list. /// </returns> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <c>ElementType</c>.<see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementSequence"/> /// or <see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementAlternative"/>. /// </exception> #if CODE_ANALYSIS [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] #endif public IList_ServiceElement GetValueAsElementList() { if (m_etd != ElementTypeDescriptor.ElementSequence && m_etd != ElementTypeDescriptor.ElementAlternative) { throw new InvalidOperationException(ErrorMsgNotSeqAltType); } // #ctor disallows null value for seq/alt. System.Diagnostics.Debug.Assert(m_rawValue != null); return (IList_ServiceElement)m_rawValue; } /// <summary> /// Gets the value as a array of <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>. /// </summary> /// - /// <returns>The list of elements as an array. /// </returns> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <c>ElementType</c>.<see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementSequence"/> /// or <see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementAlternative"/>. /// </exception> #if CODE_ANALYSIS [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] #endif public ServiceElement[] GetValueAsElementArray() { IList_ServiceElement list = GetValueAsElementList(); ServiceElement[] arr = new ServiceElement[list.Count]; GetValueAsElementList().CopyTo(arr, 0); return arr; } //------------------------ /// <summary> /// Gets the value as a <see cref="T:System.Uri"/>. /// </summary> /// - /// <returns>The Url value as a <see cref="T:System.Uri"/>. /// </returns> /// - /// <remarks> /// <para>It turns out that we can't trust vendors to add only valid /// URLs to their records, for instance the iPhone has an attribute /// with value "www.apple.com" which isn't a URL as it has no scheme /// part (http://) etc. /// </para> /// <para>Thus a Url value in an element can be stored in a number of /// formats. If created by the parser then it will be stored as a /// <see cref="T:System.String"/> or as an array of /// <see cref="T:System.Byte"/> if property /// <see cref="P:InTheHand.Net.Bluetooth.ServiceRecordParser.LazyUrlCreation">ServiceRecordParser.LazyUrlCreation</see> /// is set. If created locally it can be those types or also /// <see cref="T:System.Uri"/> . /// </para> /// <para>This method will try to convert from those formats to <see cref="T:System.Uri"/>. /// If the URL is invalid e.g. has bad characters or is missing the scheme /// part etc then an error will occur. One can instead access the /// element's <see cref="P:InTheHand.Net.Bluetooth.ServiceElement.Value"/> /// property and expect one of the three types. When created by the /// parser it will be of type <see cref="T:System.String"/> unless /// <see cref="P:InTheHand.Net.Bluetooth.ServiceRecordParser.LazyUrlCreation"/> /// is set. /// </para> /// </remarks> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <c>ElementType</c>.<see cref="F:InTheHand.Net.Bluetooth.ElementType.Url"/>. /// </exception> #if CODE_ANALYSIS [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] #endif public Uri GetValueAsUri() { if (m_type != ElementType.Url) { throw new InvalidOperationException(ErrorMsgNotUrlType); } System.Diagnostics.Debug.Assert(m_rawValue != null); Uri asUri = m_rawValue as Uri; if (asUri == null) { var arr = m_rawValue as byte[]; string str; if (arr != null) { str = ServiceRecordParser.CreateUriStringFromBytes(arr); } else { str = (string)m_rawValue; } asUri = new Uri(str); } return asUri; } //------------------------ /// <summary> /// Gets the value as a <see cref="T:System.Guid"/>. /// </summary> /// - /// <returns>The UUID value as a <see cref="T:System.Guid"/>. /// </returns> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <c>ElementType</c>.<see cref="F:InTheHand.Net.Bluetooth.ElementType.Uuid128"/>. /// </exception> #if CODE_ANALYSIS [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] #endif public Guid GetValueAsUuid() { if (m_etd != ElementTypeDescriptor.Uuid) { throw new InvalidOperationException(ErrorMsgNotUuidType); } // Guid result; if (m_type == ElementType.Uuid16) { result = BluetoothService.CreateBluetoothUuid((UInt16)Value); return result; } else if (m_type == ElementType.Uuid32) { result = BluetoothService.CreateBluetoothUuid((UInt32)Value); return result; } else { return (Guid)Value; } } //TODO ((Could have GetValueAsUuid16/32. Check subtype, but convert to short form if is Bluetooth Based.)) //------------------------ /// <summary> /// Get the value of the <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>, /// where it is encoded using the given encoding form. /// </summary> /// - /// <param name="encoding">The <see cref="T:System.Text.Encoding"/> /// object to be used to decode the string value /// if it has been read as a raw byte array. /// </param> /// - /// <returns> /// A <see cref="T:System.String"/> holding the value of the /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/> /// from the service element. /// </returns> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>. /// </exception> public String GetValueAsString(Encoding encoding) { if (encoding == null) { throw new ArgumentNullException("encoding"); } if (m_type != ElementType.TextString) { throw new InvalidOperationException(ErrorMsgNotTextStringType); } // String stringAsStored = m_rawValue as String; if (stringAsStored != null) { return stringAsStored; } // byte[] rawBytes = (byte[])m_rawValue; String str = encoding.GetString(rawBytes, 0, rawBytes.Length); if (str.Length > 0 && str[str.Length - 1] == 0) { // dodgy null-termination str = str.Substring(0, str.Length - 1); } return str; } /// <summary> /// Get the value of the <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>, /// when it is encoded as specified by the given IETF Charset identifer. /// </summary> /// - /// <remarks> /// Note that a strict decoding of the string is carried out /// (except on the NETCF where it is not supported). /// Thus if the value is not in the specified encoding, or has been /// encoded incorrectly, then an error will occur. /// </remarks> /// - /// <returns> /// A <see cref="T:System.String"/> holding the value of the /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/> /// from the service element. /// </returns> /// - /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>. /// </exception> /// <exception cref="T:System.Text.DecoderFallbackException"> /// If the value in the service element is not a valid string in the given encoding. /// </exception> public String GetValueAsString(LanguageBaseItem languageBase) { if (languageBase == null) { throw new ArgumentNullException("languageBase"); } Encoding enc = languageBase.GetEncoding(); #if ! PocketPC if (_strictStringDecoding) { enc = (Encoding)enc.Clone(); //not in NETCFv1 enc.DecoderFallback = new DecoderExceptionFallback(); // not in NETCF. // Not intended for encoding, but set it anyway. enc.EncoderFallback = new EncoderExceptionFallback(); // not in NETCF. } #endif return GetValueAsString(enc); } /// <summary> /// Get the value of the <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>, /// when it is encoded as UTF-8. /// </summary> /// - /// <remarks> /// Note: a strict decoding is used. /// Thus if the value is not in UTF-8 encoding or has been /// encoded incorrectly an error will occur. /// </remarks> /// - /// <returns> /// A <see cref="T:System.String"/> holding the value of the /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/> /// from the service element. /// </returns> /// - /// <exception cref="T:System.Text.DecoderFallbackException"> /// If the value in the service element is not a valid string in the given encoding. /// On NETCF, an <see cref="T:System.ArgumentException"/> is thrown; not that /// <see cref="T:System.ArgumentException"/> is the base class of the /// <see cref="T:System.Text.DecoderFallbackException"/> exception. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The service element is not of type /// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>. /// </exception> #if CODE_ANALYSIS [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "but throws")] #endif public String GetValueAsStringUtf8() { Encoding enc = new UTF8Encoding(false, true); //throwOnInvalidBytes=true return GetValueAsString(enc); } //-------------------------------------------------------------- /// <exclude/> public const String ErrorMsgNotUuidType = "Element is not of type UUID."; /// <exclude/> public const String ErrorMsgNotTextStringType = "Not TextString type."; /// <exclude/> public const String ErrorMsgNotUrlType = "Not Url type."; /// <exclude/> public const String ErrorMsgNotSeqAltType = "Not Element Sequence or Alternative type."; /// <exclude/> public const String ErrorMsgSeqAltTypeNeedElementArray = "ElementType Sequence or Alternative needs an array of ServiceElement."; /// <exclude/> public const String ErrorMsgFmtCreateNumericalGivenNonNumber = "Not a numerical type ({0})."; // ET is our own!! /// <exclude/> public const string ErrorMsgListContainsNotElement = "The list contains a element which is not a ServiceElement."; }//class }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Collections.Generic; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// This class implements a Finite State Machine (FSM) to control the remote connection on the client side. /// There is a similar but not identical FSM on the server side for this connection. /// /// The FSM's states and events are defined to be the same for both the client FSM and the server FSM. /// This design allows the client and server FSM's to /// be as similar as possible, so that the complexity of maintaining them is minimized. /// /// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace /// pipeline themselves. /// /// This FSM defines an event handling matrix, which is filled by the event handlers. /// The state transitions can only be performed by these event handlers, which are private /// to this class. The event handling is done by a single thread, which makes this /// implementation solid and thread safe. /// /// This implementation of the FSM does not allow the remote session to be reused for a connection /// after it is been closed. This design decision is made to simplify the implementation. /// However, the design can be easily modified to allow the reuse of the remote session /// to reconnect after the connection is closed. /// </summary> internal class ClientRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); /// <summary> /// Event handling matrix. It defines what action to take when an event occur. /// [State,Event]=>Action. /// </summary> private EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle; private Queue<RemoteSessionStateEventArgs> _clientRemoteSessionStateChangeQueue; /// <summary> /// Current state of session. /// </summary> private RemoteSessionState _state; private Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue = new Queue<RemoteSessionStateMachineEventArgs>(); // all events raised through the state machine // will be queued in this private object _syncObject = new object(); // object for synchronizing access to the above // queue private bool _eventsInProcess = false; // whether some thread is actively processing events // in a loop. If this is set then other threads // should simply add to the queue and not attempt // at processing the events in the queue. This will // guarantee that events will always be serialized // and processed /// <summary> /// Timer to be used for key exchange. /// </summary> private Timer _keyExchangeTimer; /// <summary> /// Indicates that the client has previously completed the session key exchange. /// </summary> private bool _keyExchanged = false; /// <summary> /// This is to queue up a disconnect request when a key exchange is in process /// the session will be disconnect once the exchange is complete /// intermediate disconnect requests are tracked by this flag. /// </summary> private bool _pendingDisconnect = false; /// <summary> /// Processes events in the queue. If there are no /// more events to process, then sets eventsInProcess /// variable to false. This will ensure that another /// thread which raises an event can then take control /// of processing the events. /// </summary> private void ProcessEvents() { RemoteSessionStateMachineEventArgs eventArgs = null; do { lock (_syncObject) { if (_processPendingEventsQueue.Count == 0) { _eventsInProcess = false; break; } eventArgs = _processPendingEventsQueue.Dequeue(); } try { RaiseEventPrivate(eventArgs); } catch (Exception ex) { HandleFatalError(ex); } try { RaiseStateMachineEvents(); } catch (Exception ex) { HandleFatalError(ex); } } while (_eventsInProcess); } private void HandleFatalError(Exception ex) { // Event handlers should not throw exceptions. But if they do we need to // handle them here to prevent the state machine from not responding when there are pending // events to process. // Enqueue a fatal error event if such an exception occurs; clear all existing events.. we are going to terminate the session PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(ex, RemotingErrorIdStrings.FatalErrorCausingClose); RemoteSessionStateMachineEventArgs closeEvent = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError); RaiseEvent(closeEvent, true); } /// <summary> /// Raises the StateChanged events which are queued /// All StateChanged events will be raised once the /// processing of the State Machine events are /// complete. /// </summary> private void RaiseStateMachineEvents() { RemoteSessionStateEventArgs queuedEventArg = null; while (_clientRemoteSessionStateChangeQueue.Count > 0) { queuedEventArg = _clientRemoteSessionStateChangeQueue.Dequeue(); StateChanged.SafeInvoke(this, queuedEventArg); } } /// <summary> /// Unique identifier for this state machine. Used /// in tracing. /// </summary> private Guid _id; /// <summary> /// Handler to be used in cases, where setting the state is the /// only task being performed. This method also asserts /// if the specified event is valid for the current state of /// the state machine. /// </summary> /// <param name="sender">Sender of this event.</param> /// <param name="eventArgs">Event args.</param> private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs) { switch (eventArgs.StateEvent) { case RemoteSessionEvent.NegotiationCompleted: { Dbg.Assert(_state == RemoteSessionState.NegotiationReceived, "State can be set to Established only when current state is NegotiationReceived"); SetState(RemoteSessionState.Established, null); } break; case RemoteSessionEvent.NegotiationReceived: { Dbg.Assert(eventArgs.RemoteSessionCapability != null, "State can be set to NegotiationReceived only when RemoteSessionCapability is not null"); if (eventArgs.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException("eventArgs"); } SetState(RemoteSessionState.NegotiationReceived, null); } break; case RemoteSessionEvent.NegotiationSendCompleted: { Dbg.Assert((_state == RemoteSessionState.NegotiationSending) || (_state == RemoteSessionState.NegotiationSendingOnConnect), "Negotiating send can be completed only when current state is NegotiationSending"); SetState(RemoteSessionState.NegotiationSent, null); } break; case RemoteSessionEvent.ConnectFailed: { Dbg.Assert(_state == RemoteSessionState.Connecting, "A ConnectFailed event can be raised only when the current state is Connecting"); SetState(RemoteSessionState.ClosingConnection, eventArgs.Reason); } break; case RemoteSessionEvent.CloseFailed: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } break; case RemoteSessionEvent.CloseCompleted: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } break; case RemoteSessionEvent.KeyRequested: { Dbg.Assert(_state == RemoteSessionState.Established, "Server can request a key only after the client reaches the Established state"); if (_state == RemoteSessionState.Established) { SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason); } } break; case RemoteSessionEvent.KeyReceived: { Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "Key Receiving can only be raised after reaching the Established state"); if (_state == RemoteSessionState.EstablishedAndKeySent) { Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } _keyExchanged = true; SetState(RemoteSessionState.Established, eventArgs.Reason); if (_pendingDisconnect) { // session key exchange is complete, if there is a disconnect pending, process it now _pendingDisconnect = false; DoDisconnect(sender, eventArgs); } } } break; case RemoteSessionEvent.KeySent: { Dbg.Assert(_state >= RemoteSessionState.Established, "Client can send a public key only after reaching the Established state"); Dbg.Assert(_keyExchanged == false, "Client should do key exchange only once"); if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyRequested) { SetState(RemoteSessionState.EstablishedAndKeySent, eventArgs.Reason); // start the timer and wait _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ClientDefaultOperationTimeoutMs, Timeout.Infinite); } } break; case RemoteSessionEvent.DisconnectCompleted: { Dbg.Assert(_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting, "DisconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting) { SetState(RemoteSessionState.Disconnected, eventArgs.Reason); } } break; case RemoteSessionEvent.DisconnectFailed: { Dbg.Assert(_state == RemoteSessionState.Disconnecting, "DisconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Disconnecting) { SetState(RemoteSessionState.Disconnected, eventArgs.Reason); // set state to disconnected even TODO. Put some ETW event describing the disconnect process failure } } break; case RemoteSessionEvent.ReconnectCompleted: { Dbg.Assert(_state == RemoteSessionState.Reconnecting, "ReconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Reconnecting) { SetState(RemoteSessionState.Established, eventArgs.Reason); } } break; } } /// <summary> /// Handles the timeout for key exchange. /// </summary> /// <param name="sender">Sender of this event.</param> private void HandleKeyExchangeTimeout(object sender) { Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } PSRemotingDataStructureException exception = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientKeyExchangeFailed); RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception)); } /// <summary> /// Handler to be used in cases, where raising an event to /// the state needs to be performed. This method also /// asserts if the specified event is valid for /// the current state of the state machine. /// </summary> /// <param name="sender">Sender of this event.</param> /// <param name="eventArgs">Event args.</param> private void SetStateToClosedHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs) { Dbg.Assert(_state == RemoteSessionState.NegotiationReceived && eventArgs.StateEvent == RemoteSessionEvent.NegotiationFailed || eventArgs.StateEvent == RemoteSessionEvent.SendFailed || eventArgs.StateEvent == RemoteSessionEvent.ReceiveFailed || eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout || eventArgs.StateEvent == RemoteSessionEvent.KeySendFailed || eventArgs.StateEvent == RemoteSessionEvent.KeyReceiveFailed || eventArgs.StateEvent == RemoteSessionEvent.KeyRequestFailed || eventArgs.StateEvent == RemoteSessionEvent.ReconnectFailed, "An event to close the state machine can be raised only on the following conditions: " + "1. Negotiation failed 2. Send failed 3. Receive failed 4. Negotiation timedout 5. Key send failed 6. key receive failed 7. key exchange failed 8. Reconnection failed"); // if there is a NegotiationTimeout event raised, it // shouldn't matter if we are currently in the // Established state if (eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout && State == RemoteSessionState.Established) { return; } // raise an event to close the state machine RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, eventArgs.Reason)); } #region constructor /// <summary> /// Creates an instance of ClientRemoteSessionDSHandlerStateMachine. /// </summary> internal ClientRemoteSessionDSHandlerStateMachine() { _clientRemoteSessionStateChangeQueue = new Queue<RemoteSessionStateEventArgs>(); // Initialize the state machine event handling matrix _stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { _stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatal; _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += SetStateHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnectSession; } _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSendingOnConnect] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationSendingOnConnect, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationReceived] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += SetStateToClosedHandler; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.ClosingConnection, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnect; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectFailed] += SetStateHandler; // dont close _stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.ReconnectStart] += DoReconnect; _stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectFailed] += SetStateToClosedHandler; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.RCDisconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler; // Disconnect during key exchange process _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySent] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceived] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceiveFailed] += SetStateToClosedHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // TODO: All these are potential unexpected state transitions.. should have a way to track these calls.. // should atleast put a dbg assert in this handler for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } } } _id = Guid.NewGuid(); // initialize the state to be Idle: this means it is ready to start connecting. SetState(RemoteSessionState.Idle, null); } #endregion constructor /// <summary> /// Helper method used by dependents to figure out if the RaiseEvent /// method can be short-circuited. This will be useful in cases where /// the dependent code wants to take action immediately instead of /// going through state machine. /// </summary> /// <param name="arg"></param> internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg) { if (arg.StateEvent == RemoteSessionEvent.MessageReceived) { if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyReceived || // TODO - Client session would never get into this state... to be removed _state == RemoteSessionState.EstablishedAndKeySent || _state == RemoteSessionState.Disconnecting || // There can be input data until disconnect has been completed _state == RemoteSessionState.Disconnected) // Data can arrive while state machine is transitioning to disconnected, in a race. { return true; } } return false; } /// <summary> /// This method is used by all classes to raise a FSM event. /// The method will queue the event. The event queue will be handled in /// a thread safe manner by a single dedicated thread. /// </summary> /// <param name="arg"> /// This parameter contains the event to be raised. /// </param> /// <param name="clearQueuedEvents"> /// optional bool indicating whether to clear currently queued events /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueuedEvents = false) { lock (_syncObject) { s_trace.WriteLine("Event received : {0} for {1}", arg.StateEvent, _id); if (clearQueuedEvents) { _processPendingEventsQueue.Clear(); } _processPendingEventsQueue.Enqueue(arg); if (!_eventsInProcess) { _eventsInProcess = true; } else { return; } } ProcessEvents(); } /// <summary> /// This is the private version of raising a FSM event. /// It can only be called by the dedicated thread that processes the event queue. /// It calls the event handler /// in the right position of the event handling matrix. /// </summary> /// <param name="arg"> /// The parameter contains the actual FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg) { if (arg == null) { throw PSTraceSource.NewArgumentNullException("arg"); } EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; if (handler != null) { s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); handler(this, arg); s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); } } /// <summary> /// This is a readonly property available to all other classes. It gives the FSM state. /// Other classes can query for this state. Only the FSM itself can change the state. /// </summary> internal RemoteSessionState State { get { return _state; } } /// <summary> /// This event indicates that the FSM state changed. /// </summary> internal event EventHandler<RemoteSessionStateEventArgs> StateChanged; #region Event Handlers /// <summary> /// This is the handler for CreateSession event of the FSM. This is the beginning of everything /// else. From this moment on, the FSM will proceeds step by step to eventually reach /// Established state or Closed state. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="PSArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); Dbg.Assert(_state != RemoteSessionState.ClosingConnection || _state != RemoteSessionState.Closed, "Reconnect after connection is closing or closed is not allowed"); if (State == RemoteSessionState.Idle) { // we are short-circuiting the state by going directly to NegotiationSending.. // This will save 1 network trip just to establish a connection. // Raise the event for sending the negotiation RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); RaiseEvent(sendingArg); } } } /// <summary> /// This is the handler for ConnectSession event of the FSM. This is the beginning of everything /// else. From this moment on, the FSM will proceeds step by step to eventually reach /// Established state or Closed state. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="PSArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoConnectSession(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); if (State == RemoteSessionState.Idle) { // We need to send negotiation and connect algorithm related info // Change state to let other DSHandlers add appropriate messages to be piggybacked on transport's Create payload RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendingOnConnect); RaiseEvent(sendingArg); } } } /// <summary> /// This is the handler for NegotiationSending event. /// It sets the new state to be NegotiationSending and /// calls data structure handler to send the negotiation packet. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs arg) { if (arg.StateEvent == RemoteSessionEvent.NegotiationSending) { SetState(RemoteSessionState.NegotiationSending, null); } else if (arg.StateEvent == RemoteSessionEvent.NegotiationSendingOnConnect) { SetState(RemoteSessionState.NegotiationSendingOnConnect, null); } else { Dbg.Assert(false, "NegotiationSending called on wrong event"); } } private void DoDisconnectDuringKeyExchange(object sender, RemoteSessionStateMachineEventArgs arg) { // set flag to indicate Disconnect request queue up _pendingDisconnect = true; } private void DoDisconnect(object sender, RemoteSessionStateMachineEventArgs arg) { SetState(RemoteSessionState.Disconnecting, null); } private void DoReconnect(object sender, RemoteSessionStateMachineEventArgs arg) { SetState(RemoteSessionState.Reconnecting, null); } private void DoRCDisconnectStarted(object sender, RemoteSessionStateMachineEventArgs arg) { if (State != RemoteSessionState.Disconnecting && State != RemoteSessionState.Disconnected) { SetState(RemoteSessionState.RCDisconnecting, null); } } /// <summary> /// This is the handler for Close event. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="arg"/> does not contain remote data. /// </exception> private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { RemoteSessionState oldState = _state; switch (oldState) { case RemoteSessionState.ClosingConnection: case RemoteSessionState.Closed: // do nothing break; case RemoteSessionState.Connecting: case RemoteSessionState.Connected: case RemoteSessionState.Established: case RemoteSessionState.EstablishedAndKeyReceived: // TODO - Client session would never get into this state... to be removed case RemoteSessionState.EstablishedAndKeySent: case RemoteSessionState.NegotiationReceived: case RemoteSessionState.NegotiationSent: case RemoteSessionState.NegotiationSending: case RemoteSessionState.Disconnected: case RemoteSessionState.Disconnecting: case RemoteSessionState.Reconnecting: case RemoteSessionState.RCDisconnecting: SetState(RemoteSessionState.ClosingConnection, arg.Reason); break; case RemoteSessionState.Idle: case RemoteSessionState.UndefinedState: default: PSRemotingTransportException forceClosedException = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed); SetState(RemoteSessionState.Closed, forceClosedException); break; } CleanAll(); } } /// <summary> /// Handles a fatal error message. Throws a well defined error message, /// which contains the reason for the fatal error as an inner exception. /// This way the internal details are not surfaced to the user. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing this event.</param> private void DoFatal(object sender, RemoteSessionStateMachineEventArgs eventArgs) { PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(eventArgs.Reason, RemotingErrorIdStrings.FatalErrorCausingClose); RemoteSessionStateMachineEventArgs closeEvent = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError); RaiseEvent(closeEvent); } #endregion Event Handlers private void CleanAll() { } /// <summary> /// Sets the state of the state machine. Since only /// one thread can be manipulating the state at a time /// the state is not synchronized. /// </summary> /// <param name="newState">New state of the state machine.</param> /// <param name="reason">reason why the state machine is set /// to the new state</param> private void SetState(RemoteSessionState newState, Exception reason) { RemoteSessionState oldState = _state; if (newState != oldState) { _state = newState; s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); RemoteSessionStateInfo stateInfo = new RemoteSessionStateInfo(_state, reason); RemoteSessionStateEventArgs sessionStateEventArg = new RemoteSessionStateEventArgs(stateInfo); _clientRemoteSessionStateChangeQueue.Enqueue(sessionStateEventArg); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Text; namespace System.Net.Http.Headers { // This type is used to store a collection of headers in 'headerStore': // - A header can have multiple values. // - A header can have an associated parser which is able to parse the raw string value into a strongly typed object. // - If a header has an associated parser and the provided raw value can't be parsed, the value is considered // invalid. Invalid values are stored if added using TryAddWithoutValidation(). If the value was added using Add(), // Add() will throw FormatException. // - Since parsing header values is expensive and users usually only care about a few headers, header values are // lazily initialized. // // Given the properties above, a header value can have three states: // - 'raw': The header value was added using TryAddWithoutValidation() and it wasn't parsed yet. // - 'parsed': The header value was successfully parsed. It was either added using Add() where the value was parsed // immediately, or if added using TryAddWithoutValidation() a user already accessed a property/method triggering the // value to be parsed. // - 'invalid': The header value was parsed, but parsing failed because the value is invalid. Storing invalid values // allows users to still retrieve the value (by calling GetValues()), but it will not be exposed as strongly typed // object. E.g. the client receives a response with the following header: 'Via: 1.1 proxy, invalid' // - HttpHeaders.GetValues() will return "1.1 proxy", "invalid" // - HttpResponseHeaders.Via collection will only contain one ViaHeaderValue object with value "1.1 proxy" [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public abstract class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>> { private Dictionary<string, HeaderStoreItemInfo> _headerStore; private Dictionary<string, HttpHeaderParser> _parserStore; private HashSet<string> _invalidHeaders; private enum StoreLocation { Raw, Invalid, Parsed } protected HttpHeaders() { } public void Add(string name, string value) { CheckHeaderName(name); // We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing // the value then throws, we would have to remove the header from the store again. So just get a // HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header. HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(name, out info, out addToStore); ParseAndAddValue(name, info, value); // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. if (addToStore && (info.ParsedValue != null)) { AddHeaderToStore(name, info); } } public void Add(string name, IEnumerable<string> values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } CheckHeaderName(name); HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(name, out info, out addToStore); try { // Note that if the first couple of values are valid followed by an invalid value, the valid values // will be added to the store before the exception for the invalid value is thrown. foreach (string value in values) { ParseAndAddValue(name, info, value); } } finally { // Even if one of the values was invalid, make sure we add the header for the valid ones. We need to be // consistent here: If values get added to an _existing_ header, then all values until the invalid one // get added. Same here: If multiple values get added to a _new_ header, make sure the header gets added // with the valid values. // However, if all values for a _new_ header were invalid, then don't add the header. if (addToStore && (info.ParsedValue != null)) { AddHeaderToStore(name, info); } } } public bool TryAddWithoutValidation(string name, string value) { if (!TryCheckHeaderName(name)) { return false; } if (value == null) { // We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty // values, we'll just add them to the collection. This will result in delimiter-only values: // E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,". value = string.Empty; } HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false); AddValue(info, value, StoreLocation.Raw); return true; } public bool TryAddWithoutValidation(string name, IEnumerable<string> values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } if (!TryCheckHeaderName(name)) { return false; } HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false); foreach (string value in values) { // We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty // values, we'll just add them to the collection. This will result in delimiter-only values: // E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,". AddValue(info, value ?? string.Empty, StoreLocation.Raw); } return true; } public void Clear() { if (_headerStore != null) { _headerStore.Clear(); } } public bool Remove(string name) { CheckHeaderName(name); if (_headerStore == null) { return false; } return _headerStore.Remove(name); } public IEnumerable<string> GetValues(string name) { CheckHeaderName(name); IEnumerable<string> values; if (!TryGetValues(name, out values)) { throw new InvalidOperationException(SR.net_http_headers_not_found); } return values; } public bool TryGetValues(string name, out IEnumerable<string> values) { if (!TryCheckHeaderName(name)) { values = null; return false; } if (_headerStore == null) { values = null; return false; } HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(name, out info)) { values = GetValuesAsStrings(info); return true; } values = null; return false; } public bool Contains(string name) { CheckHeaderName(name); if (_headerStore == null) { return false; } // We can't just call headerStore.ContainsKey() since after parsing the value the header may not exist // anymore (if the value contains invalid newline chars, we remove the header). So try to parse the // header value. HeaderStoreItemInfo info = null; return TryGetAndParseHeaderInfo(name, out info); } public override string ToString() { if (_headerStore == null || _headerStore.Count == 0) { return string.Empty; } // Return all headers as string similar to: // HeaderName1: Value1, Value2 // HeaderName2: Value1 // ... StringBuilder sb = new StringBuilder(); foreach (var header in this) { sb.Append(header.Key); sb.Append(": "); sb.Append(this.GetHeaderString(header.Key)); sb.Append("\r\n"); } return sb.ToString(); } internal IEnumerable<KeyValuePair<string, string>> GetHeaderStrings() { if (_headerStore == null) { yield break; } foreach (var header in _headerStore) { HeaderStoreItemInfo info = header.Value; string stringValue = GetHeaderString(info); yield return new KeyValuePair<string, string>(header.Key, stringValue); } } internal string GetHeaderString(string headerName) { return GetHeaderString(headerName, null); } internal string GetHeaderString(string headerName, object exclude) { HeaderStoreItemInfo info; if (!TryGetHeaderInfo(headerName, out info)) { return string.Empty; } return GetHeaderString(info, exclude); } private string GetHeaderString(HeaderStoreItemInfo info) { return GetHeaderString(info, null); } private string GetHeaderString(HeaderStoreItemInfo info, object exclude) { string stringValue; string[] values = GetValuesAsStrings(info, exclude); if (values.Length == 1) { stringValue = values[0]; } else { // Note that if we get multiple values for a header that doesn't support multiple values, we'll // just separate the values using a comma (default separator). string separator = HttpHeaderParser.DefaultSeparator; if ((info.Parser != null) && (info.Parser.SupportsMultipleValues)) { separator = info.Parser.Separator; } stringValue = string.Join(separator, values); } return stringValue; } #region IEnumerable<KeyValuePair<string, IEnumerable<string>>> Members public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator() { return _headerStore != null && _headerStore.Count > 0 ? GetEnumeratorCore() : ((IEnumerable<KeyValuePair<string, IEnumerable<string>>>)Array.Empty<KeyValuePair<string, IEnumerable<string>>>()).GetEnumerator(); } private IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumeratorCore() { List<string> invalidHeaders = null; foreach (var header in _headerStore) { HeaderStoreItemInfo info = header.Value; // Make sure we parse all raw values before returning the result. Note that this has to be // done before we calculate the array length (next line): A raw value may contain a list of // values. if (!ParseRawHeaderValues(header.Key, info, false)) { // We have an invalid header value (contains invalid newline chars). Mark it as "to-be-deleted" // and skip this header. if (invalidHeaders == null) { invalidHeaders = new List<string>(); } invalidHeaders.Add(header.Key); } else { string[] values = GetValuesAsStrings(info); yield return new KeyValuePair<string, IEnumerable<string>>(header.Key, values); } } // While we were enumerating headers, we also parsed header values. If during parsing it turned out that // the header value was invalid (contains invalid newline chars), remove the header from the store after // completing the enumeration. if (invalidHeaders != null) { Debug.Assert(_headerStore != null); foreach (string invalidHeader in invalidHeaders) { _headerStore.Remove(invalidHeader); } } } #endregion #region IEnumerable Members Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion internal void SetConfiguration(Dictionary<string, HttpHeaderParser> parserStore, HashSet<string> invalidHeaders) { Debug.Assert(_parserStore == null, "Parser store was already set."); _parserStore = parserStore; _invalidHeaders = invalidHeaders; } internal void AddParsedValue(string name, object value) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); Debug.Assert(value != null); HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true); Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available."); // If the current header has only one value, we can't add another value. The strongly typed property // must not call AddParsedValue(), but SetParsedValue(). E.g. for headers like 'Date', 'Host'. Debug.Assert(info.CanAddValue, "Header '" + name + "' doesn't support multiple values"); AddValue(info, value, StoreLocation.Parsed); } internal void SetParsedValue(string name, object value) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); Debug.Assert(value != null); // This method will first clear all values. This is used e.g. when setting the 'Date' or 'Host' header. // I.e. headers not supporting collections. HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true); Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available."); info.InvalidValue = null; info.ParsedValue = null; info.RawValue = null; AddValue(info, value, StoreLocation.Parsed); } internal void SetOrRemoveParsedValue(string name, object value) { if (value == null) { Remove(name); } else { SetParsedValue(name, value); } } internal bool RemoveParsedValue(string name, object value) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); Debug.Assert(value != null); if (_headerStore == null) { return false; } // If we have a value for this header, then verify if we have a single value. If so, compare that // value with 'item'. If we have a list of values, then remove 'item' from the list. HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(name, out info)) { Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available."); Debug.Assert(info.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use Remove(string) instead."); bool result = false; // If there is no entry, just return. if (info.ParsedValue == null) { return false; } IEqualityComparer comparer = info.Parser.Comparer; List<object> parsedValues = info.ParsedValue as List<object>; if (parsedValues == null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); if (AreEqual(value, info.ParsedValue, comparer)) { info.ParsedValue = null; result = true; } } else { foreach (object item in parsedValues) { Debug.Assert(item.GetType() == value.GetType(), "One of the stored values does not have the same type as 'value'."); if (AreEqual(value, item, comparer)) { // Remove 'item' rather than 'value', since the 'comparer' may consider two values // equal even though the default obj.Equals() may not (e.g. if 'comparer' does // case-insensitive comparison for strings, but string.Equals() is case-sensitive). result = parsedValues.Remove(item); break; } } // If we removed the last item in a list, remove the list. if (parsedValues.Count == 0) { info.ParsedValue = null; } } // If there is no value for the header left, remove the header. if (info.IsEmpty) { bool headerRemoved = Remove(name); Debug.Assert(headerRemoved, "Existing header '" + name + "' couldn't be removed."); } return result; } return false; } internal bool ContainsParsedValue(string name, object value) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); Debug.Assert(value != null); if (_headerStore == null) { return false; } // If we have a value for this header, then verify if we have a single value. If so, compare that // value with 'item'. If we have a list of values, then compare each item in the list with 'item'. HeaderStoreItemInfo info = null; if (TryGetAndParseHeaderInfo(name, out info)) { Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available."); Debug.Assert(info.Parser.SupportsMultipleValues, "This method should not be used for single-value headers. Use equality comparer instead."); // If there is no entry, just return. if (info.ParsedValue == null) { return false; } List<object> parsedValues = info.ParsedValue as List<object>; IEqualityComparer comparer = info.Parser.Comparer; if (parsedValues == null) { Debug.Assert(info.ParsedValue.GetType() == value.GetType(), "Stored value does not have the same type as 'value'."); return AreEqual(value, info.ParsedValue, comparer); } else { foreach (object item in parsedValues) { Debug.Assert(item.GetType() == value.GetType(), "One of the stored values does not have the same type as 'value'."); if (AreEqual(value, item, comparer)) { return true; } } return false; } } return false; } internal virtual void AddHeaders(HttpHeaders sourceHeaders) { Debug.Assert(sourceHeaders != null); Debug.Assert(_parserStore == sourceHeaders._parserStore, "Can only copy headers from an instance with the same header parsers."); if (sourceHeaders._headerStore == null) { return; } List<string> invalidHeaders = null; foreach (var header in sourceHeaders._headerStore) { // Only add header values if they're not already set on the message. Note that we don't merge // collections: If both the default headers and the message have set some values for a certain // header, then we don't try to merge the values. if ((_headerStore == null) || (!_headerStore.ContainsKey(header.Key))) { HeaderStoreItemInfo sourceInfo = header.Value; // If DefaultRequestHeaders values are copied to multiple messages, it is useful to parse these // default header values only once. This is what we're doing here: By parsing raw headers in // 'sourceHeaders' before copying values to our header store. if (!sourceHeaders.ParseRawHeaderValues(header.Key, sourceInfo, false)) { // If after trying to parse source header values no value is left (i.e. all values contain // invalid newline chars), mark this header as 'to-be-deleted' and skip to the next header. if (invalidHeaders == null) { invalidHeaders = new List<string>(); } invalidHeaders.Add(header.Key); } else { AddHeaderInfo(header.Key, sourceInfo); } } } if (invalidHeaders != null) { Debug.Assert(sourceHeaders._headerStore != null); foreach (string invalidHeader in invalidHeaders) { sourceHeaders._headerStore.Remove(invalidHeader); } } } private void AddHeaderInfo(string headerName, HeaderStoreItemInfo sourceInfo) { HeaderStoreItemInfo destinationInfo = CreateAndAddHeaderToStore(headerName); Debug.Assert(sourceInfo.Parser == destinationInfo.Parser, "Expected same parser on both source and destination header store for header '" + headerName + "'."); // We have custom header values. The parsed values are strings. if (destinationInfo.Parser == null) { Debug.Assert((sourceInfo.RawValue == null) && (sourceInfo.InvalidValue == null), "No raw or invalid values expected for custom headers."); // Custom header values are always stored as string or list of strings. destinationInfo.ParsedValue = CloneStringHeaderInfoValues(sourceInfo.ParsedValue); } else { // We have a parser, so we have to copy invalid values and clone parsed values. // Invalid values are always strings. Strings are immutable. So we only have to clone the // collection (if there is one). destinationInfo.InvalidValue = CloneStringHeaderInfoValues(sourceInfo.InvalidValue); // Now clone and add parsed values (if any). if (sourceInfo.ParsedValue != null) { List<object> sourceValues = sourceInfo.ParsedValue as List<object>; if (sourceValues == null) { CloneAndAddValue(destinationInfo, sourceInfo.ParsedValue); } else { foreach (object item in sourceValues) { CloneAndAddValue(destinationInfo, item); } } } } } private static void CloneAndAddValue(HeaderStoreItemInfo destinationInfo, object source) { // We only have one value. Clone it and assign it to the store. ICloneable cloneableValue = source as ICloneable; if (cloneableValue != null) { AddValue(destinationInfo, cloneableValue.Clone(), StoreLocation.Parsed); } else { // If it doesn't implement ICloneable, it's a value type or an immutable type like String/Uri. AddValue(destinationInfo, source, StoreLocation.Parsed); } } private static object CloneStringHeaderInfoValues(object source) { if (source == null) { return null; } List<object> sourceValues = source as List<object>; if (sourceValues == null) { // If we just have one value, return the reference to the string (strings are immutable so it's OK // to use the reference). return source; } else { // If we have a list of strings, create a new list and copy all strings to the new list. return new List<object>(sourceValues); } } private HeaderStoreItemInfo GetOrCreateHeaderInfo(string name, bool parseRawValues) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); Contract.Ensures(Contract.Result<HeaderStoreItemInfo>() != null); HeaderStoreItemInfo result = null; bool found = false; if (parseRawValues) { found = TryGetAndParseHeaderInfo(name, out result); } else { found = TryGetHeaderInfo(name, out result); } if (!found) { result = CreateAndAddHeaderToStore(name); } return result; } private HeaderStoreItemInfo CreateAndAddHeaderToStore(string name) { // If we don't have the header in the store yet, add it now. HeaderStoreItemInfo result = new HeaderStoreItemInfo(GetParser(name)); AddHeaderToStore(name, result); return result; } private void AddHeaderToStore(string name, HeaderStoreItemInfo info) { if (_headerStore == null) { _headerStore = new Dictionary<string, HeaderStoreItemInfo>( StringComparer.OrdinalIgnoreCase); } _headerStore.Add(name, info); } private bool TryGetHeaderInfo(string name, out HeaderStoreItemInfo info) { if (_headerStore == null) { info = null; return false; } return _headerStore.TryGetValue(name, out info); } private bool TryGetAndParseHeaderInfo(string name, out HeaderStoreItemInfo info) { if (TryGetHeaderInfo(name, out info)) { return ParseRawHeaderValues(name, info, true); } return false; } private bool ParseRawHeaderValues(string name, HeaderStoreItemInfo info, bool removeEmptyHeader) { // Prevent multiple threads from parsing the raw value at the same time, or else we would get // false duplicates or false nulls. lock (info) { // Unlike TryGetHeaderInfo() this method tries to parse all non-validated header values (if any) // before returning to the caller. if (info.RawValue != null) { List<string> rawValues = info.RawValue as List<string>; if (rawValues == null) { ParseSingleRawHeaderValue(name, info); } else { ParseMultipleRawHeaderValues(name, info, rawValues); } // At this point all values are either in info.ParsedValue, info.InvalidValue, or were removed since they // contain invalid newline chars. Reset RawValue. info.RawValue = null; // During parsing, we removed the value since it contains invalid newline chars. Return false to indicate that // this is an empty header. If the caller specified to remove empty headers, we'll remove the header before // returning. if ((info.InvalidValue == null) && (info.ParsedValue == null)) { if (removeEmptyHeader) { // After parsing the raw value, no value is left because all values contain invalid newline // chars. Debug.Assert(_headerStore != null); _headerStore.Remove(name); } return false; } } } return true; } private static void ParseMultipleRawHeaderValues(string name, HeaderStoreItemInfo info, List<string> rawValues) { if (info.Parser == null) { foreach (string rawValue in rawValues) { if (!ContainsInvalidNewLine(rawValue, name)) { AddValue(info, rawValue, StoreLocation.Parsed); } } } else { foreach (string rawValue in rawValues) { if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true)) { if (NetEventSource.IsEnabled) NetEventSource.Log.HeadersInvalidValue(name, rawValue); } } } } private static void ParseSingleRawHeaderValue(string name, HeaderStoreItemInfo info) { string rawValue = info.RawValue as string; Debug.Assert(rawValue != null, "RawValue must either be List<string> or string."); if (info.Parser == null) { if (!ContainsInvalidNewLine(rawValue, name)) { AddValue(info, rawValue, StoreLocation.Parsed); } } else { if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true)) { if (NetEventSource.IsEnabled) NetEventSource.Log.HeadersInvalidValue(name, rawValue); } } } // See Add(name, string) internal bool TryParseAndAddValue(string name, string value) { // We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing // the value then throws, we would have to remove the header from the store again. So just get a // HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header. HeaderStoreItemInfo info; bool addToStore; PrepareHeaderInfoForAdd(name, out info, out addToStore); bool result = TryParseAndAddRawHeaderValue(name, info, value, false); if (result && addToStore && (info.ParsedValue != null)) { // If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add // it to the store if we added at least one value. AddHeaderToStore(name, info); } return result; } // See ParseAndAddValue private static bool TryParseAndAddRawHeaderValue(string name, HeaderStoreItemInfo info, string value, bool addWhenInvalid) { Debug.Assert(info != null); Debug.Assert(info.Parser != null); // Values are added as 'invalid' if we either can't parse the value OR if we already have a value // and the current header doesn't support multiple values: e.g. trying to add a date/time value // to the 'Date' header if we already have a date/time value will result in the second value being // added to the 'invalid' header values. if (!info.CanAddValue) { if (addWhenInvalid) { AddValue(info, value ?? string.Empty, StoreLocation.Invalid); } return false; } int index = 0; object parsedValue = null; if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue)) { // The raw string only represented one value (which was successfully parsed). Add the value and return. if ((value == null) || (index == value.Length)) { if (parsedValue != null) { AddValue(info, parsedValue, StoreLocation.Parsed); } return true; } Debug.Assert(index < value.Length, "Parser must return an index value within the string length."); // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List<object> parsedValues = new List<object>(); if (parsedValue != null) { parsedValues.Add(parsedValue); } while (index < value.Length) { if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue)) { if (parsedValue != null) { parsedValues.Add(parsedValue); } } else { if (!ContainsInvalidNewLine(value, name) && addWhenInvalid) { AddValue(info, value, StoreLocation.Invalid); } return false; } } // All values were parsed correctly. Copy results to the store. foreach (object item in parsedValues) { AddValue(info, item, StoreLocation.Parsed); } return true; } if (!ContainsInvalidNewLine(value, name) && addWhenInvalid) { AddValue(info, value ?? string.Empty, StoreLocation.Invalid); } return false; } private static void AddValue(HeaderStoreItemInfo info, object value, StoreLocation location) { // Since we have the same pattern for all three store locations (raw, invalid, parsed), we use // this helper method to deal with adding values: // - if 'null' just set the store property to 'value' // - if 'List<T>' append 'value' to the end of the list // - if 'T', i.e. we have already a value stored (but no list), create a list, add the stored value // to the list and append 'value' at the end of the newly created list. Debug.Assert((info.Parser != null) || ((info.Parser == null) && (value.GetType() == typeof(string))), "If no parser is defined, then the value must be string."); object currentStoreValue = null; switch (location) { case StoreLocation.Raw: currentStoreValue = info.RawValue; AddValueToStoreValue<string>(info, value, ref currentStoreValue); info.RawValue = currentStoreValue; break; case StoreLocation.Invalid: currentStoreValue = info.InvalidValue; AddValueToStoreValue<string>(info, value, ref currentStoreValue); info.InvalidValue = currentStoreValue; break; case StoreLocation.Parsed: Debug.Assert((value == null) || (!(value is List<object>)), "Header value types must not derive from List<object> since this type is used internally to store " + "lists of values. So we would not be able to distinguish between a single value and a list of values."); currentStoreValue = info.ParsedValue; AddValueToStoreValue<object>(info, value, ref currentStoreValue); info.ParsedValue = currentStoreValue; break; default: Debug.Assert(false, "Unknown StoreLocation value: " + location.ToString()); break; } } private static void AddValueToStoreValue<T>(HeaderStoreItemInfo info, object value, ref object currentStoreValue) where T : class { // If there is no value set yet, then add current item as value (we don't create a list // if not required). If 'info.Value' is already assigned then make sure 'info.Value' is a // List<T> and append 'item' to the list. if (currentStoreValue == null) { currentStoreValue = value; } else { List<T> storeValues = currentStoreValue as List<T>; if (storeValues == null) { storeValues = new List<T>(2); Debug.Assert(value is T); storeValues.Add(currentStoreValue as T); currentStoreValue = storeValues; } Debug.Assert(value is T); storeValues.Add(value as T); } } // Since most of the time we just have 1 value, we don't create a List<object> for one value, but we change // the return type to 'object'. The caller has to deal with the return type (object vs. List<object>). This // is to optimize the most common scenario where a header has only one value. internal object GetParsedValues(string name) { Debug.Assert((name != null) && (name.Length > 0)); Debug.Assert(HttpRuleParser.GetTokenLength(name, 0) == name.Length); HeaderStoreItemInfo info = null; if (!TryGetAndParseHeaderInfo(name, out info)) { return null; } return info.ParsedValue; } private void PrepareHeaderInfoForAdd(string name, out HeaderStoreItemInfo info, out bool addToStore) { info = null; addToStore = false; if (!TryGetAndParseHeaderInfo(name, out info)) { info = new HeaderStoreItemInfo(GetParser(name)); addToStore = true; } } private void ParseAndAddValue(string name, HeaderStoreItemInfo info, string value) { Debug.Assert(info != null); if (info.Parser == null) { // If we don't have a parser for the header, we consider the value valid if it doesn't contains // invalid newline characters. We add the values as "parsed value". Note that we allow empty values. CheckInvalidNewLine(value); AddValue(info, value ?? string.Empty, StoreLocation.Parsed); return; } // If the header only supports 1 value, we can add the current value only if there is no // value already set. if (!info.CanAddValue) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_single_value_header, name)); } int index = 0; object parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index); // The raw string only represented one value (which was successfully parsed). Add the value and return. // If value is null we still have to first call ParseValue() to allow the parser to decide whether null is // a valid value. If it is (i.e. no exception thrown), we set the parsed value (if any) and return. if ((value == null) || (index == value.Length)) { // If the returned value is null, then it means the header accepts empty values. I.e. we don't throw // but we don't add 'null' to the store either. if (parsedValue != null) { AddValue(info, parsedValue, StoreLocation.Parsed); } return; } Debug.Assert(index < value.Length, "Parser must return an index value within the string length."); // If we successfully parsed a value, but there are more left to read, store the results in a temp // list. Only when all values are parsed successfully write the list to the store. List<object> parsedValues = new List<object>(); if (parsedValue != null) { parsedValues.Add(parsedValue); } while (index < value.Length) { parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index); if (parsedValue != null) { parsedValues.Add(parsedValue); } } // All values were parsed correctly. Copy results to the store. foreach (object item in parsedValues) { AddValue(info, item, StoreLocation.Parsed); } } private HttpHeaderParser GetParser(string name) { if (_parserStore == null) { return null; } HttpHeaderParser parser = null; if (_parserStore.TryGetValue(name, out parser)) { return parser; } return null; } private void CheckHeaderName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name)); } if (HttpRuleParser.GetTokenLength(name, 0) != name.Length) { throw new FormatException(SR.net_http_headers_invalid_header_name); } if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name))) { throw new InvalidOperationException(SR.net_http_headers_not_allowed_header_name); } } private bool TryCheckHeaderName(string name) { if (string.IsNullOrEmpty(name)) { return false; } if (HttpRuleParser.GetTokenLength(name, 0) != name.Length) { return false; } if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name))) { return false; } return true; } private static void CheckInvalidNewLine(string value) { if (value == null) { return; } if (HttpRuleParser.ContainsInvalidNewLine(value)) { throw new FormatException(SR.net_http_headers_no_newlines); } } private static bool ContainsInvalidNewLine(string value, string name) { if (HttpRuleParser.ContainsInvalidNewLine(value)) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_no_newlines, name, value)); return true; } return false; } private static string[] GetValuesAsStrings(HeaderStoreItemInfo info) { return GetValuesAsStrings(info, null); } // When doing exclusion comparison, assume raw values have been parsed. private static string[] GetValuesAsStrings(HeaderStoreItemInfo info, object exclude) { Contract.Ensures(Contract.Result<string[]>() != null); int length = GetValueCount(info); string[] values; if (length > 0) { values = new string[length]; int currentIndex = 0; ReadStoreValues<string>(values, info.RawValue, null, null, ref currentIndex); ReadStoreValues<object>(values, info.ParsedValue, info.Parser, exclude, ref currentIndex); // Set parser parameter to 'null' for invalid values: The invalid values is always a string so we // don't need the parser to "serialize" the value to a string. ReadStoreValues<string>(values, info.InvalidValue, null, null, ref currentIndex); // The values array may not be full because some values were excluded if (currentIndex < length) { string[] trimmedValues = new string[currentIndex]; Array.Copy(values, 0, trimmedValues, 0, currentIndex); values = trimmedValues; } } else { values = Array.Empty<string>(); } return values; } private static int GetValueCount(HeaderStoreItemInfo info) { Debug.Assert(info != null); int valueCount = 0; UpdateValueCount<string>(info.RawValue, ref valueCount); UpdateValueCount<string>(info.InvalidValue, ref valueCount); UpdateValueCount<object>(info.ParsedValue, ref valueCount); return valueCount; } private static void UpdateValueCount<T>(object valueStore, ref int valueCount) { if (valueStore == null) { return; } List<T> values = valueStore as List<T>; if (values != null) { valueCount += values.Count; } else { valueCount++; } } private static void ReadStoreValues<T>(string[] values, object storeValue, HttpHeaderParser parser, T exclude, ref int currentIndex) { Debug.Assert(values != null); if (storeValue != null) { List<T> storeValues = storeValue as List<T>; if (storeValues == null) { if (ShouldAdd<T>(storeValue, parser, exclude)) { values[currentIndex] = parser == null ? storeValue.ToString() : parser.ToString(storeValue); currentIndex++; } } else { foreach (object item in storeValues) { if (ShouldAdd<T>(item, parser, exclude)) { values[currentIndex] = parser == null ? item.ToString() : parser.ToString(item); currentIndex++; } } } } } private static bool ShouldAdd<T>(object storeValue, HttpHeaderParser parser, T exclude) { bool add = true; if (parser != null && exclude != null) { if (parser.Comparer != null) { add = !parser.Comparer.Equals(exclude, storeValue); } else { add = !exclude.Equals(storeValue); } } return add; } private bool AreEqual(object value, object storeValue, IEqualityComparer comparer) { Debug.Assert(value != null); if (comparer != null) { return comparer.Equals(value, storeValue); } // We don't have a comparer, so use the Equals() method. return value.Equals(storeValue); } #region Private Classes private class HeaderStoreItemInfo { private object _rawValue; private object _invalidValue; private object _parsedValue; private HttpHeaderParser _parser; internal object RawValue { get { return _rawValue; } set { _rawValue = value; } } internal object InvalidValue { get { return _invalidValue; } set { _invalidValue = value; } } internal object ParsedValue { get { return _parsedValue; } set { _parsedValue = value; } } internal HttpHeaderParser Parser { get { return _parser; } } internal bool CanAddValue { get { Debug.Assert(_parser != null, "There should be no reason to call CanAddValue if there is no parser for the current header."); // If the header only supports one value, and we have already a value set, then we can't add // another value. E.g. the 'Date' header only supports one value. We can't add multiple timestamps // to 'Date'. // So if this is a known header, ask the parser if it supports multiple values and check whether // we already have a (valid or invalid) value. // Note that we ignore the rawValue by purpose: E.g. we are parsing 2 raw values for a header only // supporting 1 value. When the first value gets parsed, CanAddValue returns true and we add the // parsed value to ParsedValue. When the second value is parsed, CanAddValue returns false, because // we have already a parsed value. return ((_parser.SupportsMultipleValues) || ((_invalidValue == null) && (_parsedValue == null))); } } internal bool IsEmpty { get { return ((_rawValue == null) && (_invalidValue == null) && (_parsedValue == null)); } } internal HeaderStoreItemInfo(HttpHeaderParser parser) { // Can be null. _parser = parser; } } #endregion } }
namespace BaristaLabs.BaristaCore.JavaScript { using Internal; using System; using System.Runtime.InteropServices; /// <summary> /// ChakraCore.h interface /// </summary> public interface ICoreJavaScriptEngine { /// <summary> /// Creates a new enhanced JavaScript function. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="nativeFunction"> /// The method to call when the function is invoked. /// </param> /// <param name="metadata"> /// If this is not JS_INVALID_REFERENCE, it is converted to a string and used as the name of the function. /// </param> /// <param name="callbackState"> /// User provided state that will be passed back to the callback. /// </param> /// <returns> /// The new function object. /// </returns> JavaScriptValueSafeHandle JsCreateEnhancedFunction(JavaScriptEnhancedNativeFunction nativeFunction, JavaScriptValueSafeHandle metadata, IntPtr callbackState); /// <summary> /// Initialize a ModuleRecord from host /// </summary> /// <remarks> /// Bootstrap the module loading process by creating a new module record. /// </remarks> /// <param name="referencingModule"> /// The parent module of the new module - nullptr for a root module. /// </param> /// <param name="normalizedSpecifier"> /// The normalized specifier for the module. /// </param> /// <returns> /// The new module record. The host should not try to call this API twice /// with the same normalizedSpecifier. /// </returns> JavaScriptModuleRecord JsInitializeModuleRecord(JavaScriptModuleRecord referencingModule, JavaScriptValueSafeHandle normalizedSpecifier); /// <summary> /// Parse the source for an ES module /// </summary> /// <remarks> /// This is basically ParseModule operation in ES6 spec. It is slightly different in that: /// a) The ModuleRecord was initialized earlier, and passed in as an argument. /// b) This includes a check to see if the module being Parsed is the last module in the /// dependency tree. If it is it automatically triggers Module Instantiation. /// </remarks> /// <param name="requestModule"> /// The ModuleRecord being parsed. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// </param> /// <param name="script"> /// The source script to be parsed, but not executed in this code. /// </param> /// <param name="scriptLength"> /// The length of sourceText in bytes. As the input might contain a embedded null. /// </param> /// <param name="sourceFlag"> /// The type of the source code passed in. It could be utf16 or utf8 at this time. /// </param> /// <returns> /// The error object if there is parse error. /// </returns> JavaScriptValueSafeHandle JsParseModuleSource(JavaScriptModuleRecord requestModule, JavaScriptSourceContext sourceContext, byte[] script, uint scriptLength, JavaScriptParseModuleSourceFlags sourceFlag); /// <summary> /// Execute module code. /// </summary> /// <remarks> /// This method implements 15.2.1.1.6.5, "ModuleEvaluation" concrete method. /// This method should be called after the engine notifies the host that the module is ready. /// This method only needs to be called on root modules - it will execute all of the dependent modules. /// One moduleRecord will be executed only once. Additional execution call on the same moduleRecord will fail. /// </remarks> /// <param name="requestModule"> /// The ModuleRecord being executed. /// </param> /// <returns> /// The return value of the module. /// </returns> JavaScriptValueSafeHandle JsModuleEvaluation(JavaScriptModuleRecord requestModule); /// <summary> /// Set host info for the specified module. /// </summary> /// <remarks> /// This is used for four things: /// 1. Setting up the callbacks for module loading - note these are actually /// set on the current Context not the module so only have to be set for /// the first root module in any given context. /// 2. Setting host defined info on a module record - can be anything that /// you wish to associate with your modules. /// 3. Setting a URL for a module to be used for stack traces/debugging - /// note this must be set before calling JsParseModuleSource on the module /// or it will be ignored. /// 4. Setting an exception on the module object - only relevant prior to it being Parsed. /// </remarks> /// <param name="requestModule"> /// The request module. /// </param> /// <param name="moduleHostInfo"> /// The type of host info to be set. /// </param> /// <param name="hostInfo"> /// The host info to be set. /// </param> void JsSetModuleHostInfo(JavaScriptModuleRecord requestModule, JavaScriptModuleHostInfoKind moduleHostInfo, IntPtr hostInfo); /// <summary> /// Retrieve the host info for the specified module. /// </summary> /// <remarks> /// This can used to retrieve info previously set with JsSetModuleHostInfo. /// </remarks> /// <param name="requestModule"> /// The request module. /// </param> /// <param name="moduleHostInfo"> /// The type of host info to be retrieved. /// </param> /// <returns> /// The retrieved host info for the module. /// </returns> IntPtr JsGetModuleHostInfo(JavaScriptModuleRecord requestModule, JavaScriptModuleHostInfoKind moduleHostInfo); /// <summary> /// Returns metadata relating to the exception that caused the runtime of the current context to be in the exception state and resets the exception state for that runtime. The metadata includes a reference to the exception itself. /// </summary> /// <remarks> /// If the runtime of the current context is not in an exception state, this API will return /// JsErrorInvalidArgument. If the runtime is disabled, this will return an exception /// indicating that the script was terminated, but it will not clear the exception (the /// exception will be cleared if the runtime is re-enabled using /// JsEnableRuntimeExecution). /// The metadata value is a javascript object with the following properties: exception, the /// thrown exception object; line, the 0 indexed line number where the exception was thrown; /// column, the 0 indexed column number where the exception was thrown; length, the /// source-length of the cause of the exception; source, a string containing the line of /// source code where the exception was thrown; and url, a string containing the name of /// the script file containing the code that threw the exception. /// Requires an active script context. /// </remarks> /// <returns> /// The exception metadata for the runtime of the current context. /// </returns> JavaScriptValueSafeHandle JsGetAndClearExceptionWithMetadata(); /// <summary> /// Create JavascriptString variable from ASCII or Utf8 string /// </summary> /// <remarks> /// Requires an active script context. /// Input string can be either ASCII or Utf8 /// </remarks> /// <param name="content"> /// Pointer to string memory. /// </param> /// <param name="length"> /// Number of bytes within the string /// </param> /// <returns> /// JsValueRef representing the JavascriptString /// </returns> JavaScriptValueSafeHandle JsCreateString(string content, ulong length); /// <summary> /// Create JavascriptString variable from Utf16 string /// </summary> /// <remarks> /// Requires an active script context. /// Expects Utf16 string /// </remarks> /// <param name="content"> /// Pointer to string memory. /// </param> /// <param name="length"> /// Number of characters within the string /// </param> /// <returns> /// JsValueRef representing the JavascriptString /// </returns> JavaScriptValueSafeHandle JsCreateStringUtf16(string content, ulong length); /// <summary> /// Write JavascriptString value into C string buffer (Utf8) /// </summary> /// <remarks> /// When size of the `buffer` is unknown, /// `buffer` argument can be nullptr. /// In that case, `length` argument will return the length needed. /// </remarks> /// <param name="value"> /// JavascriptString value /// </param> /// <param name="buffer"> /// Pointer to buffer /// </param> /// <param name="bufferSize"> /// Buffer size /// </param> /// <returns> /// Total number of characters needed or written /// </returns> ulong JsCopyString(JavaScriptValueSafeHandle value, byte[] buffer, ulong bufferSize); /// <summary> /// Write string value into Utf16 string buffer /// </summary> /// <remarks> /// When size of the `buffer` is unknown, /// `buffer` argument can be nullptr. /// In that case, `written` argument will return the length needed. /// when start is out of range or < 0, returns JsErrorInvalidArgument /// and `written` will be equal to 0. /// If calculated length is 0 (It can be due to string length or `start` /// and length combination), then `written` will be equal to 0 and call /// returns JsNoError /// </remarks> /// <param name="value"> /// JavascriptString value /// </param> /// <param name="start"> /// start offset of buffer /// </param> /// <param name="length"> /// length to be written /// </param> /// <param name="buffer"> /// Pointer to buffer /// </param> /// <returns> /// Total number of characters written /// </returns> ulong JsCopyStringUtf16(JavaScriptValueSafeHandle value, int start, int length, byte[] buffer); /// <summary> /// Parses a script and returns a function representing the script. /// </summary> /// <remarks> /// Requires an active script context. /// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. /// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, /// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. /// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source /// for better performance and smaller memory footprint. /// </remarks> /// <param name="script"> /// The script to run. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// </param> /// <param name="sourceUrl"> /// The location the script came from. /// </param> /// <param name="parseAttributes"> /// Attribute mask for parsing the script /// </param> /// <returns> /// The result of the compiled script. /// </returns> JavaScriptValueSafeHandle JsParse(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes); /// <summary> /// Executes a script. /// </summary> /// <remarks> /// Requires an active script context. /// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. /// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, /// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. /// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source /// for better performance and smaller memory footprint. /// </remarks> /// <param name="script"> /// The script to run. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// </param> /// <param name="sourceUrl"> /// The location the script came from /// </param> /// <param name="parseAttributes"> /// Attribute mask for parsing the script /// </param> /// <returns> /// The result of the script, if any. This parameter can be null. /// </returns> JavaScriptValueSafeHandle JsRun(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes); /// <summary> /// Creates the property ID associated with the name. /// </summary> /// <remarks> /// Property IDs are specific to a context and cannot be used across contexts. /// Requires an active script context. /// </remarks> /// <param name="name"> /// The name of the property ID to get or create. The name may consist of only digits. /// The string is expected to be ASCII / utf8 encoded. /// </param> /// <param name="length"> /// length of the name in bytes /// </param> /// <returns> /// The property ID in this runtime for the given name. /// </returns> JavaScriptPropertyIdSafeHandle JsCreatePropertyId(string name, ulong length); /// <summary> /// Copies the name associated with the property ID into a buffer. /// </summary> /// <remarks> /// Requires an active script context. /// When size of the `buffer` is unknown, /// `buffer` argument can be nullptr. /// `length` argument will return the size needed. /// </remarks> /// <param name="propertyId"> /// The property ID to get the name of. /// </param> /// <param name="buffer"> /// The buffer holding the name associated with the property ID, encoded as utf8 /// </param> /// <param name="bufferSize"> /// Size of the buffer. /// </param> /// <returns> /// NO DESCRIPTION PROVIDED /// </returns> ulong JsCopyPropertyId(JavaScriptPropertyIdSafeHandle propertyId, byte[] buffer, ulong bufferSize); /// <summary> /// Serializes a parsed script to a buffer than can be reused. /// </summary> /// <remarks> /// JsSerializeScript parses a script and then stores the parsed form of the script in a /// runtime-independent format. The serialized script then can be deserialized in any /// runtime without requiring the script to be re-parsed. /// Requires an active script context. /// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. /// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, /// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. /// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source /// for better performance and smaller memory footprint. /// </remarks> /// <param name="script"> /// The script to serialize /// </param> /// <param name="parseAttributes"> /// Encoding for the script. /// </param> /// <returns> /// ArrayBuffer /// </returns> JavaScriptValueSafeHandle JsSerialize(JavaScriptValueSafeHandle script, JavaScriptParseScriptAttributes parseAttributes); /// <summary> /// Parses a serialized script and returns a function representing the script. Provides the ability to lazy load the script source only if/when it is needed. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="buffer"> /// The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer). /// </param> /// <param name="scriptLoadCallback"> /// Callback called when the source code of the script needs to be loaded. /// This is an optional parameter, set to null if not needed. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// This context will passed into scriptLoadCallback. /// </param> /// <param name="sourceUrl"> /// The location the script came from. /// </param> /// <returns> /// A function representing the script code. /// </returns> JavaScriptValueSafeHandle JsParseSerialized(JavaScriptValueSafeHandle buffer, JavaScriptSerializedLoadScriptCallback scriptLoadCallback, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl); /// <summary> /// Runs a serialized script. Provides the ability to lazy load the script source only if/when it is needed. /// </summary> /// <remarks> /// Requires an active script context. /// The runtime will detach the data from the buffer and hold on to it until all /// instances of any functions created from the buffer are garbage collected. /// </remarks> /// <param name="buffer"> /// The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer). /// </param> /// <param name="scriptLoadCallback"> /// Callback called when the source code of the script needs to be loaded. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// This context will passed into scriptLoadCallback. /// </param> /// <param name="sourceUrl"> /// The location the script came from. /// </param> /// <returns> /// The result of running the script, if any. This parameter can be null. /// </returns> JavaScriptValueSafeHandle JsRunSerialized(JavaScriptValueSafeHandle buffer, JavaScriptSerializedLoadScriptCallback scriptLoadCallback, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl); /// <summary> /// Gets the state of a given Promise object. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="promise"> /// The Promise object. /// </param> /// <returns> /// The current state of the Promise. /// </returns> JavaScriptPromiseState JsGetPromiseState(JavaScriptValueSafeHandle promise); /// <summary> /// Gets the result of a given Promise object. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="promise"> /// The Promise object. /// </param> /// <returns> /// The result of the Promise. /// </returns> JavaScriptValueSafeHandle JsGetPromiseResult(JavaScriptValueSafeHandle promise); /// <summary> /// Creates a new JavaScript Promise object. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="resolveFunction"> /// The function called to resolve the created Promise object. /// </param> /// <param name="rejectFunction"> /// The function called to reject the created Promise object. /// </param> /// <returns> /// The new Promise object. /// </returns> JavaScriptValueSafeHandle JsCreatePromise(out JavaScriptValueSafeHandle resolveFunction, out JavaScriptValueSafeHandle rejectFunction); /// <summary> /// Creates a weak reference to a value. /// </summary> /// <param name="value"> /// The value to be referenced. /// </param> /// <returns> /// Weak reference to the value. /// </returns> JavaScriptWeakReferenceSafeHandle JsCreateWeakReference(JavaScriptValueSafeHandle value); /// <summary> /// Gets a strong reference to the value referred to by a weak reference. /// </summary> /// <param name="weakRef"> /// A weak reference. /// </param> /// <returns> /// Reference to the value, or JS_INVALID_REFERENCE if the value is /// no longer available. /// </returns> JavaScriptValueSafeHandle JsGetWeakReferenceValue(JavaScriptWeakReferenceSafeHandle weakRef); /// <summary> /// Creates a Javascript SharedArrayBuffer object with shared content get from JsGetSharedArrayBufferContent. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="sharedContents"> /// The storage object of a SharedArrayBuffer which can be shared between multiple thread. /// </param> /// <returns> /// The new SharedArrayBuffer object. /// </returns> JavaScriptValueSafeHandle JsCreateSharedArrayBufferWithSharedContent(IntPtr sharedContents); /// <summary> /// Get the storage object from a SharedArrayBuffer. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="sharedArrayBuffer"> /// The SharedArrayBuffer object. /// </param> /// <returns> /// The storage object of a SharedArrayBuffer which can be shared between multiple thread. /// User should call JsReleaseSharedArrayBufferContentHandle after finished using it. /// </returns> IntPtr JsGetSharedArrayBufferContent(JavaScriptValueSafeHandle sharedArrayBuffer); /// <summary> /// Decrease the reference count on a SharedArrayBuffer storage object. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="sharedContents"> /// The storage object of a SharedArrayBuffer which can be shared between multiple thread. /// </param> void JsReleaseSharedArrayBufferContentHandle(IntPtr sharedContents); /// <summary> /// Determines whether an object has a non-inherited property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that may contain the property. /// </param> /// <param name="propertyId"> /// The ID of the property. /// </param> /// <returns> /// Whether the object has the non-inherited property. /// </returns> bool JsHasOwnProperty(JavaScriptValueSafeHandle @object, JavaScriptPropertyIdSafeHandle propertyId); /// <summary> /// Write JS string value into char string buffer without a null terminator /// </summary> /// <remarks> /// When size of the `buffer` is unknown, /// `buffer` argument can be nullptr. /// In that case, `written` argument will return the length needed. /// When start is out of range or < 0, returns JsErrorInvalidArgument /// and `written` will be equal to 0. /// If calculated length is 0 (It can be due to string length or `start` /// and length combination), then `written` will be equal to 0 and call /// returns JsNoError /// The JS string `value` will be converted one utf16 code point at a time, /// and if it has code points that do not fit in one byte, those values /// will be truncated. /// </remarks> /// <param name="value"> /// JavascriptString value /// </param> /// <param name="start"> /// Start offset of buffer /// </param> /// <param name="length"> /// Number of characters to be written /// </param> /// <param name="buffer"> /// Pointer to buffer /// </param> /// <returns> /// Total number of characters written /// </returns> ulong JsCopyStringOneByte(JavaScriptValueSafeHandle value, int start, int length, byte[] buffer); /// <summary> /// Obtains frequently used properties of a data view. /// </summary> /// <param name="dataView"> /// The data view instance. /// </param> /// <param name="byteOffset"> /// The offset in bytes from the start of arrayBuffer referenced by the array. /// </param> /// <param name="byteLength"> /// The number of bytes in the array. /// </param> /// <returns> /// The ArrayBuffer backstore of the view. /// </returns> JavaScriptValueSafeHandle JsGetDataViewInfo(JavaScriptValueSafeHandle dataView, out uint byteOffset, out uint byteLength); /// <summary> /// Determine if one JavaScript value is less than another JavaScript value. /// </summary> /// <remarks> /// This function is equivalent to the < operator in Javascript. /// Requires an active script context. /// </remarks> /// <param name="object1"> /// The first object to compare. /// </param> /// <param name="object2"> /// The second object to compare. /// </param> /// <returns> /// Whether object1 is less than object2. /// </returns> bool JsLessThan(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2); /// <summary> /// Determine if one JavaScript value is less than or equal to another JavaScript value. /// </summary> /// <remarks> /// This function is equivalent to the <= operator in Javascript. /// Requires an active script context. /// </remarks> /// <param name="object1"> /// The first object to compare. /// </param> /// <param name="object2"> /// The second object to compare. /// </param> /// <returns> /// Whether object1 is less than or equal to object2. /// </returns> bool JsLessThanOrEqual(JavaScriptValueSafeHandle object1, JavaScriptValueSafeHandle object2); /// <summary> /// Creates a new object (with prototype) that stores some external data. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="data"> /// External data that the object will represent. May be null. /// </param> /// <param name="finalizeCallback"> /// A callback for when the object is finalized. May be null. /// </param> /// <param name="prototype"> /// Prototype object or nullptr. /// </param> /// <returns> /// The new object. /// </returns> JavaScriptValueSafeHandle JsCreateExternalObjectWithPrototype(IntPtr data, JavaScriptObjectFinalizeCallback finalizeCallback, JavaScriptValueSafeHandle prototype); /// <summary> /// Gets an object's property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that contains the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <returns> /// The value of the property. /// </returns> JavaScriptValueSafeHandle JsObjectGetProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key); /// <summary> /// Puts an object's property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that contains the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <param name="value"> /// The new value of the property. /// </param> /// <param name="useStrictRules"> /// The property set should follow strict mode rules. /// </param> void JsObjectSetProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, JavaScriptValueSafeHandle value, bool useStrictRules); /// <summary> /// Determines whether an object has a property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that may contain the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <returns> /// Whether the object (or a prototype) has the property. /// </returns> bool JsObjectHasProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key); /// <summary> /// Defines a new object's own property from a property descriptor. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that has the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <param name="propertyDescriptor"> /// The property descriptor. /// </param> /// <returns> /// Whether the property was defined. /// </returns> bool JsObjectDefineProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, JavaScriptValueSafeHandle propertyDescriptor); /// <summary> /// Deletes an object's property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that contains the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <param name="useStrictRules"> /// The property set should follow strict mode rules. /// </param> /// <returns> /// Whether the property was deleted. /// </returns> JavaScriptValueSafeHandle JsObjectDeleteProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key, bool useStrictRules); /// <summary> /// Gets a property descriptor for an object's own property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that has the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <returns> /// The property descriptor. /// </returns> JavaScriptValueSafeHandle JsObjectGetOwnPropertyDescriptor(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key); /// <summary> /// Determines whether an object has a non-inherited property. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="@object"> /// The object that may contain the property. /// </param> /// <param name="key"> /// The key (JavascriptString or JavascriptSymbol) to the property. /// </param> /// <returns> /// Whether the object has the non-inherited property. /// </returns> bool JsObjectHasOwnProperty(JavaScriptValueSafeHandle @object, JavaScriptValueSafeHandle key); /// <summary> /// Sets whether any action should be taken when a promise is rejected with no reactions or a reaction is added to a promise that was rejected before it had reactions. By default in either of these cases nothing occurs. This function allows you to specify if something should occur and provide a callback to implement whatever should occur. /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="promiseRejectionTrackerCallback"> /// The callback function being set. /// </param> /// <param name="callbackState"> /// User provided state that will be passed back to the callback. /// </param> void JsSetHostPromiseRejectionTracker(JavaScriptPromiseRejectionTrackerCallback promiseRejectionTrackerCallback, IntPtr callbackState); /// <summary> /// Retrieve the namespace object for a module. /// </summary> /// <remarks> /// Requires an active script context and that the module has already been evaluated. /// </remarks> /// <param name="requestModule"> /// The JsModuleRecord for which the namespace is being requested. /// </param> /// <returns> /// A JsValueRef - the requested namespace object. /// </returns> JavaScriptValueSafeHandle JsGetModuleNamespace(JavaScriptModuleRecord requestModule); /// <summary> /// Determines if a provided object is a JavscriptProxy Object and provides references to a Proxy's target and handler. /// </summary> /// <remarks> /// Requires an active script context. /// If object is not a Proxy object the target and handler parameters are not touched. /// If nullptr is supplied for target or handler the function returns after /// setting the isProxy value. /// If the object is a revoked Proxy target and handler are set to JS_INVALID_REFERENCE. /// If it is a Proxy object that has not been revoked target and handler are set to the /// the object's target and handler. /// </remarks> /// <param name="@object"> /// The object that may be a Proxy. /// </param> /// <param name="target"> /// Pointer to a JsValueRef - the object's target. /// </param> /// <param name="handler"> /// Pointer to a JsValueRef - the object's handler. /// </param> /// <returns> /// Pointer to a Boolean - is the object a proxy? /// </returns> bool JsGetProxyProperties(JavaScriptValueSafeHandle @object, out JavaScriptValueSafeHandle target, out JavaScriptValueSafeHandle handler); /// <summary> /// Parses a script and stores the generated parser state cache into a buffer which can be reused. /// </summary> /// <remarks> /// JsSerializeParserState parses a script and then stores a cache of the parser state /// in a runtime-independent format. The parser state may be deserialized in any runtime along /// with the same script to skip the initial parse phase. /// Requires an active script context. /// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. /// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, /// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. /// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source /// for better performance and smaller memory footprint. /// </remarks> /// <param name="scriptVal"> /// The script to parse. /// </param> /// <param name="parseAttributes"> /// Encoding for the script. /// </param> /// <returns> /// The buffer to put the serialized parser state cache into. /// </returns> JavaScriptValueSafeHandle JsSerializeParserState(JavaScriptValueSafeHandle scriptVal, JavaScriptParseScriptAttributes parseAttributes); /// <summary> /// Deserializes the cache of initial parser state and (along with the same script source) executes the script and returns the result. /// </summary> /// <remarks> /// Requires an active script context. /// Script source can be either JavascriptString or JavascriptExternalArrayBuffer. /// In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16, /// JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes. /// Use JavascriptExternalArrayBuffer with Utf8/ASCII script source /// for better performance and smaller memory footprint. /// </remarks> /// <param name="script"> /// The script to run. /// </param> /// <param name="sourceContext"> /// A cookie identifying the script that can be used by debuggable script contexts. /// </param> /// <param name="sourceUrl"> /// The location the script came from /// </param> /// <param name="parseAttributes"> /// Attribute mask for parsing the script /// </param> /// <param name="parserState"> /// A buffer containing a cache of the parser state generated by JsSerializeParserState. /// </param> /// <returns> /// The result of the script, if any. This parameter can be null. /// </returns> JavaScriptValueSafeHandle JsRunScriptWithParserState(JavaScriptValueSafeHandle script, JavaScriptSourceContext sourceContext, JavaScriptValueSafeHandle sourceUrl, JavaScriptParseScriptAttributes parseAttributes, JavaScriptValueSafeHandle parserState); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //Inner Product of two 2D array using System; public class ArrayClass { public int[,] a2d; public int[,,] a3d; public ArrayClass(int size) { a2d = new int[size, size]; a3d = new int[size, size, size]; } } public class intmm { public static int size; public static Random rand; public static ArrayClass ima; public static ArrayClass imb; public static ArrayClass imr; public static void Init2DMatrix(out ArrayClass m, out int[][] refm) { int i, j, temp; i = 0; //m = new int[size, size]; m = new ArrayClass(size); refm = new int[size][]; for (int k = 0; k < refm.Length; k++) refm[k] = new int[size]; while (i < size) { j = 0; while (j < size) { temp = rand.Next(); m.a2d[i, j] = temp - (temp / 120) * 120 - 60; refm[i][j] = temp - (temp / 120) * 120 - 60; j++; } i++; } } public static void InnerProduct2D(out int res, ref ArrayClass a2d, ref ArrayClass b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a2d.a2d[row, i] * b.a2d[i, col]; i++; } } public static void InnerProduct2DRef(out int res, ref int[][] a2d, ref int[][] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a2d[row][i] * b[i][col]; i++; } } public static void Init3DMatrix(ArrayClass m, int[][] refm) { int i, j, temp; i = 0; while (i < size) { j = 0; while (j < size) { temp = rand.Next(); m.a3d[i, j, 0] = temp - (temp / 120) * 120 - 60; refm[i][j] = temp - (temp / 120) * 120 - 60; j++; } i++; } } public static void InnerProduct3D(out int res, ArrayClass a3d, ArrayClass b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a3d.a3d[row, i, 0] * b.a3d[i, col, 0]; i++; } } public static void InnerProduct3DRef(out int res, int[][] a3d, int[][] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a3d[row][i] * b[i][col]; i++; } } public static int Main() { bool pass = false; rand = new Random(); size = rand.Next(2, 10); Console.WriteLine(); Console.WriteLine("2D Array"); Console.WriteLine("Testing inner product of {0} by {0} matrices", size); Console.WriteLine("the matrices are members of class"); Console.WriteLine("Matrix element stores random integer"); Console.WriteLine("array set/get, ref/out param are used"); ima = new ArrayClass(size); imb = new ArrayClass(size); imr = new ArrayClass(size); int[][] refa2d = new int[size][]; int[][] refb2d = new int[size][]; int[][] refr2d = new int[size][]; for (int k = 0; k < refr2d.Length; k++) refr2d[k] = new int[size]; Init2DMatrix(out ima, out refa2d); Init2DMatrix(out imb, out refb2d); int m = 0; int n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct2D(out imr.a2d[m, n], ref ima, ref imb, m, n); InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr.a2d[i, j] != refr2d[i][j]) { Console.WriteLine("i={0}, j={1}, imr.a2d[i,j] {2}!=refr2d[i][j] {3}", i, j, imr.a2d[i, j], refr2d[i][j]); pass = false; } } Console.WriteLine(); Console.WriteLine("3D Array"); Console.WriteLine("Testing inner product of one slice of two {0} by {0} by {0} matrices", size); Console.WriteLine("the matrices are members of class and matrix element stores random integer"); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) imr.a3d[i, j, 0] = 1; int[][] refa3d = new int[size][]; int[][] refb3d = new int[size][]; int[][] refr3d = new int[size][]; for (int k = 0; k < refa3d.Length; k++) refa3d[k] = new int[size]; for (int k = 0; k < refb3d.Length; k++) refb3d[k] = new int[size]; for (int k = 0; k < refr3d.Length; k++) refr3d[k] = new int[size]; Init3DMatrix(ima, refa3d); Init3DMatrix(imb, refb3d); m = 0; n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct3D(out imr.a3d[m, n, 0], ima, imb, m, n); InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr.a3d[i, j, 0] != refr3d[i][j]) { Console.WriteLine("i={0}, j={1}, imr.a3d[i,j,0] {2}!=refr3d[i][j] {3}", i, j, imr.a3d[i, j, 0], refr3d[i][j]); pass = false; } } Console.WriteLine(); if (pass) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Hydra.Framework; namespace Hydra.SharedCache.Common { // // ********************************************************************** /// <summary> /// Logic within this class maintains cache data and statistics, like increasing key /// hit counts this is used in case the cache reaches its maximum memory capacity /// </summary> // ********************************************************************** // [Serializable] public class CacheCleanup { // // ********************************************************************** /// <summary> /// needed for lock(){} operations /// </summary> // ********************************************************************** // private static object bulkObject = new object(); private Enums.ServiceCacheCleanUp cleanupCacheConfiguration = Enums.ServiceCacheCleanUp.CACHEITEMPRIORITY; // // ********************************************************************** /// <summary> /// Gets/sets the CleanupCacheConfiguration /// Defines the cleanup cache configuration, the default value is CACHEITEMPRIORITY [check <see cref="Enums.ServiceCacheCleanUp"/> for more information] /// </summary> // ********************************************************************** // public Enums.ServiceCacheCleanUp CleanupCacheConfiguration { [System.Diagnostics.DebuggerStepThrough] get { return this.cleanupCacheConfiguration; } [System.Diagnostics.DebuggerStepThrough] set { this.cleanupCacheConfiguration = value; } } private long cacheAmountOfObjects = -1; // // ********************************************************************** /// <summary> /// Gets the CacheAmountOfObjects (extern readonly) /// </summary> // ********************************************************************** // public long CacheAmountOfObjects { [System.Diagnostics.DebuggerStepThrough] get { return this.cacheAmountOfObjects; } } private long cacheFillFactor = 90; // // ********************************************************************** /// <summary> /// Gets/sets the CacheFillFactor /// </summary> // ********************************************************************** // public long CacheFillFactor { [System.Diagnostics.DebuggerStepThrough] get { return this.cacheFillFactor; } } private bool purgeIsRunning; // // ********************************************************************** /// <summary> /// Gets the PurgeIsRunning /// </summary> // ********************************************************************** // public bool PurgeIsRunning { [System.Diagnostics.DebuggerStepThrough] get { return this.purgeIsRunning; } } private Dictionary<string, Cleanup> cleanupDict; // // ********************************************************************** /// <summary> /// Gets the cleanup list. /// </summary> /// <value>The cleanup list.</value> // ********************************************************************** // public Dictionary<string, Cleanup> CleanupDict { [System.Diagnostics.DebuggerStepThrough] get { if (this.cleanupDict == null) { this.cleanupDict = new Dictionary<string, Cleanup>(); } return this.cleanupDict; } } #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="CacheCleanup"/> class. /// </summary> // ********************************************************************** // public CacheCleanup() { Log.Entry(); try { this.cleanupCacheConfiguration = Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.ServiceCacheCleanup; } catch (Exception ex) { string msg = @"Configuration failure, please validate your [ServiceCacheCleanUp] key, it contains an invalid value!! Current configured value: {0}; As standard the CACHEITEMPRIORITY has been set."; Log.Error(string.Format(msg, Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.ServiceCacheCleanup), ex); this.cleanupCacheConfiguration = Enums.ServiceCacheCleanUp.LRU; } try { this.cacheAmountOfObjects = long.Parse(Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects.ToString()) * (1024 * 1024); } catch (Exception ex) { string msg = @"Configuration failure, please validate your [CacheAmountOfObjects] key, it contains an invalid value!! Current configured value: {0}; standard taken, value:-1. You may explorer now OutOfMemoryExceptions in your log files."; Log.Error(string.Format(msg, Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects), ex); } try { this.cacheFillFactor = long.Parse(Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.CacheAmountFillFactorInPercentage.ToString()); } catch (Exception ex) { string msg = @"Configuration failure, please validate your [CacheAmountFillFactorInPercentage] key, it contains an invalid value!! Current configured value: {0}; standard taken, value:90."; Log.Error(string.Format(msg, Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.CacheAmountFillFactorInPercentage), ex); this.cacheFillFactor = 90; } Log.Exit(); } #endregion #region Methods // // ********************************************************************** /// <summary> /// checksum for Hybrid cache clearup, makes a recursive call /// until it receives a smaller value then: 100000 /// </summary> /// <param name="para">The para.</param> /// <returns>a smaller value then: 100000</returns> // ********************************************************************** // public static long HybridChecksum(long para) { if (para < 100000) return para; return HybridChecksum(para / 100000) + para % 100000; } // // ********************************************************************** /// <summary> /// Calculates the hybrid checksum, this is used to /// create rate for every specific object in the cache /// based on various object attributes. /// <remarks> /// The calculate done like this: HybridChecksum((c.HitRatio + ((c.ObjectSize / 1024) + (c.Span.Ticks / 1024) + (c.UsageDatetime.Ticks / 1024)))); /// </remarks> /// </summary> /// <param name="c">an object of type <see cref="Cleanup"/></param> /// <param name="currentConfiguration">The current configuration.</param> /// <returns>a rate as <see cref="long"/></returns> // ********************************************************************** // public static long CalculateHybridChecksum(Cleanup c, Enums.ServiceCacheCleanUp currentConfiguration) { // // do not make Hybrid calculations on other cleanup strategy - boost performance // if (currentConfiguration == Enums.ServiceCacheCleanUp.HYBRID) { return HybridChecksum((c.HitRatio + ((c.ObjectSize / 1024) + (c.Span.Ticks / 1024) + (c.UsageDatetime.Ticks / 1024)))); } else { return 0; } } // // ********************************************************************** /// <summary> /// Updates the specified msg or its updating the available record if its already added. /// </summary> /// <param name="msg">The MSG.</param> // ********************************************************************** // public void Update(LBSMessage msg) { lock (bulkObject) { Cleanup c = null; if (this.CleanupDict.ContainsKey(msg.Key)) { c = this.CleanupDict[msg.Key]; // // update // if (msg.Payload != null) { c.ObjectSize = msg.Payload.Length == 1 ? c.ObjectSize : msg.Payload.Length; } else { c.ObjectSize = 0; } c.Prio = msg.ItemPriority; c.HitRatio += 1; c.HybridPoint = CalculateHybridChecksum(c, this.CleanupCacheConfiguration); c.Span = msg.Expires.Subtract(DateTime.Now); c.UsageDatetime = DateTime.Now; } else { // // add // object is not available, create a new instance / calculations / and add it to the list. // Cleanup cleanup = new Cleanup(msg.Key, msg.ItemPriority, msg.Expires.Subtract(DateTime.Now), 0, DateTime.Now, msg.Payload != null ? msg.Payload.Length : 0, 0); cleanup.HybridPoint = CalculateHybridChecksum(cleanup, this.CleanupCacheConfiguration); this.CleanupDict[msg.Key] = cleanup; } } } // // ********************************************************************** /// <summary> /// Gets the access stat list. /// </summary> /// <returns></returns> // ********************************************************************** // public Dictionary<string, long> GetAccessStatList() { Dictionary<string, long> result = new Dictionary<string, long>(); List<Cleanup> cleanupCopy = null; lock (bulkObject) { cleanupCopy = new List<Cleanup>(this.CleanupDict.Values); } Cleanup.Sorting = Cleanup.SortingOrder.Desc; cleanupCopy.Sort(Cleanup.CacheItemHitRatio); int i = 0; foreach (Cleanup c in cleanupCopy) { result.Add(c.Key, c.HitRatio); // // do not send back more then 20 keys // if (++i == 20) break; } return result; } // // ********************************************************************** /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> // ********************************************************************** // public void Remove(string key) { lock (bulkObject) { if (this.CleanupDict.ContainsKey(key)) { this.CleanupDict.Remove(key); } } GC.WaitForPendingFinalizers(); } // // ********************************************************************** /// <summary> /// Clears this instance. /// </summary> // ********************************************************************** // public void Clear() { lock (bulkObject) { this.CleanupDict.Clear(); } GC.Collect(); } // // ********************************************************************** /// <summary> /// Purges this instance, free memory /// step 1: sort list based on requested configuration /// step 2: start to remove items from the list. /// </summary> /// <param name="actualCacheSize">Actual size of the cache.</param> /// <returns></returns> // ********************************************************************** // public List<string> Purge(long actualCacheSize) { lock (bulkObject) { // // do not run purge concurrently, there we need to // maintain a status if purge is running // if (this.purgeIsRunning) return null; // // set the flag to prevent additional threads to access // and to wait for the following lock. // this.purgeIsRunning = true; } List<string> removeObjectKeys = new List<string>(); List<Cleanup> removeObjectValues; lock (bulkObject) { removeObjectValues = new List<Cleanup>(this.CleanupDict.Values); } lock (bulkObject) { try { // // sort list based on requested configuration before it // starts to purge objects from the cache // switch (this.cleanupCacheConfiguration) { case Enums.ServiceCacheCleanUp.LRU: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemUsageDateTime); break; case Enums.ServiceCacheCleanUp.LFU: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemHitRatio); break; case Enums.ServiceCacheCleanUp.TIMEBASED: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemTimeSpan); break; case Enums.ServiceCacheCleanUp.SIZE: Cleanup.Sorting = Cleanup.SortingOrder.Desc; removeObjectValues.Sort(Cleanup.CacheItemObjectSize); break; case Enums.ServiceCacheCleanUp.LLF: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemObjectSize); break; case Enums.ServiceCacheCleanUp.HYBRID: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemHybridPoints); break; default: Cleanup.Sorting = Cleanup.SortingOrder.Asc; removeObjectValues.Sort(Cleanup.CacheItemPriority); break; } do { // // store a list to delete it afterwards from the Cache itself // removeObjectKeys.Add(removeObjectValues[0].Key); // // calcualte actual cache size // actualCacheSize -= removeObjectValues[0].ObjectSize; // // phisically remove it // this.CleanupDict.Remove(removeObjectValues[0].Key); } while (!((actualCacheSize * this.cacheFillFactor / this.cacheAmountOfObjects) < this.cacheFillFactor)); } finally { this.purgeIsRunning = false; } } return removeObjectKeys; } #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.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal sealed partial class PkcsPalWindows : PkcsPal { internal PkcsPalWindows() { } public sealed override DecryptorPal Decode(byte[] encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes) { return DecryptorPalWindows.Decode(encodedMessage, out version, out contentInfo, out contentEncryptionAlgorithm, out originatorCerts, out unprotectedAttributes); } public sealed override byte[] EncodeOctetString(byte[] octets) { unsafe { fixed (byte* pOctets = octets) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pOctets, (uint)(octets.Length)); return Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } public sealed override byte[] DecodeOctetString(byte[] encodedOctets) { using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OCTET_STRING, encodedOctets)) { unsafe { DATA_BLOB blob = *(DATA_BLOB*)(sh.DangerousGetHandle()); return blob.ToByteArray(); } } } public sealed override byte[] EncodeUtcTime(DateTime utcTime) { long ft; try { ft = utcTime.ToFileTimeUtc(); } catch (ArgumentException ex) { throw new CryptographicException(ex.Message, ex); } unsafe { return Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.PKCS_UTC_TIME, &ft); } } public sealed override DateTime DecodeUtcTime(byte[] encodedUtcTime) { long signingTime = 0; unsafe { fixed (byte* pEncodedUtcTime = encodedUtcTime) { int cbSize = sizeof(long); if (!Interop.Crypt32.CryptDecodeObject(CryptDecodeObjectStructType.PKCS_UTC_TIME, (IntPtr)pEncodedUtcTime, encodedUtcTime.Length, &signingTime, ref cbSize)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } } return DateTime.FromFileTimeUtc(signingTime); } public sealed override string DecodeOid(byte[] encodedOid) { using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OBJECT_IDENTIFIER, encodedOid)) { unsafe { IntPtr pOidValue = *(IntPtr*)(sh.DangerousGetHandle()); string contentType = pOidValue.ToStringAnsi(); return contentType; } } } public sealed override Oid GetEncodedMessageType(byte[] encodedMessage) { using (SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) { if (hCryptMsg == null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedMessage, encodedMessage.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); int msgTypeAsInt; int cbSize = sizeof(int); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_TYPE_PARAM, 0, out msgTypeAsInt, ref cbSize)) throw Marshal.GetLastWin32Error().ToCryptographicException(); CryptMsgType msgType = (CryptMsgType)msgTypeAsInt; switch (msgType) { case CryptMsgType.CMSG_DATA: return Oid.FromOidValue(Oids.Pkcs7Data, OidGroup.ExtensionOrAttribute); case CryptMsgType.CMSG_SIGNED: return Oid.FromOidValue(Oids.Pkcs7Signed, OidGroup.ExtensionOrAttribute); case CryptMsgType.CMSG_ENVELOPED: return Oid.FromOidValue(Oids.Pkcs7Enveloped, OidGroup.ExtensionOrAttribute); case CryptMsgType.CMSG_SIGNED_AND_ENVELOPED: return Oid.FromOidValue(Oids.Pkcs7SignedEnveloped, OidGroup.ExtensionOrAttribute); case CryptMsgType.CMSG_HASHED: return Oid.FromOidValue(Oids.Pkcs7Hashed, OidGroup.ExtensionOrAttribute); case CryptMsgType.CMSG_ENCRYPTED: return Oid.FromOidValue(Oids.Pkcs7Encrypted, OidGroup.ExtensionOrAttribute); default: throw ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); } } } public sealed override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs) { certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: true)); certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: true)); } public sealed override Exception CreateRecipientsNotFoundException() { return ErrorCode.CRYPT_E_RECIPIENT_NOT_FOUND.ToCryptographicException(); } public sealed override Exception CreateRecipientInfosAfterEncryptException() { return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); } public sealed override Exception CreateDecryptAfterEncryptException() { return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); } public sealed override Exception CreateDecryptTwiceException() { return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); } public sealed override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate) { using (SafeCertContextHandle hCertContext = certificate.CreateCertContextHandle()) { byte[] ski = hCertContext.GetSubjectKeyIdentifer(); return ski; } } public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) { return GetPrivateKey<T>(certificate, silent, preferNCrypt: true); } public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) { return GetPrivateKey<T>(certificate, silent, preferNCrypt: false); } private T GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm { if (!certificate.HasPrivateKey) { return null; } SafeProvOrNCryptKeyHandle handle = GetCertificatePrivateKey( certificate, silent, preferNCrypt, out CryptKeySpec keySpec, out Exception exception); using (handle) { if (handle == null || handle.IsInvalid) { if (exception != null) { throw exception; } return null; } if (keySpec == CryptKeySpec.CERT_NCRYPT_KEY_SPEC) { using (SafeNCryptKeyHandle keyHandle = new SafeNCryptKeyHandle(handle.DangerousGetHandle(), handle)) { CngKeyHandleOpenOptions options = CngKeyHandleOpenOptions.None; byte clrIsEphemeral = 0; Interop.NCrypt.ErrorCode errorCode = Interop.NCrypt.NCryptGetByteProperty(keyHandle, "CLR IsEphemeral", ref clrIsEphemeral, CngPropertyOptions.CustomProperty); if (errorCode == Interop.NCrypt.ErrorCode.ERROR_SUCCESS && clrIsEphemeral == 1) { options |= CngKeyHandleOpenOptions.EphemeralKey; } using (CngKey cngKey = CngKey.Open(keyHandle, options)) { if (typeof(T) == typeof(RSA)) return (T)(object)new RSACng(cngKey); if (typeof(T) == typeof(ECDsa)) return (T)(object)new ECDsaCng(cngKey); if (typeof(T) == typeof(DSA)) return (T)(object)new DSACng(cngKey); Debug.Fail($"Unknown CNG key type request: {typeof(T).FullName}"); return null; } } } // The key handle is for CAPI. // Our CAPI types don't allow usage from a handle, so we have a few choices: // 1) Extract the information we need to re-open the key handle. // 2) Re-implement {R|D}SACryptoServiceProvider // 3) PNSE. // 4) Defer to cert.Get{R|D}SAPrivateKey if not silent, throw otherwise. CspParameters cspParams = handle.GetProvParameters(); Debug.Assert((cspParams.Flags & CspProviderFlags.UseExistingKey) != 0); cspParams.KeyNumber = (int)keySpec; if (silent) { cspParams.Flags |= CspProviderFlags.NoPrompt; } if (typeof(T) == typeof(RSA)) return (T)(object)new RSACryptoServiceProvider(cspParams); if (typeof(T) == typeof(DSA)) return (T)(object)new DSACryptoServiceProvider(cspParams); Debug.Fail($"Unknown CAPI key type request: {typeof(T).FullName}"); return null; } } internal static SafeProvOrNCryptKeyHandle GetCertificatePrivateKey( X509Certificate2 cert, bool silent, bool preferNCrypt, out CryptKeySpec keySpec, out Exception exception) { CryptAcquireCertificatePrivateKeyFlags flags = CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG | CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG; if (preferNCrypt) { flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG; } else { flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG; } if (silent) { flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG; } bool isNCrypt; bool mustFree; using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle()) { IntPtr hKey; int cbSize = IntPtr.Size; if (Interop.Crypt32.CertGetCertificateContextProperty( hCertContext, CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID, out hKey, ref cbSize)) { exception = null; keySpec = CryptKeySpec.CERT_NCRYPT_KEY_SPEC; return new SafeProvOrNCryptKeyHandleUwp(hKey, hCertContext); } if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey( hCertContext, flags, IntPtr.Zero, out hKey, out keySpec, out mustFree)) { exception = Marshal.GetHRForLastWin32Error().ToCryptographicException(); return null; } // We need to know whether we got back a CRYPTPROV or NCrypt handle. // Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP. // Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which // one we got through the keySpec value. switch (keySpec) { case CryptKeySpec.AT_KEYEXCHANGE: case CryptKeySpec.AT_SIGNATURE: isNCrypt = false; break; case CryptKeySpec.CERT_NCRYPT_KEY_SPEC: isNCrypt = true; break; default: // As of this writing, we've exhausted all the known values of keySpec. // We have no idea what kind of key handle we got so play it safe and fail fast. throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec)); } SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp( hKey, ownsHandle: mustFree, isNcrypt: isNCrypt); exception = null; return hProvOrNCryptKey; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class logTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunLogTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; BigInteger bi; // Log Method - Log(1,+Infinity) Assert.Equal(0, BigInteger.Log(1, double.PositiveInfinity)); // Log Method - Log(1,0) VerifyLogString("0 1 bLog"); // Log Method - Log(0, >1) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 10); VerifyLogString(Print(tempByteArray1) + "0 bLog"); } // Log Method - Log(0, 0>x>1) for (int i = 0; i < s_samples; i++) { Assert.Equal(double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble())); } // Log Method - base = 0 for (int i = 0; i < s_samples; i++) { bi = 1; while (bi == 1) { bi = new BigInteger(GetRandomPosByteArray(s_random, 8)); } Assert.True((double.IsNaN(BigInteger.Log(bi, 0)))); } // Log Method - base = 1 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyLogString("1 " + Print(tempByteArray1) + "bLog"); } // Log Method - base = NaN for (int i = 0; i < s_samples; i++) { Assert.True(double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), double.NaN))); } // Log Method - base = +Infinity for (int i = 0; i < s_samples; i++) { Assert.True(double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), double.PositiveInfinity))); } // Log Method - Log(0,1) VerifyLogString("1 0 bLog"); // Log Method - base < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 10); tempByteArray2 = GetRandomNegByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); Assert.True(double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble()))); } // Log Method - value < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomNegByteArray(s_random, 10); tempByteArray2 = GetRandomPosByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); } // Log Method - Small BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10)); double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - Large BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100))); double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 3); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - one small and one large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 1); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - two large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - Very Large BigInteger 1 << 128 << Int.MaxValue and 2 LargeValueLogTests(128, 1); } [Fact] [OuterLoop] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void RunLargeValueLogTests() { LargeValueLogTests(0, 4, 64, 3); } /// <summary> /// Test Log Method on Very Large BigInteger more than (1 &lt;&lt; Int.MaxValue) by base 2 /// Tested BigInteger are: pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit]) /// Note: /// ToString() can not operate such large values /// VerifyLogString() can not operate such large values, /// Math.Log() can not operate such large values /// </summary> private static void LargeValueLogTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1) { BigInteger init = BigInteger.One << startShift; double logbase = 2D; for (int i = 0; i < smallShiftLoopLimit; i++) { BigInteger temp = init << ((i + 1) * smallShift); for (int j = 0; j<bigShiftLoopLimit; j++) { temp = temp << (int.MaxValue / 10); double expected = (double)startShift + smallShift * (double)(i + 1) + (int.MaxValue / 10) * (double)(j + 1); Assert.True(ApproxEqual(BigInteger.Log(temp, logbase), expected)); } } } private static void VerifyLogString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; i++) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static string Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } private static bool ApproxEqual(double value1, double value2) { //Special case values; if (double.IsNaN(value1)) { return double.IsNaN(value2); } if (double.IsNegativeInfinity(value1)) { return double.IsNegativeInfinity(value2); } if (double.IsPositiveInfinity(value1)) { return double.IsPositiveInfinity(value2); } if (value2 == 0) { return (value1 == 0); } double result = Math.Abs((value1 / value2) - 1); return (result <= double.Parse("1e-15")); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Text; using System.Windows.Forms; namespace AxiomCoders.PdfTemplateEditor.Controls { class ColorSlider : LabelRotate { public event EventHandler SelectedValueChanged; Orientation m_orientation = Orientation.Vertical; public Orientation Orientation { get { return m_orientation; } set { m_orientation = value; } } public enum eNumberOfColors { Use2Colors, Use3Colors, } eNumberOfColors m_numberOfColors = eNumberOfColors.Use3Colors; public eNumberOfColors NumberOfColors { get { return m_numberOfColors; } set { m_numberOfColors = value; } } public enum eValueOrientation { MinToMax, MaxToMin, } eValueOrientation m_valueOrientation = eValueOrientation.MinToMax; public eValueOrientation ValueOrientation { get { return m_valueOrientation; } set { m_valueOrientation = value; } } float m_percent = 0; public float Percent { get { return m_percent; } set { // ok so it is not really percent, but a value between 0 - 1. if (value < 0) value = 0; if (value > 1) value = 1; if (value != m_percent) { m_percent = value; if (SelectedValueChanged != null) SelectedValueChanged(this, null); Invalidate(); } } } Color m_color1 = Color.Black; Color m_color2 = Color.FromArgb(255,127,127,127); Color m_color3 = Color.White; public Color Color1 { get { return m_color1; } set { m_color1 = value; } } public Color Color2 { get { return m_color2; } set { m_color2 = value; } } public Color Color3 { get { return m_color3; } set { m_color3 = value; } } Padding m_barPadding = new Padding(12,5, 24, 10); public Padding BarPadding { get { return m_barPadding; } set { m_barPadding = value; Invalidate(); } } public ColorSlider() { } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); Invalidate(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); DrawColorBar(e.Graphics); if (Focused) { RectangleF lr = ClientRectangleF; lr.Inflate(-2,-2); ControlPaint.DrawFocusRectangle(e.Graphics, Util.Rect(lr)); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); PointF mousepoint = new PointF(e.X, e.Y); if (e.Button == MouseButtons.Left) SetPercent(mousepoint); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); Focus(); PointF mousepoint = new PointF(e.X, e.Y); if (e.Button == MouseButtons.Left) SetPercent(mousepoint); } protected override bool ProcessDialogKey(Keys keyData) { float percent = Percent * 100; int step = 0; if ((keyData & Keys.Up) == Keys.Up) step = 1; if ((keyData & Keys.Down) == Keys.Down) step = -1; if ((keyData & Keys.Control) == Keys.Control) step *= 5; if (step != 0) { SetPercent((float)Math.Round(percent + step)); return true; } return base.ProcessDialogKey(keyData); } protected virtual void SetPercent(float percent) { Percent = percent / 100; } protected virtual void SetPercent(PointF mousepoint) { RectangleF cr = ClientRectangleF; RectangleF br = BarRectangle; mousepoint.X += cr.X - br.X; mousepoint.Y += cr.Y - br.Y; Percent = GetPercentSet(BarRectangle, Orientation, mousepoint); Refresh(); } protected RectangleF BarRectangle { get { RectangleF r = ClientRectangle; r.X += BarPadding.Left; r.Width -= BarPadding.Right; r.Y += BarPadding.Top; r.Height -= BarPadding.Bottom; return r; } } protected float GetPercentSet(RectangleF r, Orientation orientation, PointF mousepoint) { float percentSet = 0; if (orientation == Orientation.Vertical) { if (m_valueOrientation == eValueOrientation.MaxToMin) percentSet = 1 - ((mousepoint.Y - r.Y / r.Height) / r.Height); else percentSet = mousepoint.Y / r.Height; } if (orientation == Orientation.Horizontal) if (m_valueOrientation == eValueOrientation.MaxToMin) percentSet = 1 - ((mousepoint.X - r.X / r.Width) / r.Width); else percentSet = (mousepoint.X / r.Width); if (percentSet < 0) percentSet = 0; if (percentSet > 100) percentSet = 100; return percentSet; } protected void DrawSelector(Graphics dc, RectangleF r, Orientation orientation, float percentSet) { Pen pen = new Pen(Color.CadetBlue); percentSet = Math.Max(0, percentSet); percentSet = Math.Min(1, percentSet); if (orientation == Orientation.Vertical) { float selectorY = (float)Math.Floor(r.Top + (r.Height - (r.Height * percentSet))); if (m_valueOrientation == eValueOrientation.MaxToMin) selectorY = (float)Math.Floor(r.Top + (r.Height - (r.Height * percentSet))); else selectorY = (float)Math.Floor(r.Top + (r.Height * percentSet)); dc.DrawLine(pen, r.X, selectorY, r.Right, selectorY); Image image = SelectorImages.Image(SelectorImages.eIndexes.Right); float xpos = r.Right; float ypos = selectorY - image.Height/2; dc.DrawImageUnscaled(image, (int)xpos, (int)ypos); image = SelectorImages.Image(SelectorImages.eIndexes.Left); xpos = r.Left - image.Width; dc.DrawImageUnscaled(image, (int)xpos, (int)ypos); } if (orientation == Orientation.Horizontal) { float selectorX = 0; if (m_valueOrientation == eValueOrientation.MaxToMin) selectorX = (float)Math.Floor(r.Left + (r.Width - (r.Width * percentSet))); else selectorX = (float)Math.Floor(r.Left + (r.Width * percentSet)); dc.DrawLine(pen, selectorX, r.Top, selectorX, r.Bottom); Image image = SelectorImages.Image(SelectorImages.eIndexes.Up); float xpos = selectorX - image.Width/2; float ypos = r.Bottom; dc.DrawImageUnscaled(image, (int)xpos, (int)ypos); image = SelectorImages.Image(SelectorImages.eIndexes.Down); ypos = r.Top - image.Height; dc.DrawImageUnscaled(image, (int)xpos, (int)ypos); } } protected void DrawColorBar(Graphics dc) { RectangleF lr = BarRectangle; if (m_numberOfColors == eNumberOfColors.Use2Colors) Util.Draw2ColorBar(dc, lr, Orientation, m_color1, m_color2); else Util.Draw3ColorBar(dc, lr, Orientation, m_color1, m_color2, m_color3); DrawSelector(dc, lr, Orientation, (float)Percent); } } class HSLColorSlider : ColorSlider { HSLColor m_selectedColor = new HSLColor(); public HSLColor SelectedHSLColor { get { return m_selectedColor; } set { if (m_selectedColor == value) return; m_selectedColor = value; value.Lightness = 0.5; Color2 = Color.FromArgb(255, value.Color); Percent = (float)m_selectedColor.Lightness; Refresh();//Invalidate(Util.Rect(BarRectangle)); } } protected override void SetPercent(PointF mousepoint) { base.SetPercent(mousepoint); m_selectedColor.Lightness = Percent; Refresh(); } protected override void SetPercent(float percent) { base.SetPercent(percent); m_selectedColor.Lightness = percent / 100; SelectedHSLColor = m_selectedColor; } } }
using DanielBogdan.PlainRSS.Core; using DanielBogdan.PlainRSS.Core.Domain; using DanielBogdan.PlainRSS.Core.DTOs; using DanielBogdan.PlainRSS.Core.Logging; using DanielBogdan.PlainRSS.Core.Theming; using DanielBogdan.PlainRSS.UI.WinAPI; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Forms; namespace DanielBogdan.PlainRSS.UI { public partial class MainForm : Form { private static readonly Logger Logger = new Logger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private Settings settings = new Settings(); private readonly PreviewForm previewForm = new PreviewForm(); private readonly BindingList<RssItem> rssItems = new BindingList<RssItem>(); private readonly List<string> userAgents = new List<string>(); private IList<Theme> themes; private Theme currentTheme; private RssListener listener = null; private bool isClosing = false; private int filteredCounter = 0; public MainForm() { InitializeComponent(); } #region Menu events /// <summary> /// About menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { var about = new About(); about.ShowDialog(this); } /// <summary> /// Exit menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exitToolStripMenuItem_Click(object sender, EventArgs e) { isClosing = true; Close(); } /// <summary> /// Clear items menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void clearToolStripMenuItem_Click(object sender, EventArgs e) { lock (rssItems) { rssItems.Clear(); filteredCounter = 0; } SetMainFormStatus(); } /// <summary> /// Configure menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void configureToolStripMenuItem_Click(object sender, EventArgs e) { var settingsForm = new SettingsForm { Settings = settings }; settingsForm.ShowDialog(this); CreateTrayContextMenu(); } /// <summary> /// start/stop the listener /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void startStopToolStripMenuItem_Click(object sender, EventArgs e) { if (listener.IsRunning()) { listener.Stop(); startStopToolStripMenuItem.Text = @"Start"; configureToolStripMenuItem.Enabled = true; } else { var ok = false; foreach (var rssCategory in settings.RssCategories) { foreach (var rssWebsite in rssCategory.RssWebsites) { if (rssWebsite.Enabled) { ok = true; break; } } } if (ok) { listener.Start(); startStopToolStripMenuItem.Text = @"Stop"; configureToolStripMenuItem.Enabled = false; } else MessageBox.Show(this, @"There is no website enabled. Please check the configuration", @"Stopped", MessageBoxButtons.OK, MessageBoxIcon.Information); } } #endregion #region Context menu events /// <summary> /// Always on top menu item click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void aotStripMenuItem_Click(object sender, EventArgs e) { var toolStripMenuItem = sender as ToolStripMenuItem; if (toolStripMenuItem == null) return; settings.AlwaysOnTop = toolStripMenuItem.Checked; TopMost = settings.AlwaysOnTop; } /// <summary> /// Contex menu enable/disable rss item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnClickWebsite(object sender, EventArgs e) { var toolStripMenuItem = sender as ToolStripMenuItem; if (toolStripMenuItem == null) return; var rssWebsite = toolStripMenuItem.Tag as RssWebsite; if (rssWebsite == null) return; rssWebsite.Enabled = !rssWebsite.Enabled; toolStripMenuItem.Checked = rssWebsite.Enabled; } #endregion #region Tray icon events /// <summary> /// Notify tray icon double click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void notifyIconTray_MouseDoubleClick(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; this.Show(); } /// <summary> /// Baloon clicked - open the url with default browser /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void notifyIconTray_BalloonTipClicked(object sender, EventArgs e) { var item = notifyIconTray.Tag as RssItem; if (item != null && !string.IsNullOrWhiteSpace(item.Link)) { try { System.Diagnostics.Process.Start(item.Link); } catch (Exception exception) { Logger.Error($"{nameof(notifyIconTray_BalloonTipClicked)} exception", exception); } } } #endregion #region Main form events /// <summary> /// Main form load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { //Ignore server certificate check ServicePointManager.Expect100Continue = false; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; rssItemBindingSource.DataSource = rssItems; previewForm.Visible = false; previewForm.Owner = this; userAgents.AddRange(Properties.Resources.UserAgents.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); var appDataPath = GetAppDataPath(); themes = ThemeManager.LoadThemes(Path.Combine(appDataPath, "Themes")); currentTheme = themes[0]; try { var settingsPersister = new SettingsPersister(); settings = settingsPersister.ReadSettings(appDataPath); } catch (Exception exception) { Logger.Warn($"{nameof(MainForm_Load)} exception", exception); } //Start background worker listener = new RssListener(settings, userAgents); listener.NewRss += OnNewRss; startStopToolStripMenuItem_Click(null, EventArgs.Empty); CreateThemeMainMenu(); CreateTrayContextMenu(); ModifyMainFormStyle(); InitHotKey(); } private string GetAppDataPath() { var name = Assembly.GetEntryAssembly().GetName().Name; var company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute( Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)) .Company; return Path.Combine( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), company), name); } /// <summary> /// Main form closing event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing && !isClosing) { e.Cancel = true; this.Hide(); } else { if (listener.IsRunning()) listener.Stop(); try { var settingsPersister = new SettingsPersister(); var name = Assembly.GetEntryAssembly().GetName().Name; var company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute( Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)) .Company; settingsPersister.SaveSettings(settings, Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), company), name)); } catch (Exception exception) { Logger.Warn($"{nameof(MainForm_FormClosing)} exception", exception); } notifyIconTray.Dispose(); } } #endregion private void ModifyMainFormStyle() { var assembly = Assembly.GetEntryAssembly().GetName(); Text = $@"{assembly.Name} {assembly.Version}"; Opacity = settings.Opacity; TopMost = settings.AlwaysOnTop; var screenHeight = Screen.PrimaryScreen.WorkingArea.Height; var screenWidth = Screen.PrimaryScreen.WorkingArea.Width; Location = new Point(screenWidth - this.Size.Width, 0); Size = new Size(this.Size.Width, screenHeight); } private void SetMainFormStatus() { this.toolStripStatusLabel.Text = $@"{this.listBoxItems.Items.Count} projects. {filteredCounter} filtered."; } private void InitHotKey() { //hotkey init for showing var key = new HotKey { KeyModifier = HotKey.KeyModifiers.Alt | HotKey.KeyModifiers.Control, Key = Keys.C }; key.HotKeyPressed += new System.Windows.Forms.KeyEventHandler(hotkey_HotKeyPressed); //end } private void hotkey_HotKeyPressed(object sender, System.Windows.Forms.KeyEventArgs e) { this.Visible = true; } private void CreateTrayContextMenu() { contextMenuStripTray.Items.Clear(); foreach (var rssCategory in settings.RssCategories) { var toolStripMenuItem = new ToolStripMenuItem(rssCategory.Name); foreach (var rssWeb in rssCategory.RssWebsites) { var childToolStripMenuItem = new ToolStripMenuItem(rssWeb.Name); childToolStripMenuItem.Click += new EventHandler(OnClickWebsite); childToolStripMenuItem.Checked = rssWeb.Enabled; childToolStripMenuItem.Tag = rssWeb; toolStripMenuItem.DropDownItems.Add(childToolStripMenuItem); } contextMenuStripTray.Items.Add(toolStripMenuItem); } var aotMenuItem = new ToolStripMenuItem("Always On Top") { Checked = settings.AlwaysOnTop, CheckOnClick = true }; aotMenuItem.Click += new EventHandler(aotStripMenuItem_Click); contextMenuStripTray.Items.Add(aotMenuItem); var clearMenuItem = new ToolStripMenuItem("Clear", Properties.Resources.ic_delete_black_24dp_1x) { CheckOnClick = false }; clearMenuItem.Click += (sender, args) => clearToolStripMenuItem_Click(null, null); contextMenuStripTray.Items.Add(clearMenuItem); var exitMenuItem = new ToolStripMenuItem("Exit", Properties.Resources.exit, new EventHandler(exitToolStripMenuItem_Click)); exitMenuItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; contextMenuStripTray.Items.Add(exitMenuItem); } private void CreateThemeMainMenu() { //TODO: Implement theming } /// <summary> /// NewRss event handler /// </summary> /// <param name="rssItem"></param> private void OnNewRss(RssItem rssItem) { if (!InvokeRequired) { if (!rssItem.Website.FirstUpdate) { if (rssItems.Contains(rssItem)) return; if (settings.IgnoreEnabled) { if (IsFilteredOut(rssItem)) { Logger.Info($"{nameof(OnNewRss)} filtered out \"{rssItem.Title}\" pub date {rssItem.PubDate} link {rssItem.Link}"); filteredCounter++; SetMainFormStatus(); return; } } lock (rssItems) { rssItems.Insert(0, rssItem); if (this.rssItems.Count > settings.MaxHistoryItems) this.rssItems.RemoveAt(rssItems.Count - 1); } Logger.Info($"{nameof(OnNewRss)} shown item \"{rssItem.Title}\" pub date {rssItem.PubDate} link {rssItem.Link}"); SetMainFormStatus(); notifyIconTray.Tag = rssItem; this.notifyIconTray.ShowBalloonTip(0, $"{rssItem.Title}", string.Join("\r\n", Utilities.WrapTextByCharacterNoFull(rssItem.Description, 100)), ToolTipIcon.Info); } } else { Invoke(new Action<RssItem>(OnNewRss), new object[] { rssItem }); } } /// <summary> /// Check if the filter regex matches item title or description /// </summary> /// <param name="item"></param> /// <returns></returns> private bool IsFilteredOut(RssItem item) { foreach (string filter in settings.IgnoredItems.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (Regex.IsMatch(item.Title, filter.Trim(), RegexOptions.IgnoreCase) || Regex.IsMatch(item.Description, filter.Trim(), RegexOptions.IgnoreCase)) return true; } return false; } #region Rss Items list events /// <summary> /// Ownerdraw /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBoxItems_DrawItem(object sender, DrawItemEventArgs e) { var backColor = e.BackColor; // Determine the color of the brush to draw each item based // on the index of the item to draw. switch (e.Index % 2) { case 0: backColor = Color.FromArgb(255, 60, 60, 60); break; //case 1: // backColor = Color.Orange; // break; } // If the ListBox has focus, draw a focus rectangle around the selected item. if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) e = new DrawItemEventArgs(e.Graphics, e.Font, e.Bounds /*new Rectangle(e.Bounds.Location, new Size(e.Bounds.Width, e.Bounds.Height * 2)) */, e.Index, e.State, e.ForeColor, Color.DarkGray); // Draw the background of the ListBox control for each item based on above selection else e = new DrawItemEventArgs(e.Graphics, e.Font, e.Bounds, e.Index, e.State, e.ForeColor, backColor); e.DrawBackground(); Image image = Properties.Resources.feed_icon_grey_24px; var point = new Point(e.Bounds.X + 10, e.Bounds.Y + 10); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) image = Properties.Resources.feed_icon_orange_24px; if (e.Index >= 0 && image != null) e.Graphics.DrawImage(image, point); // Draw the current item text based on the current Font // and the custom brush settings. point = new Point(e.Bounds.X + 50, e.Bounds.Y + 10); if (e.Index >= 0) { var rssItem = this.listBoxItems.Items[e.Index] as RssItem; if (rssItem == null) return; using (var largerFont = new Font(e.Font, FontStyle.Regular)) { var toDraw = $"{(rssItem.PubDate.Date == DateTime.Today ? "Today, " + rssItem.PubDate.ToString("hh:mm") : rssItem.PubDate.ToString("dddd, hh:mm"))}"; var drawWidth = e.Graphics.MeasureString(toDraw, largerFont).Width; e.Graphics.DrawString(toDraw, largerFont, new SolidBrush(e.ForeColor), point, StringFormat.GenericDefault); point.Offset((int)drawWidth, 0); using (var largerBoldFont = new Font(e.Font, FontStyle.Bold)) { e.Graphics.DrawString($" {rssItem.Category.Name} {rssItem.Website.Name}", largerBoldFont, new SolidBrush(e.ForeColor), point, StringFormat.GenericDefault); point.Offset(-1 * (int)drawWidth, largerFont.Height); } } using (var largerFont = new Font(e.Font.FontFamily, 14, FontStyle.Bold)) { e.Graphics.DrawString(rssItem.Title, largerFont, new SolidBrush(e.ForeColor), point, StringFormat.GenericDefault); point.Offset(0, largerFont.Height); } var lines = UIUtilities.WrapTextByPixelSize(rssItem.Description, e.Bounds.Width, e.Graphics, e.Font); //Draw the first two lines only e.Graphics.DrawString(lines[0], e.Font, new SolidBrush(e.ForeColor), point, StringFormat.GenericDefault); point.Offset(0, e.Font.Height); if (lines.Count > 1) e.Graphics.DrawString(lines[1] + "...", e.Font, new SolidBrush(e.ForeColor), point, StringFormat.GenericDefault); } e.DrawFocusRectangle(); } /// <summary> /// Listbox tem double clicked open URL in defaul browser /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBoxItems_DoubleClick(object sender, EventArgs e) { var item = this.listBoxItems.SelectedItem as RssItem; if (item != null && !string.IsNullOrWhiteSpace(item.Link)) { try { System.Diagnostics.Process.Start(item.Link); } catch (Exception exception) { Logger.Error($"{nameof(listBoxItems_DoubleClick)} exception", exception); } } } /// <summary> /// Show Context menu for listbox right click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBoxItems_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var point = new Point(e.X, e.Y); var index = this.listBoxItems.IndexFromPoint(point); if (index < 0 || index >= listBoxItems.Items.Count) return; this.listBoxItems.SelectedIndex = index; this.contextMenuStripList.Show(listBoxItems, point); } } /// <summary> /// Delete and Enter key handler for list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBoxItems_KeyUp(object sender, KeyEventArgs e) { if (listBoxItems.SelectedIndex < 0 || listBoxItems.SelectedIndex >= rssItems.Count) return; switch (e.KeyCode) { case Keys.Delete: { lock (rssItems) { rssItems.RemoveAt(listBoxItems.SelectedIndex); } break; } case Keys.Enter: { listBoxItems_DoubleClick(null, EventArgs.Empty); break; } } } /// <summary> /// Refresh listbox items on resize /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBoxItems_Resize(object sender, EventArgs e) { //Force redraw all items in the list when resized this.listBoxItems.Invalidate(); } /// <summary> /// Preview item using builtin WebBrowser control /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void previewToolStripMenuItem_Click(object sender, EventArgs e) { var rssItem = listBoxItems.SelectedItem as RssItem; if (rssItem == null) return; previewForm.Link = rssItem.Link; previewForm.ShowDialog(this); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Windows.Forms; using System.Data; using TVicPort_Cs; namespace PortIo { /// <summary> /// Summary description for Form1. /// </summary> /// public class PortForm : System.Windows.Forms.Form { bool DriverOpened = false; public System.Windows.Forms.GroupBox Frame4; public System.Windows.Forms.TextBox EPortAddr; public System.Windows.Forms.Button B_Test; public System.Windows.Forms.Label L_Test4; public System.Windows.Forms.Label L_Test1; public System.Windows.Forms.Label Label13; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label12; public System.Windows.Forms.Button Open_Driver; public System.Windows.Forms.Button Close_Driver; public System.Windows.Forms.Button B_Exit; private System.Windows.Forms.LinkLabel linkLabel2; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label6; internal System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox1; public System.Windows.Forms.TextBox PortR1; public System.Windows.Forms.TextBox PortW1; public System.Windows.Forms.TextBox ValW1; public System.Windows.Forms.Label Label7; public System.Windows.Forms.Label Label9; public System.Windows.Forms.Button Read_Port; public System.Windows.Forms.Label ValR1; public System.Windows.Forms.Button Write_Port; private System.Windows.Forms.ComboBox C_ReadSize; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox C_WriteSize; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox E_Cycles; private System.Windows.Forms.Label L_Days; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public PortForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PortForm)); this.Frame4 = new System.Windows.Forms.GroupBox(); this.E_Cycles = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.EPortAddr = new System.Windows.Forms.TextBox(); this.B_Test = new System.Windows.Forms.Button(); this.L_Test4 = new System.Windows.Forms.Label(); this.L_Test1 = new System.Windows.Forms.Label(); this.Label13 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.Label12 = new System.Windows.Forms.Label(); this.Open_Driver = new System.Windows.Forms.Button(); this.Close_Driver = new System.Windows.Forms.Button(); this.B_Exit = new System.Windows.Forms.Button(); this.linkLabel2 = new System.Windows.Forms.LinkLabel(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label6 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.C_WriteSize = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.C_ReadSize = new System.Windows.Forms.ComboBox(); this.PortR1 = new System.Windows.Forms.TextBox(); this.PortW1 = new System.Windows.Forms.TextBox(); this.ValW1 = new System.Windows.Forms.TextBox(); this.Label7 = new System.Windows.Forms.Label(); this.Label9 = new System.Windows.Forms.Label(); this.Read_Port = new System.Windows.Forms.Button(); this.ValR1 = new System.Windows.Forms.Label(); this.Write_Port = new System.Windows.Forms.Button(); this.L_Days = new System.Windows.Forms.Label(); this.Frame4.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // Frame4 // this.Frame4.BackColor = System.Drawing.SystemColors.Control; this.Frame4.Controls.Add(this.E_Cycles); this.Frame4.Controls.Add(this.label4); this.Frame4.Controls.Add(this.EPortAddr); this.Frame4.Controls.Add(this.B_Test); this.Frame4.Controls.Add(this.L_Test4); this.Frame4.Controls.Add(this.L_Test1); this.Frame4.Controls.Add(this.Label13); this.Frame4.Controls.Add(this.Label2); this.Frame4.Controls.Add(this.Label12); this.Frame4.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Frame4.ForeColor = System.Drawing.SystemColors.ControlText; this.Frame4.Location = new System.Drawing.Point(8, 152); this.Frame4.Name = "Frame4"; this.Frame4.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame4.Size = new System.Drawing.Size(340, 160); this.Frame4.TabIndex = 62; this.Frame4.TabStop = false; this.Frame4.Text = "Port I/O performance test"; // // E_Cycles // this.E_Cycles.AutoSize = false; this.E_Cycles.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.E_Cycles.Location = new System.Drawing.Point(148, 61); this.E_Cycles.Name = "E_Cycles"; this.E_Cycles.Size = new System.Drawing.Size(60, 24); this.E_Cycles.TabIndex = 52; this.E_Cycles.Text = "20000"; this.E_Cycles.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(20, 65); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(115, 16); this.label4.TabIndex = 51; this.label4.Text = "Number Of I/O Cycles:"; // // EPortAddr // this.EPortAddr.AcceptsReturn = true; this.EPortAddr.AutoSize = false; this.EPortAddr.BackColor = System.Drawing.SystemColors.Window; this.EPortAddr.Cursor = System.Windows.Forms.Cursors.IBeam; this.EPortAddr.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.EPortAddr.ForeColor = System.Drawing.SystemColors.WindowText; this.EPortAddr.Location = new System.Drawing.Point(148, 28); this.EPortAddr.MaxLength = 4; this.EPortAddr.Name = "EPortAddr"; this.EPortAddr.RightToLeft = System.Windows.Forms.RightToLeft.No; this.EPortAddr.Size = new System.Drawing.Size(40, 24); this.EPortAddr.TabIndex = 44; this.EPortAddr.Text = "0378"; this.EPortAddr.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.EPortAddr.TextChanged += new System.EventHandler(this.EPortAddr_TextChanged); // // B_Test // this.B_Test.BackColor = System.Drawing.SystemColors.Control; this.B_Test.Cursor = System.Windows.Forms.Cursors.Default; this.B_Test.Enabled = false; this.B_Test.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.B_Test.ForeColor = System.Drawing.SystemColors.ControlText; this.B_Test.Location = new System.Drawing.Point(224, 26); this.B_Test.Name = "B_Test"; this.B_Test.RightToLeft = System.Windows.Forms.RightToLeft.No; this.B_Test.Size = new System.Drawing.Size(96, 28); this.B_Test.TabIndex = 41; this.B_Test.Text = "Run test"; this.B_Test.Click += new System.EventHandler(this.B_Test_Click); // // L_Test4 // this.L_Test4.AutoSize = true; this.L_Test4.BackColor = System.Drawing.SystemColors.Control; this.L_Test4.Cursor = System.Windows.Forms.Cursors.Default; this.L_Test4.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.L_Test4.ForeColor = System.Drawing.SystemColors.ControlText; this.L_Test4.Location = new System.Drawing.Point(148, 131); this.L_Test4.Name = "L_Test4"; this.L_Test4.RightToLeft = System.Windows.Forms.RightToLeft.No; this.L_Test4.Size = new System.Drawing.Size(57, 16); this.L_Test4.TabIndex = 50; this.L_Test4.Text = "0 microsec"; // // L_Test1 // this.L_Test1.AutoSize = true; this.L_Test1.BackColor = System.Drawing.SystemColors.Control; this.L_Test1.Cursor = System.Windows.Forms.Cursors.Default; this.L_Test1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.L_Test1.ForeColor = System.Drawing.SystemColors.ControlText; this.L_Test1.Location = new System.Drawing.Point(148, 98); this.L_Test1.Name = "L_Test1"; this.L_Test1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.L_Test1.Size = new System.Drawing.Size(57, 16); this.L_Test1.TabIndex = 49; this.L_Test1.Text = "0 microsec"; // // Label13 // this.Label13.AutoSize = true; this.Label13.BackColor = System.Drawing.SystemColors.Control; this.Label13.Cursor = System.Windows.Forms.Cursors.Default; this.Label13.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label13.ForeColor = System.Drawing.SystemColors.ControlText; this.Label13.Location = new System.Drawing.Point(24, 131); this.Label13.Name = "Label13"; this.Label13.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label13.Size = new System.Drawing.Size(111, 16); this.Label13.TabIndex = 48; this.Label13.Text = "With ReadPortFIFO():"; // // Label2 // this.Label2.AutoSize = true; this.Label2.BackColor = System.Drawing.SystemColors.Control; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Location = new System.Drawing.Point(11, 98); this.Label2.Name = "Label2"; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.Size = new System.Drawing.Size(124, 16); this.Label2.TabIndex = 47; this.Label2.Text = "Separate I/O operations:"; // // Label12 // this.Label12.AutoSize = true; this.Label12.BackColor = System.Drawing.SystemColors.Control; this.Label12.Cursor = System.Windows.Forms.Cursors.Default; this.Label12.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label12.ForeColor = System.Drawing.SystemColors.ControlText; this.Label12.Location = new System.Drawing.Point(69, 32); this.Label12.Name = "Label12"; this.Label12.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label12.Size = new System.Drawing.Size(66, 16); this.Label12.TabIndex = 45; this.Label12.Text = "Port address"; this.Label12.Click += new System.EventHandler(this.Label12_Click); // // Open_Driver // this.Open_Driver.BackColor = System.Drawing.SystemColors.Control; this.Open_Driver.Cursor = System.Windows.Forms.Cursors.Default; this.Open_Driver.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Open_Driver.ForeColor = System.Drawing.SystemColors.ControlText; this.Open_Driver.Location = new System.Drawing.Point(384, 160); this.Open_Driver.Name = "Open_Driver"; this.Open_Driver.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Open_Driver.Size = new System.Drawing.Size(104, 32); this.Open_Driver.TabIndex = 61; this.Open_Driver.Text = "Open Driver"; this.Open_Driver.Click += new System.EventHandler(this.Open_Driver_Click); // // Close_Driver // this.Close_Driver.BackColor = System.Drawing.SystemColors.Control; this.Close_Driver.Cursor = System.Windows.Forms.Cursors.Default; this.Close_Driver.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Close_Driver.ForeColor = System.Drawing.SystemColors.ControlText; this.Close_Driver.Location = new System.Drawing.Point(384, 208); this.Close_Driver.Name = "Close_Driver"; this.Close_Driver.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Close_Driver.Size = new System.Drawing.Size(104, 32); this.Close_Driver.TabIndex = 60; this.Close_Driver.Text = "Close Driver"; this.Close_Driver.Click += new System.EventHandler(this.Close_Driver_Click); // // B_Exit // this.B_Exit.BackColor = System.Drawing.SystemColors.Control; this.B_Exit.Cursor = System.Windows.Forms.Cursors.Default; this.B_Exit.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.B_Exit.ForeColor = System.Drawing.SystemColors.ControlText; this.B_Exit.Location = new System.Drawing.Point(384, 280); this.B_Exit.Name = "B_Exit"; this.B_Exit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.B_Exit.Size = new System.Drawing.Size(104, 32); this.B_Exit.TabIndex = 59; this.B_Exit.Text = "Exit"; this.B_Exit.Click += new System.EventHandler(this.B_Exit_Click); // // linkLabel2 // this.linkLabel2.AutoSize = true; this.linkLabel2.Location = new System.Drawing.Point(371, 92); this.linkLabel2.Name = "linkLabel2"; this.linkLabel2.Size = new System.Drawing.Size(131, 16); this.linkLabel2.TabIndex = 80; this.linkLabel2.TabStop = true; this.linkLabel2.Text = "[email protected]"; this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked); // // linkLabel1 // this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new System.Drawing.Point(364, 68); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(145, 16); this.linkLabel1.TabIndex = 79; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "http://www.RapidDriver.com"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked_1); // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label6.Location = new System.Drawing.Point(371, 44); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(130, 16); this.label6.TabIndex = 78; this.label6.Text = "(c) 2005, EnTech Taiwan"; this.label6.Click += new System.EventHandler(this.label6_Click); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(404, 20); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(48, 16); this.label3.TabIndex = 77; this.label3.Text = "TVicPort"; this.label3.Click += new System.EventHandler(this.label3_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.C_WriteSize); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.C_ReadSize); this.groupBox1.Controls.Add(this.PortR1); this.groupBox1.Controls.Add(this.PortW1); this.groupBox1.Controls.Add(this.ValW1); this.groupBox1.Controls.Add(this.Label7); this.groupBox1.Controls.Add(this.Label9); this.groupBox1.Controls.Add(this.Read_Port); this.groupBox1.Controls.Add(this.ValR1); this.groupBox1.Controls.Add(this.Write_Port); this.groupBox1.Location = new System.Drawing.Point(8, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(340, 128); this.groupBox1.TabIndex = 81; this.groupBox1.TabStop = false; // // C_WriteSize // this.C_WriteSize.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.C_WriteSize.Items.AddRange(new object[] { "Byte", "Word", "Long"}); this.C_WriteSize.Location = new System.Drawing.Point(72, 86); this.C_WriteSize.Name = "C_WriteSize"; this.C_WriteSize.Size = new System.Drawing.Size(56, 21); this.C_WriteSize.TabIndex = 87; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(80, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 16); this.label1.TabIndex = 86; this.label1.Text = "Size:"; // // C_ReadSize // this.C_ReadSize.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.C_ReadSize.Items.AddRange(new object[] { "Byte", "Word", "Long"}); this.C_ReadSize.Location = new System.Drawing.Point(72, 46); this.C_ReadSize.Name = "C_ReadSize"; this.C_ReadSize.Size = new System.Drawing.Size(56, 21); this.C_ReadSize.TabIndex = 85; // // PortR1 // this.PortR1.AcceptsReturn = true; this.PortR1.AutoSize = false; this.PortR1.BackColor = System.Drawing.SystemColors.Window; this.PortR1.Cursor = System.Windows.Forms.Cursors.IBeam; this.PortR1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.PortR1.ForeColor = System.Drawing.SystemColors.WindowText; this.PortR1.Location = new System.Drawing.Point(16, 44); this.PortR1.MaxLength = 4; this.PortR1.Name = "PortR1"; this.PortR1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.PortR1.Size = new System.Drawing.Size(44, 24); this.PortR1.TabIndex = 83; this.PortR1.Text = "0378"; this.PortR1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // PortW1 // this.PortW1.AcceptsReturn = true; this.PortW1.AutoSize = false; this.PortW1.BackColor = System.Drawing.SystemColors.Window; this.PortW1.Cursor = System.Windows.Forms.Cursors.IBeam; this.PortW1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.PortW1.ForeColor = System.Drawing.SystemColors.WindowText; this.PortW1.Location = new System.Drawing.Point(16, 84); this.PortW1.MaxLength = 0; this.PortW1.Name = "PortW1"; this.PortW1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.PortW1.Size = new System.Drawing.Size(44, 24); this.PortW1.TabIndex = 79; this.PortW1.Text = "0378"; this.PortW1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // ValW1 // this.ValW1.AcceptsReturn = true; this.ValW1.AutoSize = false; this.ValW1.BackColor = System.Drawing.SystemColors.Window; this.ValW1.Cursor = System.Windows.Forms.Cursors.IBeam; this.ValW1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ValW1.ForeColor = System.Drawing.SystemColors.WindowText; this.ValW1.Location = new System.Drawing.Point(140, 84); this.ValW1.MaxLength = 8; this.ValW1.Name = "ValW1"; this.ValW1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ValW1.Size = new System.Drawing.Size(72, 24); this.ValW1.TabIndex = 77; this.ValW1.Text = "00000036"; this.ValW1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // Label7 // this.Label7.AutoSize = true; this.Label7.BackColor = System.Drawing.SystemColors.Control; this.Label7.Cursor = System.Windows.Forms.Cursors.Default; this.Label7.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label7.ForeColor = System.Drawing.SystemColors.ControlText; this.Label7.Location = new System.Drawing.Point(12, 20); this.Label7.Name = "Label7"; this.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label7.Size = new System.Drawing.Size(55, 16); this.Label7.TabIndex = 81; this.Label7.Text = "Addr (hex)"; // // Label9 // this.Label9.AutoSize = true; this.Label9.BackColor = System.Drawing.SystemColors.Control; this.Label9.Cursor = System.Windows.Forms.Cursors.Default; this.Label9.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Label9.ForeColor = System.Drawing.SystemColors.ControlText; this.Label9.Location = new System.Drawing.Point(148, 20); this.Label9.Name = "Label9"; this.Label9.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label9.Size = new System.Drawing.Size(57, 16); this.Label9.TabIndex = 80; this.Label9.Text = "Value(hex)"; // // Read_Port // this.Read_Port.BackColor = System.Drawing.SystemColors.Control; this.Read_Port.Cursor = System.Windows.Forms.Cursors.Default; this.Read_Port.Enabled = false; this.Read_Port.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Read_Port.ForeColor = System.Drawing.SystemColors.ControlText; this.Read_Port.Location = new System.Drawing.Point(228, 42); this.Read_Port.Name = "Read_Port"; this.Read_Port.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Read_Port.Size = new System.Drawing.Size(96, 28); this.Read_Port.TabIndex = 82; this.Read_Port.Text = "Read port"; this.Read_Port.Click += new System.EventHandler(this.Read_Port_Click); // // ValR1 // this.ValR1.BackColor = System.Drawing.SystemColors.Control; this.ValR1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.ValR1.Cursor = System.Windows.Forms.Cursors.Default; this.ValR1.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.ValR1.ForeColor = System.Drawing.SystemColors.ControlText; this.ValR1.Location = new System.Drawing.Point(140, 44); this.ValR1.Name = "ValR1"; this.ValR1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ValR1.Size = new System.Drawing.Size(72, 24); this.ValR1.TabIndex = 84; this.ValR1.Text = "00000000"; this.ValR1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // Write_Port // this.Write_Port.BackColor = System.Drawing.SystemColors.Control; this.Write_Port.Cursor = System.Windows.Forms.Cursors.Default; this.Write_Port.Enabled = false; this.Write_Port.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Write_Port.ForeColor = System.Drawing.SystemColors.ControlText; this.Write_Port.Location = new System.Drawing.Point(228, 82); this.Write_Port.Name = "Write_Port"; this.Write_Port.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Write_Port.Size = new System.Drawing.Size(96, 28); this.Write_Port.TabIndex = 78; this.Write_Port.Text = "Write port"; this.Write_Port.Click += new System.EventHandler(this.Write_Port_Click); // // L_Days // this.L_Days.Location = new System.Drawing.Point(360, 120); this.L_Days.Name = "L_Days"; this.L_Days.Size = new System.Drawing.Size(148, 16); this.L_Days.TabIndex = 82; this.L_Days.Text = "Evaluation Days Left: ??"; this.L_Days.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // PortForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(512, 325); this.Controls.Add(this.L_Days); this.Controls.Add(this.groupBox1); this.Controls.Add(this.linkLabel2); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label6); this.Controls.Add(this.label3); this.Controls.Add(this.Frame4); this.Controls.Add(this.Open_Driver); this.Controls.Add(this.Close_Driver); this.Controls.Add(this.B_Exit); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "PortForm"; this.Text = "Port I/O Sample Application"; this.Load += new System.EventHandler(this.PortForm_Load); this.Closed += new System.EventHandler(this.PortForm_Closed); this.Frame4.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new PortForm()); } private void LockControls() { Open_Driver.Enabled = !DriverOpened; Close_Driver.Enabled = DriverOpened; Read_Port.Enabled = DriverOpened; Write_Port.Enabled = DriverOpened; B_Test.Enabled = DriverOpened; } private void Open_Driver_Click(object sender, System.EventArgs e) { TVicPort.OpenTVicPort(); DriverOpened = TVicPort.IsDriverOpened() != 0; if (DriverOpened) L_Days.Text = "Evaluation Days Left: " + TVicPort.EvaluationDaysLeft().ToString("d"); LockControls(); } private void Close_Driver_Click(object sender, System.EventArgs e) { TVicPort.CloseTVicPort(); DriverOpened = false; LockControls(); } private void B_Exit_Click(object sender, System.EventArgs e) { Close(); } private void PortForm_Closed(object sender, System.EventArgs e) { TVicPort.CloseTVicPort(); } private void Read_Port_Click(object sender, System.EventArgs e) { ushort PortAddr; PortAddr = ushort.Parse(PortR1.Text,NumberStyles.HexNumber); PortR1.Text = PortAddr.ToString("X4"); switch (C_ReadSize.SelectedIndex) { case 0: ValR1.Text = (TVicPort.ReadPort(PortAddr)).ToString("X2"); break; case 1: ValR1.Text = (TVicPort.ReadPortW(PortAddr)).ToString("X4"); break; case 2: ValR1.Text = (TVicPort.ReadPortL(PortAddr)).ToString("X8"); break; } } private void Write_Port_Click(object sender, System.EventArgs e) { ushort PortAddr; uint lVal; byte bVal; ushort wVal; PortAddr = ushort.Parse(PortW1.Text,NumberStyles.HexNumber); PortW1.Text = PortAddr.ToString("X4"); switch (C_WriteSize.SelectedIndex) { case 0: bVal = byte.Parse(ValW1.Text,NumberStyles.HexNumber); TVicPort.WritePort(PortAddr,bVal); break; case 1: wVal = ushort.Parse(ValW1.Text,NumberStyles.HexNumber); TVicPort.WritePortW(PortAddr, wVal); break; case 2: lVal = uint.Parse(ValW1.Text,NumberStyles.HexNumber); TVicPort.WritePortL(PortAddr,lVal); break; } } private void B_Test_Click(object sender, System.EventArgs e) { Cursor = Cursors.WaitCursor; ushort Cycle, NumPortCycles; ushort PortAddr; byte DataByte; double a,b,r; PortAddr = ushort.Parse(EPortAddr.Text,NumberStyles.HexNumber); NumPortCycles = ushort.Parse(E_Cycles.Text,NumberStyles.Integer); byte[] buffer = new byte[NumPortCycles]; // Separate I/O operations a = DateTime.Now.Ticks; for (Cycle = 1; Cycle<=NumPortCycles; Cycle++) DataByte = TVicPort.ReadPort(PortAddr); b = DateTime.Now.Ticks; r = System.Math.Abs(b-a)/(10*NumPortCycles); L_Test1.Text = String.Concat(r.ToString("F4")," microsec"); // with ReadPortBuffer() a = DateTime.Now.Ticks; // Declare an unsafe block unsafe { // Fix the byte array. fixed (byte *array = buffer) { // Make the call here, passing in the array. TVicPort.ReadPortFIFO(PortAddr,NumPortCycles,array); } } b = DateTime.Now.Ticks; r = System.Math.Abs(b-a)/(10*NumPortCycles); L_Test4.Text = String.Concat(r.ToString("F4")," microsec"); Cursor = Cursors.Default; } private void PortForm_Load(object sender, System.EventArgs e) { DriverOpened = false; C_ReadSize.SelectedIndex = 0; C_WriteSize.SelectedIndex = 0; LockControls(); } private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { } private void linkLabel2_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("mailto:RapidDriver%20Support%20<"+linkLabel2.Text+">?subject=RapidDriver"); } private void EPortAddr_TextChanged(object sender, System.EventArgs e) { } private void Label12_Click(object sender, System.EventArgs e) { } private void label3_Click(object sender, System.EventArgs e) { } private void label6_Click(object sender, System.EventArgs e) { } private void linkLabel1_LinkClicked_1(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { } } }
using SteamKit2; using System.Collections.Generic; using SteamTrade; //gmc inc using System; using System.Configuration; using System.Globalization; using GamerscoinWrapper.Wrapper; using GamerscoinWrapper.Wrapper.Interfaces; using System.Threading; using System.Timers; namespace SteamBot { public class SimpleUserHandler : UserHandler { public int ScrapPutUp; public SimpleUserHandler (Bot bot, SteamID sid) : base(bot, sid) {} public override bool OnGroupAdd() { return false; } public override bool OnFriendAdd () { Bot.log.Success(Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " (" + OtherSID.ToString() + ") added me!"); string userinfo = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " (" + OtherSID.ToString() + ")"; Bot.log.Success(Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " (" + OtherSID.ToString() + ") added me!"); // Using a timer here because the message will fail to send if you do it too quickly return true; } public override void OnLoginCompleted() { } public override void OnChatRoomMessage(SteamID chatID, SteamID sender, string message) { Log.Info(Bot.SteamFriends.GetFriendPersonaName(sender) + ": " + message); base.OnChatRoomMessage(chatID, sender, message); } public override void OnFriendRemove () {} public override void OnMessage (string message, EChatEntryType type) { //REGULAR chat commands if (message.Contains("!help")) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Available Bot Commands :"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!wallet"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!getwallet"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!withdraw"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!trade"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!getid"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!buy"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!sell"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "!info"); } else if (message.Contains("hi")) { string userinfo = Bot.SteamFriends.GetFriendPersonaName(OtherSID); Bot.SteamFriends.SendChatMessage(OtherSID, type, "You're welcome! " + userinfo); } else if (message.Contains("!wallet")) { //Enter GamersCoin Demon Settings into app.config //Basic Setup Wallet Connector IBaseBtcConnector baseBtcConnector = new BaseBtcConnector(true); // Use Primary Wallet //Bot.SteamFriends.SendChatMessage(OtherSID, type, "Connecting to Gamerscoin daemon: " + ConfigurationManager.AppSettings["ServerIp"] + "..."); Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); string woot = baseBtcConnector.GetAccountAddress(OtherSID + ""); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Send Your GamersCoins to : " + woot + " to buy Items with GamersCoins"); decimal myBalance = baseBtcConnector.GetBalance(OtherSID + ""); Bot.SteamFriends.SendChatMessage(OtherSID, type, "My balance: " + myBalance + " GMC"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); } //Get New Wallet Address else if (message.Contains("!getwallet")) { IBaseBtcConnector baseBtcConnector = new BaseBtcConnector(true); // Get New Wallet for User with SteamID //Bot.SteamFriends.SendChatMessage(OtherSID, type, "Connecting to Gamerscoin daemon: " + ConfigurationManager.AppSettings["ServerIp"] + "..."); string woot = baseBtcConnector.GetAccountAddress("" + OtherSID); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Your New GamersCoin Address : " + woot); } // Withdraw All GamersCoin from Wallet else if (message.StartsWith("!withdraw G")) { // Create new instance with string array. string lineOfText = message.ToString(); string[] wordArray = lineOfText.Split(' '); string account = OtherSID.ToString(); string address = wordArray[1].ToString(); decimal amount = Convert.ToDecimal(wordArray[2]); IBaseBtcConnector baseBtcConnector = new BaseBtcConnector(true); // Withdraw GamersCoins from Wallet for User decimal myBalance = baseBtcConnector.GetBalance(OtherSID + ""); if (myBalance >= amount) { baseBtcConnector.SendFrom(account, address, amount); Thread.Sleep(2000); Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); //Bot.SteamFriends.SendChatMessage(OtherSID, type, "Connecting to Gamerscoin daemon: " + ConfigurationManager.AppSettings["ServerIp"] + "..."); Bot.SteamFriends.SendChatMessage(OtherSID, type, "You withdraw " + amount + " GamersCoins to " + address + " address."); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Withdraw Done !!!"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Thanks for using our Fairtradebot !!!"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Have a nice Day ...."); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Thanks for Freedom !!!"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Your New Wallet balance: " + myBalance + " GMC"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); Bot.log.Success(Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " (" + OtherSID.ToString() + ") withdraw " + address + " " + amount); } else { Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Your withdraw amount is to high"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "Your Wallet balance: " + myBalance + " GMC"); Bot.SteamFriends.SendChatMessage(OtherSID, type, "##################################################################################"); } } else if (message.Contains("!withdraw")) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Please use : !withdraw gamerscoinaddress amount-to-paypout"); } else if (message.Contains("!trade")) { Bot.SteamTrade.Trade(OtherSID); } else if (message.Contains("fuck") || message.Contains("suck") || message.Contains("dick") || message.Contains("cock") || message.Contains("tit") || message.Contains("boob") || message.Contains("pussy") || message.Contains("vagina") || message.Contains("cunt") || message.Contains("penis")) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Sorry, but as a robot I cannot perform sexual functions."); } else if (message.Contains("!getid")) { string userinfo = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " (" + OtherSID.ToString() + ")"; Bot.SteamFriends.SendChatMessage(OtherSID, type, "You're steamname and steamid is " + userinfo); } else if (message == "!buy") { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Please type that into the TRADE WINDOW, not here!"); } else if (message == "!sell") { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Please type that into the TRADE WINDOW, not here!"); } else if (message == "!info") { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Bot verion 1.0"); } // ADMIN commands else if (message == "self.restart") { if (IsAdmin) { // Starts a new instance of the program itself var filename = System.Reflection.Assembly.GetExecutingAssembly().Location; System.Diagnostics.Process.Start(filename); // Closes the current process } } else if (message == ".canceltrade") { if (IsAdmin) { Trade.CancelTrade(); } } else { Bot.SteamFriends.SendChatMessage(OtherSID, type, Bot.ChatResponse); } } public override bool OnTradeRequest() { return true; } public override void OnTradeError (string error) { Bot.SteamFriends.SendChatMessage (OtherSID, EChatEntryType.ChatMsg, "Oh, there was an error: " + error + "." ); Bot.log.Warn (error); } public override void OnTradeTimeout () { Bot.SteamFriends.SendChatMessage (OtherSID, EChatEntryType.ChatMsg, "Sorry, but you were AFK and the trade was canceled."); Bot.log.Info ("User was kicked because he was AFK."); } public override void OnTradeInit() { Trade.SendMessage ("Success. Please put up your items."); } public override void OnTradeAddItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {} public override void OnTradeRemoveItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {} public override void OnTradeMessage (string message) {} public override void OnTradeReady (bool ready) { if (!ready) { Trade.SetReady (false); } else { if(Validate ()) { Trade.SetReady (true); } Trade.SendMessage ("Scrap: " + ScrapPutUp); } } public override void OnTradeSuccess() { // Trade completed successfully Log.Success("Trade Complete."); } public override void OnTradeAccept() { if (Validate() || IsAdmin) { //Even if it is successful, AcceptTrade can fail on //trades with a lot of items so we use a try-catch try { if (Trade.AcceptTrade()) Log.Success("Trade Accepted!"); } catch { Log.Warn ("The trade might have failed, but we can't be sure."); } } } public bool Validate () { ScrapPutUp = 0; List<string> errors = new List<string> (); foreach (ulong id in Trade.OtherOfferedItems) { var item = Trade.OtherInventory.GetItem (id); if (item.Defindex == 5000) ScrapPutUp++; else if (item.Defindex == 5001) ScrapPutUp += 3; else if (item.Defindex == 5002) ScrapPutUp += 9; else { var schemaItem = Trade.CurrentSchema.GetItem (item.Defindex); errors.Add ("Item " + schemaItem.Name + " is not a metal."); } } if (ScrapPutUp < 1) { errors.Add ("You must put up at least 1 scrap."); } // send the errors if (errors.Count != 0) Trade.SendMessage("There were errors in your trade: "); foreach (string error in errors) { Trade.SendMessage(error); } return errors.Count == 0; } } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using BenchmarkDotNet.Extensions; namespace BenchmarkDotNet.Environments { [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] public class OsBrandStringHelper { // See https://en.wikipedia.org/wiki/Ver_(command) private static readonly Dictionary<string, string> WindowsBrandVersions = new Dictionary<string, string> { { "1.04", "1.0" }, { "2.11", "2.0" }, { "3", "3.0" }, { "3.10.528", "NT 3.1" }, { "3.11", "for Workgroups 3.11" }, { "3.50.807", "NT 3.5" }, { "3.51.1057", "NT 3.51" }, { "4.00.950", "95" }, { "4.00.1111", "95 OSR2" }, { "4.03.1212-1214", "95 OSR2.1" }, { "4.03.1214", "95 OSR2.5" }, { "4.00.1381", "NT 4.0" }, { "4.10.1998", "98" }, { "4.10.2222", "98 SE" }, { "4.90.2380.2", "ME Beta" }, { "4.90.2419", "ME Beta 2" }, { "4.90.3000", "ME" }, { "5.00.1515", "NT 5.0 Beta" }, { "5.00.2031", "2000 Beta 3" }, { "5.00.2128", "2000 RC2" }, { "5.00.2183", "2000 RC3" }, { "5.00.2195", "2000" }, { "5.0.2195", "2000 Professional" }, { "5.1.2505", "XP RC1" }, { "5.1.2600", "XP" }, { "5.1.2600.1105-1106", "XP SP1" }, { "5.1.2600.2180", "XP SP2" }, { "5.2.3541", ".NET Server interim" }, { "5.2.3590", ".NET Server Beta 3" }, { "5.2.3660", ".NET Server RC1" }, { "5.2.3718", ".NET Server 2003 RC2" }, { "5.2.3763", "Server 2003 Beta" }, { "5.2.3790", "XP Professional x64 Edition" }, { "5.2.3790.1180", "Server 2003 SP1" }, { "5.2.3790.1218", "Server 2003" }, { "6.0.5048", "Longhorn" }, { "6.0.5112", "Vista Beta 1" }, { "6.0.5219", "Vista CTP" }, { "6.0.5259", "Vista TAP Preview" }, { "6.0.5270", "Vista CTP December" }, { "6.0.5308", "Vista CTP February" }, { "6.0.5342", "Vista CTP Refresh" }, { "6.0.5365", "Vista April EWD" }, { "6.0.5381", "Vista Beta 2 Preview" }, { "6.0.5384", "Vista Beta 2" }, { "6.0.5456", "Vista Pre-RC1 Build 5456" }, { "6.0.5472", "Vista Pre-RC1 Build 5472" }, { "6.0.5536", "Vista Pre-RC1 Build 5536" }, { "6.0.5600.16384", "Vista RC1" }, { "6.0.5700", "Vista Pre-RC2" }, { "6.0.5728", "Vista Pre-RC2 Build 5728" }, { "6.0.5744.16384", "Vista RC2" }, { "6.0.5808", "Vista Pre-RTM Build 5808" }, { "6.0.5824", "Vista Pre-RTM Build 5824" }, { "6.0.5840", "Vista Pre-RTM Build 5840" }, { "6.0.6000", "Vista" }, { "6.0.6000.16386", "Vista RTM" }, { "6.0.6001", "Vista SP1" }, { "6.0.6002", "Vista SP2" }, { "6.1.7600", "7" }, { "6.1.7600.16385", "7" }, { "6.1.7601", "7 SP1" }, { "6.1.8400", "Home Server 2011" }, { "6.2.8102", "8 Developer Preview" }, { "6.2.9200", "8" }, { "6.2.9200.16384", "8 RTM" }, { "6.2.10211", "Phone 8" }, { "6.3.9600", "8.1" }, { "6.4.9841", "10 Technical Preview 1" }, { "6.4.9860", "10 Technical Preview 2" }, { "6.4.9879", "10 Technical Preview 3" }, { "10.0.9926", "10 Technical Preview 4" }, { "10.0.10041", "10 Technical Preview 5" }, { "10.0.10049", "10 Technical Preview 6" }, { "10.0.10240", "10 Threshold 1 [1507, RTM]" }, { "10.0.10586", "10 Threshold 2 [1511, November Update]" }, { "10.0.14393", "10 Redstone 1 [1607, Anniversary Update]" }, { "10.0.15063", "10 Redstone 2 [1703, Creators Update]" }, { "10.0.16299", "10 Redstone 3 [1709, Fall Creators Update]" }, { "10.0.17134", "10 Redstone 4 [1803, April 2018 Update]" }, { "10.0.17763", "10 Redstone 5 [1809, October 2018 Update]" } }; private class Windows10Version { private int Version { get; } [NotNull] private string CodeName { get; } [NotNull] private string MarketingName { get; } private int BuildNumber { get; } [NotNull] private string ShortifiedCodeName => CodeName.Replace(" ", ""); [NotNull] private string ShortifiedMarketingName => MarketingName.Replace(" ", ""); private Windows10Version(int version, [NotNull] string codeName, [NotNull] string marketingName, int buildNumber) { Version = version; CodeName = codeName; MarketingName = marketingName; BuildNumber = buildNumber; } private string ToFullVersion([CanBeNull] int? ubr = null) => ubr == null ? $"10.0.{BuildNumber}" : $"10.0.{BuildNumber}.{ubr}"; // The line with OsBrandString is one of the longest lines in the summary. // When people past in on GitHub, it can be a reason of an ugly horizontal scrollbar. // To avoid this, we are trying to minimize this line and use the minimum possible number of characters. public string ToPrettifiedString([CanBeNull] int? ubr) => $"{ToFullVersion(ubr)} ({Version}/{ShortifiedMarketingName}/{ShortifiedCodeName})"; // See https://en.wikipedia.org/wiki/Windows_10_version_history private static readonly List<Windows10Version> WellKnownVersions = new List<Windows10Version> { new Windows10Version(1507, "Threshold 1", "RTM", 10240), new Windows10Version(1511, "Threshold 2", "November Update", 10586), new Windows10Version(1607, "Redstone 1", "Anniversary Update", 14393), new Windows10Version(1703, "Redstone 2", "Creators Update", 15063), new Windows10Version(1709, "Redstone 3", "Fall Creators Update", 16299), new Windows10Version(1803, "Redstone 4", "April 2018 Update", 17134), new Windows10Version(1809, "Redstone 5", "October 2018 Update", 17763) }; [CanBeNull] public static Windows10Version Resolve([NotNull] string osVersion) => WellKnownVersions.FirstOrDefault(v => osVersion == $"10.0.{v.BuildNumber}"); } /// <summary> /// Transform an operation system name and version to a nice form for summary. /// </summary> /// <param name="osName">Original operation system name</param> /// <param name="osVersion">Original operation system version</param> /// <param name="windowsUbr">UBR (Update Build Revision), the revision number of Windows version (if available)</param> /// <returns>Prettified operation system title</returns> [NotNull] public static string Prettify([NotNull] string osName, [NotNull] string osVersion, [CanBeNull] int? windowsUbr = null) { if (osName == "Windows") return PrettifyWindows(osVersion, windowsUbr); return $"{osName} {osVersion}"; } [NotNull] private static string PrettifyWindows([NotNull] string osVersion, [CanBeNull] int? windowsUbr) { var windows10Version = Windows10Version.Resolve(osVersion); if (windows10Version != null) return "Windows " + windows10Version.ToPrettifiedString(windowsUbr); string brandVersion = WindowsBrandVersions.GetValueOrDefault(osVersion); string completeOsVersion = windowsUbr != null && osVersion.Count(c => c == '.') == 2 ? osVersion + "." + windowsUbr : osVersion; string fullVersion = brandVersion == null ? osVersion : brandVersion + " (" + completeOsVersion + ")"; return "Windows " + fullVersion; } private class MacOSXVersion { private int DarwinVersion { get; } [NotNull]private string CodeName { get; } private MacOSXVersion(int darwinVersion, [NotNull] string codeName) { DarwinVersion = darwinVersion; CodeName = codeName; } private static readonly List<MacOSXVersion> WellKnownVersions = new List<MacOSXVersion> { new MacOSXVersion(6, "Jaguar"), new MacOSXVersion(7, "Panther"), new MacOSXVersion(8, "Tiger"), new MacOSXVersion(9, "Leopard"), new MacOSXVersion(10, "Snow Leopard"), new MacOSXVersion(11, "Lion"), new MacOSXVersion(12, "Mountain Lion"), new MacOSXVersion(13, "Mavericks"), new MacOSXVersion(14, "Yosemite"), new MacOSXVersion(15, "El Capitan"), new MacOSXVersion(16, "Sierra"), new MacOSXVersion(17, "High Sierra"), new MacOSXVersion(18, "Mojave") }; [CanBeNull] public static string ResolveCodeName([NotNull] string kernelVersion) { if (string.IsNullOrWhiteSpace(kernelVersion)) return null; kernelVersion = kernelVersion.ToLowerInvariant().Trim(); if (kernelVersion.StartsWith("darwin")) kernelVersion = kernelVersion.Substring(6).Trim(); var numbers = kernelVersion.Split('.'); if (numbers.Length == 0) return null; string majorVersionStr = numbers[0]; if (int.TryParse(majorVersionStr, out int majorVersion)) return WellKnownVersions.FirstOrDefault(v => v.DarwinVersion == majorVersion)?.CodeName; return null; } } [NotNull] public static string PrettifyMacOSX([NotNull] string systemVersion, [NotNull] string kernelVersion) { string codeName = MacOSXVersion.ResolveCodeName(kernelVersion); if (codeName != null) { int firstDigitIndex = systemVersion.IndexOfAny("0123456789".ToCharArray()); if (firstDigitIndex == -1) return $"{systemVersion} {codeName} [{kernelVersion}]"; string systemVersionTitle = systemVersion.Substring(0, firstDigitIndex).Trim(); string systemVersionNumbers = systemVersion.Substring(firstDigitIndex).Trim(); return $"{systemVersionTitle} {codeName} {systemVersionNumbers} [{kernelVersion}]"; } return $"{systemVersion} [{kernelVersion}]"; } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool displayVersion = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = LanguageVersion.Default; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> embeddedFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool embedAllSourceFiles = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; ArrayBuilder<InstrumentationKind> instrumentationKinds = ArrayBuilder<InstrumentationKind>.GetInstance(); CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "version": displayVersion = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { foreach (InstrumentationKind instrumentationKind in ParseInstrumentationKinds(value, diagnostics)) { if (!instrumentationKinds.Contains(instrumentationKind)) { instrumentationKinds.Add(instrumentationKind); } } } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; case "embed": if (string.IsNullOrEmpty(value)) { embedAllSourceFiles = true; continue; } embeddedFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } if (embedAllSourceFiles) { embeddedFiles.AddRange(sourceFiles); } if (embeddedFiles.Count > 0) { // Restricted to portable PDBs for now, but the IsPortable condition should be removed // and the error message adjusted accordingly when native PDB support is added. if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_CannotEmbedWithoutPdb); } } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrumentationKinds: instrumentationKinds.ToImmutableAndFree() ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, DisplayVersion = displayVersion, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer, EmbeddedFiles = embeddedFiles.AsImmutable() }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private static IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private static IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } private static IEnumerable<InstrumentationKind> ParseInstrumentationKinds(string value, IList<Diagnostic> diagnostics) { string[] kinds = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var kind in kinds) { switch (kind.ToLower()) { case "testcoverage": yield return InstrumentationKind.TestCoverage; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidInstrumentationKind, kind); break; } } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, out LanguageVersion version) { if (str == null) { version = LanguageVersion.Default; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "7": version = LanguageVersion.CSharp7; return true; case "default": version = LanguageVersion.Default; return true; case "latest": version = LanguageVersion.Latest; return true; default: // We are likely to introduce minor version numbers after C# 7, thus breaking the // one-to-one correspondence between the integers and the corresponding // LanguageVersion enum values. But for compatibility we continue to accept any // integral value parsed by int.TryParse for its corresponding LanguageVersion enum // value for language version C# 6 and earlier (e.g. leading zeros are allowed) int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && versionNumber <= 6 && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = LanguageVersion.Default; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using BenchmarkDotNet.Attributes; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.Benchmarks.Config; using Umbraco.Web.PublishedCache.XmlPublishedCache; namespace Umbraco.Tests.Benchmarks { [QuickRunWithMemoryDiagnoserConfig] public class XmlPublishedContentInitBenchmarks { public XmlPublishedContentInitBenchmarks() { _xml10 = Build(10); _xml100 = Build(100); _xml1000 = Build(1000); _xml10000 = Build(10000); } private readonly string[] _intAttributes = { "id", "parentID", "nodeType", "level", "writerID", "creatorID", "template", "sortOrder", "isDoc", "isDraft" }; private readonly string[] _strAttributes = { "nodeName", "urlName", "writerName", "creatorName", "path" }; private readonly string[] _dateAttributes = { "createDate", "updateDate" }; private readonly string[] _guidAttributes = { "key", "version" }; private XmlDocument Build(int children) { var xml = new XmlDocument(); var root = Build(xml, "Home", 10); for (int i = 0; i < children; i++) { var child = Build(xml, "child" + i, 10); root.AppendChild(child); } xml.AppendChild(root); return xml; } private XmlElement Build(XmlDocument xml, string name, int propertyCount) { var random = new Random(); var content = xml.CreateElement(name); foreach (var p in _intAttributes) { var a = xml.CreateAttribute(p); a.Value = random.Next(1, 9).ToInvariantString(); content.Attributes.Append(a); } foreach (var p in _strAttributes) { var a = xml.CreateAttribute(p); a.Value = Guid.NewGuid().ToString(); content.Attributes.Append(a); } foreach (var p in _guidAttributes) { var a = xml.CreateAttribute(p); a.Value = Guid.NewGuid().ToString(); content.Attributes.Append(a); } foreach (var p in _dateAttributes) { var a = xml.CreateAttribute(p); a.Value = DateTime.Now.ToString("o"); content.Attributes.Append(a); } for (int i = 0; i < propertyCount; i++) { var prop = xml.CreateElement("prop" + i); var cdata = xml.CreateCDataSection(string.Join("", Enumerable.Range(0, 10).Select(x => Guid.NewGuid().ToString()))); prop.AppendChild(cdata); content.AppendChild(prop); } return content; } private readonly XmlDocument _xml10; private readonly XmlDocument _xml100; private readonly XmlDocument _xml1000; private readonly XmlDocument _xml10000; //out props int id, nodeType, level, writerId, creatorId, template, sortOrder; Guid key, version; string name, urlName, writerName, creatorName, docTypeAlias, path; bool isDraft; DateTime createDate, updateDate; PublishedContentType publishedContentType; Dictionary<string, IPublishedProperty> properties; [Benchmark(Baseline = true, OperationsPerInvoke = 10)] public void Original_10_Children() { OriginalInitializeNode(_xml10.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_100_Children() { OriginalInitializeNode(_xml100.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_1000_Children() { OriginalInitializeNode(_xml1000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Original_10000_Children() { OriginalInitializeNode(_xml10000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_10_Children() { XmlPublishedContent.InitializeNode(_xml10.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_100_Children() { XmlPublishedContent.InitializeNode(_xml100.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_1000_Children() { XmlPublishedContent.InitializeNode(_xml1000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } [Benchmark(OperationsPerInvoke = 10)] public void Enhanced_10000_Children() { XmlPublishedContent.InitializeNode(_xml10000.DocumentElement, false, false, out id, out key, out template, out sortOrder, out name, out writerName, out urlName, out creatorName, out creatorId, out writerId, out docTypeAlias, out nodeType, out path, out version, out createDate, out updateDate, out level, out isDraft, out publishedContentType, out properties, GetPublishedContentType); } internal static void OriginalInitializeNode(XmlNode xmlNode, bool legacy, bool isPreviewing, out int id, out Guid key, out int template, out int sortOrder, out string name, out string writerName, out string urlName, out string creatorName, out int creatorId, out int writerId, out string docTypeAlias, out int docTypeId, out string path, out Guid version, out DateTime createDate, out DateTime updateDate, out int level, out bool isDraft, out PublishedContentType contentType, out Dictionary<string, IPublishedProperty> properties) { //initialize the out params with defaults: writerName = null; docTypeAlias = null; id = template = sortOrder = template = creatorId = writerId = docTypeId = level = default(int); key = version = default(Guid); name = writerName = urlName = creatorName = docTypeAlias = path = null; createDate = updateDate = default(DateTime); isDraft = false; contentType = null; properties = null; //return if this is null if (xmlNode == null) { return; } if (xmlNode.Attributes != null) { id = int.Parse(xmlNode.Attributes.GetNamedItem("id").Value); if (xmlNode.Attributes.GetNamedItem("key") != null) // because, migration key = Guid.Parse(xmlNode.Attributes.GetNamedItem("key").Value); if (xmlNode.Attributes.GetNamedItem("template") != null) template = int.Parse(xmlNode.Attributes.GetNamedItem("template").Value); if (xmlNode.Attributes.GetNamedItem("sortOrder") != null) sortOrder = int.Parse(xmlNode.Attributes.GetNamedItem("sortOrder").Value); if (xmlNode.Attributes.GetNamedItem("nodeName") != null) name = xmlNode.Attributes.GetNamedItem("nodeName").Value; if (xmlNode.Attributes.GetNamedItem("writerName") != null) writerName = xmlNode.Attributes.GetNamedItem("writerName").Value; if (xmlNode.Attributes.GetNamedItem("urlName") != null) urlName = xmlNode.Attributes.GetNamedItem("urlName").Value; // Creatorname is new in 2.1, so published xml might not have it! try { creatorName = xmlNode.Attributes.GetNamedItem("creatorName").Value; } catch { creatorName = writerName; } //Added the actual userID, as a user cannot be looked up via full name only... if (xmlNode.Attributes.GetNamedItem("creatorID") != null) creatorId = int.Parse(xmlNode.Attributes.GetNamedItem("creatorID").Value); if (xmlNode.Attributes.GetNamedItem("writerID") != null) writerId = int.Parse(xmlNode.Attributes.GetNamedItem("writerID").Value); if (legacy) { if (xmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null) docTypeAlias = xmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value; } else { docTypeAlias = xmlNode.Name; } if (xmlNode.Attributes.GetNamedItem("nodeType") != null) docTypeId = int.Parse(xmlNode.Attributes.GetNamedItem("nodeType").Value); if (xmlNode.Attributes.GetNamedItem("path") != null) path = xmlNode.Attributes.GetNamedItem("path").Value; if (xmlNode.Attributes.GetNamedItem("version") != null) version = new Guid(xmlNode.Attributes.GetNamedItem("version").Value); if (xmlNode.Attributes.GetNamedItem("createDate") != null) createDate = DateTime.Parse(xmlNode.Attributes.GetNamedItem("createDate").Value); if (xmlNode.Attributes.GetNamedItem("updateDate") != null) updateDate = DateTime.Parse(xmlNode.Attributes.GetNamedItem("updateDate").Value); if (xmlNode.Attributes.GetNamedItem("level") != null) level = int.Parse(xmlNode.Attributes.GetNamedItem("level").Value); isDraft = (xmlNode.Attributes.GetNamedItem("isDraft") != null); } // load data var dataXPath = legacy ? "data" : "* [not(@isDoc)]"; var nodes = xmlNode.SelectNodes(dataXPath); contentType = GetPublishedContentType(PublishedItemType.Content, docTypeAlias); var propertyNodes = new Dictionary<string, XmlNode>(); if (nodes != null) foreach (XmlNode n in nodes) { var attrs = n.Attributes; if (attrs == null) continue; var alias = legacy ? attrs.GetNamedItem("alias").Value : n.Name; propertyNodes[alias.ToLowerInvariant()] = n; } properties = contentType.PropertyTypes.Select(p => { XmlNode n; return propertyNodes.TryGetValue(p.PropertyTypeAlias.ToLowerInvariant(), out n) ? new XmlPublishedProperty(p, isPreviewing, n) : new XmlPublishedProperty(p, isPreviewing); }).Cast<IPublishedProperty>().ToDictionary( x => x.PropertyTypeAlias, x => x, StringComparer.OrdinalIgnoreCase); } private static PublishedContentType GetPublishedContentType(PublishedItemType type, string alias) { return new PublishedContentType(alias, new string[] { }, new List<PublishedPropertyType>(Enumerable.Range(0, 10).Select(x => new PublishedPropertyType("prop" + x, 0, "test", initConverters: false)))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Orchard.ContentManagement; using Orchard.ContentManagement.MetaData; using Orchard.ContentManagement.MetaData.Models; using Orchard.Core.Common.Models; using Orchard.Core.Containers.Models; using Orchard.Core.Containers.Services; using Orchard.Core.Containers.ViewModels; using Orchard.Core.Contents; using Orchard.Core.Contents.ViewModels; using Orchard.Core.Title.Models; using Orchard.Data; using Orchard.DisplayManagement; using Orchard.Lists.Helpers; using Orchard.Lists.ViewModels; using Orchard.Localization; using Orchard.Logging; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.UI.Navigation; using Orchard.UI.Notify; using ContentOptions = Orchard.Lists.ViewModels.ContentOptions; using ContentsBulkAction = Orchard.Lists.ViewModels.ContentsBulkAction; using ListContentsViewModel = Orchard.Lists.ViewModels.ListContentsViewModel; namespace Orchard.Lists.Controllers { public class AdminController : Controller { private readonly IContentManager _contentManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IOrchardServices _services; private readonly IContainerService _containerService; private readonly IListViewService _listViewService; private readonly ITransactionManager _transactionManager; public AdminController( IOrchardServices services, IContentDefinitionManager contentDefinitionManager, IShapeFactory shapeFactory, IContainerService containerService, IListViewService listViewService, ITransactionManager transactionManager) { _services = services; _contentManager = services.ContentManager; _contentDefinitionManager = contentDefinitionManager; T = NullLocalizer.Instance; Logger = NullLogger.Instance; Shape = shapeFactory; _containerService = containerService; _listViewService = listViewService; _transactionManager = transactionManager; } public Localizer T { get; set; } public ILogger Logger { get; set; } dynamic Shape { get; set; } public ActionResult Index(Core.Contents.ViewModels.ListContentsViewModel model, PagerParameters pagerParameters) { var query = _containerService.GetContainersQuery(VersionOptions.Latest); if (!String.IsNullOrEmpty(model.TypeName)) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName); if (contentTypeDefinition == null) return HttpNotFound(); model.TypeDisplayName = !String.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName) ? contentTypeDefinition.DisplayName : contentTypeDefinition.Name; query = query.ForType(model.TypeName); } switch (model.Options.OrderBy) { case ContentsOrder.Modified: query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc); break; case ContentsOrder.Published: query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc); break; case ContentsOrder.Created: query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc); break; } model.Options.SelectedFilter = model.TypeName; model.Options.FilterOptions = _containerService.GetContainerTypes() .Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName)) .ToList().OrderBy(kvp => kvp.Value); var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters); var pagerShape = Shape.Pager(pager).TotalItemCount(query.Count()); var pageOfLists = query.Slice(pager.GetStartIndex(), pager.PageSize); var listsShape = Shape.List(); listsShape.AddRange(pageOfLists.Select(x => _contentManager.BuildDisplay(x, "SummaryAdmin")).ToList()); var viewModel = Shape.ViewModel() .Lists(listsShape) .Pager(pagerShape) .Options(model.Options); return View(viewModel); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] public ActionResult ListFilterPOST(ContentOptions options) { var routeValues = ControllerContext.RouteData.Values; if (options != null) { routeValues["Options.OrderBy"] = options.OrderBy; if (_containerService.GetContainerTypes().Any(ctd => string.Equals(ctd.Name, options.SelectedFilter, StringComparison.OrdinalIgnoreCase))) { routeValues["id"] = options.SelectedFilter; } else { routeValues.Remove("id"); } } return RedirectToAction("Index", routeValues); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.BulkEdit")] public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, PagerParameters pagerParameters) { if (itemIds != null) { var checkedContentItems = _contentManager.GetMany<ContentItem>(itemIds, VersionOptions.Latest, QueryHints.Empty); switch (options.BulkAction) { case ContentsBulkAction.None: break; case ContentsBulkAction.PublishNow: foreach (var item in checkedContentItems) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected lists."))) { _transactionManager.Cancel(); return new HttpUnauthorizedResult(); } _contentManager.Publish(item); } _services.Notifier.Information(T("Lists successfully published.")); break; case ContentsBulkAction.Unpublish: foreach (var item in checkedContentItems) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected lists."))) { _transactionManager.Cancel(); return new HttpUnauthorizedResult(); } _contentManager.Unpublish(item); } _services.Notifier.Information(T("Lists successfully unpublished.")); break; case ContentsBulkAction.Remove: foreach (var item in checkedContentItems) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected lists."))) { _transactionManager.Cancel(); return new HttpUnauthorizedResult(); } _contentManager.Remove(item); } _services.Notifier.Information(T("Lists successfully removed.")); break; default: throw new ArgumentOutOfRangeException(); } } return RedirectToAction("Index", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize }); } public ActionResult Create(string id) { if (String.IsNullOrWhiteSpace(id)) { var containerTypes = _containerService.GetContainerTypes().ToList(); if (containerTypes.Count > 1) { return RedirectToAction("SelectType"); } return RedirectToAction("Create", new {id = containerTypes.First().Name}); } return RedirectToAction("Create", "Admin", new {area = "Contents", id, returnUrl = Url.Action("Index", "Admin", new { area = "Orchard.Lists" })}); } public ActionResult SelectType() { var viewModel = Shape.ViewModel().ContainerTypes(_containerService.GetContainerTypes().ToList()); return View(viewModel); } public ActionResult List(ListContentsViewModel model, PagerParameters pagerParameters) { var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters); var container = _contentManager.GetLatest(model.ContainerId); if (container == null || !container.Has<ContainerPart>()) { return HttpNotFound(); } model.ContainerDisplayName = container.ContentManager.GetItemMetadata(container).DisplayText; if (string.IsNullOrEmpty(model.ContainerDisplayName)) { model.ContainerDisplayName = container.ContentType; } var query = GetListContentItemQuery(model.ContainerId); if (query == null) { return HttpNotFound(); } var containerPart = container.As<ContainerPart>(); if (containerPart.EnablePositioning) { query = OrderByPosition(query); } else { switch (model.Options.OrderBy) { case SortBy.Modified: query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc); break; case SortBy.Published: query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc); break; case SortBy.Created: query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc); break; case SortBy.DisplayText: // Note: This will obviously not work for items without a TitlePart, but we're OK with that. query = query.OrderBy<TitlePartRecord>(cr => cr.Title); break; } } var listView = containerPart.AdminListView.BuildDisplay(new BuildListViewDisplayContext { New = _services.New, Container = containerPart, ContentQuery = query, Pager = pager, ContainerDisplayName = model.ContainerDisplayName }); var viewModel = Shape.ViewModel() .Pager(pager) .ListView(listView) .ListViewProvider(containerPart.AdminListView) .ListViewProviders(_listViewService.Providers.ToList()) .Options(model.Options) .Container(container) .ContainerId(model.ContainerId) .ContainerDisplayName(model.ContainerDisplayName) .ContainerContentType(container.ContentType) .ItemContentTypes(container.As<ContainerPart>().ItemContentTypes.ToList()) ; if (containerPart.Is<ContainablePart>()) { viewModel.ListNavigation(_services.New.ListNavigation(ContainablePart: containerPart.As<ContainablePart>())); } return View(viewModel); } [HttpPost, ActionName("List")] [FormValueRequired("submit.Order")] public ActionResult ListOrderPOST(ContentOptions options) { var routeValues = ControllerContext.RouteData.Values; if (options != null) { routeValues["Options.OrderBy"] = options.OrderBy; } return RedirectToAction("List", routeValues); } [HttpPost, ActionName("List")] [FormValueRequired("submit.BulkEdit")] public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, int? targetContainerId, PagerParameters pagerParameters, string returnUrl) { if (itemIds != null) { switch (options.BulkAction) { case ContentsBulkAction.None: break; case ContentsBulkAction.PublishNow: if (!BulkPublishNow(itemIds)) { return new HttpUnauthorizedResult(); } break; case ContentsBulkAction.Unpublish: if (!BulkUnpublish(itemIds)) { return new HttpUnauthorizedResult(); } break; case ContentsBulkAction.Remove: if (!BulkRemove(itemIds)) { return new HttpUnauthorizedResult(); } break; case ContentsBulkAction.RemoveFromList: if (!BulkRemoveFromList(itemIds)) { return new HttpUnauthorizedResult(); } break; case ContentsBulkAction.MoveToList: if (!BulkMoveToList(itemIds, targetContainerId)) { return new HttpUnauthorizedResult(); } break; default: throw new ArgumentOutOfRangeException(); } } return this.RedirectLocal(returnUrl, () => RedirectToAction("List", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize })); } [HttpPost] public ActionResult Insert(int containerId, int itemId, PagerParameters pagerParameters) { var container = _containerService.Get(containerId, VersionOptions.Latest); var item = _contentManager.Get(itemId, VersionOptions.Latest, new QueryHints().ExpandParts<CommonPart, ContainablePart>()); var commonPart = item.As<CommonPart>(); var previousItemContainer = commonPart.Container; var itemMetadata = _contentManager.GetItemMetadata(item); var containerMetadata = _contentManager.GetItemMetadata(container); var position = _containerService.GetFirstPosition(containerId) + 1; LocalizedString message; if (previousItemContainer == null) { message = T("{0} was moved to <a href=\"{1}\">{2}</a>", itemMetadata.DisplayText, Url.RouteUrl(containerMetadata.AdminRouteValues), containerMetadata.DisplayText); } else if (previousItemContainer.Id != containerId) { var previousItemContainerMetadata = _contentManager.GetItemMetadata(commonPart.Container); message = T("{0} was moved from <a href=\"{3}\">{4}</a> to <a href=\"{1}\">{2}</a>", itemMetadata.DisplayText, Url.RouteUrl(containerMetadata.AdminRouteValues), containerMetadata.DisplayText, Url.RouteUrl(previousItemContainerMetadata.AdminRouteValues), previousItemContainerMetadata.DisplayText); } else { message = T("{0} is already part of this list and was moved to the top.", itemMetadata.DisplayText); } _containerService.MoveItem(item.As<ContainablePart>(), container, position); _services.Notifier.Information(message); return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize }); } [HttpPost] public ActionResult UpdatePositions(int containerId, int oldIndex, int newIndex, PagerParameters pagerParameters) { var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters); var query = OrderByPosition(GetListContentItemQuery(containerId)); if (query == null) { return HttpNotFound(); } var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList(); var contentItem = pageOfContentItems[oldIndex]; pageOfContentItems.Remove(contentItem); pageOfContentItems.Insert(newIndex, contentItem); var index = pager.GetStartIndex() + pageOfContentItems.Count; foreach (var item in pageOfContentItems.Select(x => x.As<ContainablePart>())) { item.Position = --index; RePublish(item); } return new EmptyResult(); } [ActionName("List")] [HttpPost, FormValueRequired("submit.ListOp")] public ActionResult ListOperation(int containerId, ListOperation operation, SortBy? sortBy, SortDirection? sortByDirection, PagerParameters pagerParameters) { var items = _containerService.GetContentItems(containerId, VersionOptions.Latest).Select(x => x.As<ContainablePart>()); switch (operation) { case ViewModels.ListOperation.Reverse: _containerService.Reverse(items); _services.Notifier.Information(T("The list has been reversed.")); break; case ViewModels.ListOperation.Shuffle: _containerService.Shuffle(items); _services.Notifier.Information(T("The list has been shuffled.")); break; case ViewModels.ListOperation.Sort: _containerService.Sort(items, sortBy.GetValueOrDefault(), sortByDirection.GetValueOrDefault()); _services.Notifier.Information(T("The list has been sorted.")); break; default: _services.Notifier.Error(T("Please select an operation to perform on the list.")); break; } return RedirectToAction("List", new {containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize}); } [HttpPost, ActionName("List")] [FormValueRequired("listViewName")] public ActionResult ChangeListView(int containerId, string listViewName, PagerParameters pagerParameters) { var container = _containerService.Get(containerId, VersionOptions.Latest); if (container == null || !container.Has<ContainerPart>()) { return HttpNotFound(); } container.Record.AdminListViewName = listViewName; return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize }); } /// <summary> /// Only publishes the content if it is already published. /// </summary> private void RePublish(IContent content) { if(content.ContentItem.VersionRecord.Published) _contentManager.Publish(content.ContentItem); } private IContentQuery<ContentItem> GetListContentItemQuery(int containerId) { var containableTypes = GetContainableTypes().Select(ctd => ctd.Name).ToList(); if (containableTypes.Count == 0) { // Force the name to be matched against empty and return no items in the query containableTypes.Add(string.Empty); } var query = _contentManager .Query(VersionOptions.Latest, containableTypes.ToArray()) .Join<CommonPartRecord>().Where(cr => cr.Container.Id == containerId); return query; } private IContentQuery<ContentItem> OrderByPosition(IContentQuery<ContentItem> query) { return query.Join<ContainablePartRecord>().OrderByDescending(x => x.Position); } private IEnumerable<ContentTypeDefinition> GetContainableTypes() { return _contentDefinitionManager.ListTypeDefinitions().Where(ctd => ctd.Parts.Any(c => c.PartDefinition.Name == "ContainablePart")); } private bool BulkMoveToList(IEnumerable<int> selectedIds, int? targetContainerId) { if (!targetContainerId.HasValue) { _services.Notifier.Information(T("Please select the list to move the items to.")); return true; } var id = targetContainerId.Value; var targetContainer = _contentManager.Get<ContainerPart>(id); if (targetContainer == null) { _services.Notifier.Information(T("Please select the list to move the items to.")); return true; } var itemContentTypes = targetContainer.ItemContentTypes.ToList(); var containerDisplayText = _contentManager.GetItemMetadata(targetContainer).DisplayText ?? targetContainer.ContentItem.ContentType; var selectedItems = _contentManager.GetMany<ContainablePart>(selectedIds, VersionOptions.Latest, QueryHints.Empty); foreach (var item in selectedItems) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't move selected content."))) { return false; } // Ensure the item can be in that container. if (itemContentTypes.Any() && itemContentTypes.All(x => x.Name != item.ContentItem.ContentType)) { _services.TransactionManager.Cancel(); _services.Notifier.Warning(T("One or more items could not be moved to '{0}' because it is restricted to containing items of type '{1}'.", containerDisplayText, itemContentTypes.Select(x => x.DisplayName).ToOrString(T))); return true; // todo: transactions } _containerService.MoveItem(item, targetContainer); } _services.Notifier.Information(T("Content successfully moved to <a href=\"{0}\">{1}</a>.", Url.Action("List", new { containerId = targetContainerId }), containerDisplayText)); return true; } private bool BulkRemoveFromList(IEnumerable<int> itemIds) { var selectedItems = _contentManager.GetMany<ContainablePart>(itemIds, VersionOptions.Latest, QueryHints.Empty); foreach (var item in selectedItems) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't remove selected content from the list."))) { _services.TransactionManager.Cancel(); return false; } item.As<CommonPart>().Record.Container = null; _containerService.UpdateItemPath(item.ContentItem); } _services.Notifier.Information(T("Content successfully removed from the list.")); return true; } private bool BulkRemove(IEnumerable<int> itemIds) { foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected content."))) { _services.TransactionManager.Cancel(); return false; } _contentManager.Remove(item); } _services.Notifier.Information(T("Content successfully removed.")); return true; } private bool BulkUnpublish(IEnumerable<int> itemIds) { foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected content."))) { _services.TransactionManager.Cancel(); return false; } _contentManager.Unpublish(item); } _services.Notifier.Information(T("Content successfully unpublished.")); return true; } private bool BulkPublishNow(IEnumerable<int> itemIds) { foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) { if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected content."))) { _services.TransactionManager.Cancel(); return false; } _contentManager.Publish(item); } _services.Notifier.Information(T("Content successfully published.")); return true; } } }
/* ==================================================================== */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; // need this for the properties metadata using System.Xml; using System.Text.RegularExpressions; using Oranikle.Report.Engine; using System.Drawing.Design; using System.Globalization; using System.Windows.Forms.Design; using System.Windows.Forms; namespace Oranikle.ReportDesigner { /// <summary> /// PropertyImage - The System.Drawing.Image specific Properties /// </summary> internal class PropertyImage : PropertyReportItem { internal PropertyImage(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris) : base(d, dc, ris) { } [CategoryAttribute("System.Drawing.Image"), DescriptionAttribute("The image properties.")] public PropertyImageI Image { get { return new PropertyImageI(this); } } } [TypeConverter(typeof(PropertyImageConverter)), Editor(typeof(PropertyImageUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyImageI : IReportItem { PropertyImage _pi; internal PropertyImageI(PropertyImage pi) { _pi = pi; } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageSourceConverter)), DescriptionAttribute("System.Drawing.Image Source:External, Embedded, Database.")] public string Source { get { return _pi.GetValue("Source", "External"); } set { _pi.SetValue("Source", value); } } [RefreshProperties(RefreshProperties.Repaint), DescriptionAttribute("Value depends upon the source of the image.")] public PropertyExpr Value { get { return new PropertyExpr(_pi.GetValue("Value", "")); } set { _pi.SetValue("Value", value.Expression); } } [RefreshProperties(RefreshProperties.Repaint), TypeConverter(typeof(ImageMIMETypeConverter)), DescriptionAttribute("When Source is Database MIMEType describes the type of image.")] public string MIMEType { get { return _pi.GetValue("MIMEType", ""); } set { if (string.Compare(this.Source.Trim(), "database", true) == 0) throw new ArgumentException("MIMEType isn't relevent when Source isn't Database."); _pi.SetValue("MIMEType", value); } } [DescriptionAttribute("Defines how image is sized when image doesn't match specified size.")] public ImageSizingEnum Sizing { get { string s = _pi.GetValue("Sizing", "AutoSize"); return ImageSizing.GetStyle(s); } set { _pi.SetValue("Sizing", value.ToString()); } } public override string ToString() { string s = this.Source; string v = ""; if (s.ToLower().Trim() != "none") v = this.Value.Expression; return string.Format("{0} {1}", s, v); } #region IReportItem Members public PropertyReportItem GetPRI() { return this._pi; } #endregion } #region ImageConverter internal class PropertyImageConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyImageI)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyImage) { PropertyImageI pi = value as PropertyImageI; return pi.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #endregion #region UIEditor internal class PropertyImageUIEditor : UITypeEditor { internal PropertyImageUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyImage pre = iri.GetPRI() as PropertyImage; PropertyImageI pbi = value as PropertyImageI; if (pbi == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.ImageCtl, null)) { /////// // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyImageI(pre); } return base.EditValue(context, provider, value); } } } #endregion }
// 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.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Python.Parsing; using Microsoft.PythonTools; using Microsoft.PythonTools.Common; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.Python; using TestUtilities.UI; using TestUtilities.UI.Python; using Path = System.IO.Path; namespace PythonToolsUITests { public class EnvironmentUITests { const string TestPackageSpec = "ptvsd==2.2.0"; const string TestPackageDisplay = "ptvsd (2.2.0)"; static DefaultInterpreterSetter InitPython2(PythonVisualStudioApp app) { var dis = app.SelectDefaultInterpreter(PythonPaths.Python27 ?? PythonPaths.Python27_x64); var pm = app.OptionsService.GetPackageManagers(dis.CurrentDefault).FirstOrDefault(); try { if (!pm.GetInstalledPackageAsync(new PackageSpec("virtualenv"), CancellationTokens.After60s).WaitAndUnwrapExceptions().IsValid) { pm.InstallAsync(new PackageSpec("virtualenv"), new TestPackageManagerUI(), CancellationTokens.After60s).WaitAndUnwrapExceptions(); } var r = dis; dis = null; return r; } finally { dis?.Dispose(); } } static DefaultInterpreterSetter InitPython3(PythonVisualStudioApp app) { return app.SelectDefaultInterpreter( PythonPaths.Python37 ?? PythonPaths.Python37_x64 ?? PythonPaths.Python36 ?? PythonPaths.Python36_x64 ?? PythonPaths.Python35 ?? PythonPaths.Python35_x64 ); } static EnvDTE.Project CreateTemporaryProject(VisualStudioApp app, [CallerMemberName] string projectName = null) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.PythonApplicationTemplate, TestData.GetTempPath(), projectName ?? Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) ); Assert.IsNotNull(project, "Project was not created"); return project; } public void InstallUninstallPackage(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var env = app.CreateProjectVirtualEnvironment(project, out string envName); env.Select(); app.ExecuteCommand("Python.InstallPackage", "/p:" + TestPackageSpec); var azure = app.SolutionExplorerTreeView.WaitForChildOfProject( project, TimeSpan.FromSeconds(30), Strings.Environments, envName, TestPackageDisplay ); azure.Select(); using (var confirmation = AutomationDialog.FromDte(app, "Edit.Delete")) { confirmation.OK(); } app.SolutionExplorerTreeView.WaitForChildOfProjectRemoved( project, Strings.Environments, envName, TestPackageDisplay ); } } public void CreateInstallRequirementsTxt(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var projectHome = project.GetPythonProject().ProjectHome; File.WriteAllText(Path.Combine(projectHome, "requirements.txt"), TestPackageSpec); var env = app.CreateProjectVirtualEnvironment(project, out string envName); env.Select(); app.SolutionExplorerTreeView.WaitForChildOfProject( project, Strings.Environments, envName, TestPackageDisplay ); } } public void InstallGenerateRequirementsTxt(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var env = app.CreateProjectVirtualEnvironment(project, out string envName); env.Select(); try { app.ExecuteCommand("Python.InstallRequirementsTxt", "/y", timeout: 5000); Assert.Fail("Command should not have executed"); } catch (AggregateException ae) { ae.Handle(ex => ex is COMException); } catch (COMException) { } var requirementsTxt = Path.Combine(Path.GetDirectoryName(project.FullName), "requirements.txt"); File.WriteAllText(requirementsTxt, TestPackageSpec); app.ExecuteCommand("Python.InstallRequirementsTxt", "/y"); app.SolutionExplorerTreeView.WaitForChildOfProject( project, TimeSpan.FromSeconds(30), Strings.Environments, envName, TestPackageDisplay ); File.Delete(requirementsTxt); app.ExecuteCommand("Python.GenerateRequirementsTxt", "/e:\"" + envName + "\""); app.SolutionExplorerTreeView.WaitForChildOfProject( project, "requirements.txt" ); AssertUtil.ContainsAtLeast( File.ReadAllLines(requirementsTxt).Select(s => s.Trim()), TestPackageSpec ); } } public void LoadVEnv(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var projectName = project.UniqueName; var env = app.CreateProjectVirtualEnvironment(project, out string envName); var solution = app.Dte.Solution.FullName; app.Dte.Solution.Close(true); app.Dte.Solution.Open(solution); project = app.Dte.Solution.Item(projectName); app.OpenSolutionExplorer().WaitForChildOfProject( project, TimeSpan.FromSeconds(60), Strings.Environments, envName ); } } public void ActivateVEnv(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); Assert.AreNotEqual(null, project.ProjectItems.Item(Path.GetFileNameWithoutExtension(app.Dte.Solution.FullName) + ".py")); var id0 = (string)project.Properties.Item("InterpreterId").Value; var env1 = app.CreateProjectVirtualEnvironment(project, out string envName1); var env2 = app.CreateProjectVirtualEnvironment(project, out string envName2); // At this point, env2 is active var id2 = (string)project.Properties.Item("InterpreterId").Value; Assert.AreNotEqual(id0, id2); // Activate env1 (previously stored node is now invalid, we need to query again) env1 = app.OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName1); env1.Select(); app.Dte.ExecuteCommand("Python.ActivateEnvironment"); var id1 = (string)project.Properties.Item("InterpreterId").Value; Assert.AreNotEqual(id0, id1); Assert.AreNotEqual(id2, id1); // Activate env2 app.SolutionExplorerTreeView.SelectProject(project); app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"" + envName2 + "\""); var id2b = (string)project.Properties.Item("InterpreterId").Value; Assert.AreEqual(id2, id2b); } } public void RemoveVEnv(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var env = app.CreateProjectVirtualEnvironment(project, out string envName, out string envPath); env.Select(); using (var removeDeleteDlg = RemoveItemDialog.FromDte(app)) { removeDeleteDlg.Remove(); } app.OpenSolutionExplorer().WaitForChildOfProjectRemoved( project, Strings.Environments, envName ); Assert.IsTrue(Directory.Exists(envPath), envPath); } } public void DeleteVEnv(PythonVisualStudioApp app) { using (var procs = new ProcessScope("Microsoft.PythonTools.Analyzer")) using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); TreeNode env = app.CreateProjectVirtualEnvironment(project, out string envName, out string envPath); // Need to wait some more for the database to be loaded. app.WaitForNoDialog(TimeSpan.FromSeconds(10.0)); for (int retries = 3; !procs.ExitNewProcesses() && retries >= 0; --retries) { Thread.Sleep(1000); Console.WriteLine("Failed to close all analyzer processes (remaining retries {0})", retries); } env.Select(); using (var removeDeleteDlg = RemoveItemDialog.FromDte(app)) { removeDeleteDlg.Delete(); } app.WaitForNoDialog(TimeSpan.FromSeconds(5.0)); app.OpenSolutionExplorer().WaitForChildOfProjectRemoved( project, Strings.Environments, envName ); for (int retries = 10; Directory.Exists(envPath) && retries > 0; --retries) { Thread.Sleep(1000); } Assert.IsFalse(Directory.Exists(envPath), envPath); } } public void DefaultBaseInterpreterSelection(PythonVisualStudioApp app) { // The project that will be loaded references these environments. PythonPaths.Python27.AssertInstalled(); PythonPaths.Python37.AssertInstalled(); using (var dis = InitPython3(app)) { var sln = app.CopyProjectForTest(@"TestData\Environments.sln"); var project = app.OpenProject(sln); app.OpenSolutionExplorer().SelectProject(project); app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"Python 2.7 (32-bit)\""); var environmentsNode = app.OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments); environmentsNode.Select(); using (var createVenv = AddVirtualEnvironmentDialogWrapper.FromDte(app)) { var baseInterp = createVenv.BaseInterpreter; Assert.AreEqual("Python 2.7 (32-bit)", baseInterp); createVenv.Cancel(); } app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"Python 3.7 (32-bit)\""); environmentsNode = app.OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments); environmentsNode.Select(); using (var createVenv = AddVirtualEnvironmentDialogWrapper.FromDte(app)) { var baseInterp = createVenv.BaseInterpreter; Assert.AreEqual("Python 3.7 (32-bit)", baseInterp); createVenv.Cancel(); } } } public void ProjectCreateVEnv(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var pm = app.OptionsService.GetPackageManagers(dis.CurrentDefault).FirstOrDefault(); if (pm.GetInstalledPackageAsync(new PackageSpec("virtualenv"), CancellationTokens.After60s).WaitAndUnwrapExceptions().IsValid) { if (!pm.UninstallAsync(new PackageSpec("virtualenv"), new TestPackageManagerUI(), CancellationTokens.After60s).WaitAndUnwrapExceptions()) { Assert.Fail("Failed to uninstall 'virtualenv' from {0}", dis.CurrentDefault.Configuration.GetPrefixPath()); } } var project = CreateTemporaryProject(app); var env = app.CreateProjectVirtualEnvironment(project, out string envName); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); Assert.AreEqual(string.Format("env (Python {0} ({1}))", dis.CurrentDefault.Configuration.Version, dis.CurrentDefault.Configuration.Architecture ), envName); } } public void ProjectCreateCondaEnvFromPackages(PythonVisualStudioApp app) { var project = CreateTemporaryProject(app); var env = app.CreateProjectCondaEnvironment(project, "python=3.7 requests", null, null, out string envName, out string envPath); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); FileUtils.DeleteDirectory(envPath); } public void ProjectCreateCondaEnvFromEnvFile(PythonVisualStudioApp app) { var envFilePath = CreateTempEnvYml(); var project = CreateTemporaryProject(app); var envFileItem = project.ProjectItems.AddFromFileCopy(envFilePath); var env = app.CreateProjectCondaEnvironment(project, null, envFileItem.FileNames[0], envFileItem.FileNames[0], out string envName, out string envPath); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); FileUtils.DeleteDirectory(envPath); } public void ProjectAddExistingVEnvLocal(PythonVisualStudioApp app) { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37 ?? PythonPaths.Python36_x64 ?? PythonPaths.Python36 ?? PythonPaths.Python35_x64 ?? PythonPaths.Python35; python.AssertInstalled(); var project = CreateTemporaryProject(app); var envPath = TestData.GetTempPath("venv"); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\\Environments\\venv"), envPath); File.WriteAllText(Path.Combine(envPath, "pyvenv.cfg"), string.Format(@"home = {0} include-system-site-packages = false version = 3.{1}.0", python.PrefixPath, python.Version.ToVersion().Minor)); var env = app.AddProjectLocalCustomEnvironment(project, envPath, null, python.Configuration.Version.ToString(), python.Architecture.ToString(), out string envName); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); Assert.AreEqual( string.Format("venv (Python 3.{0} (32-bit))", python.Version.ToVersion().Minor), envName ); } public void ProjectAddCustomEnvLocal(PythonVisualStudioApp app) { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37 ?? PythonPaths.Python36_x64 ?? PythonPaths.Python36 ?? PythonPaths.Python35_x64 ?? PythonPaths.Python35; python.AssertInstalled(); var project = CreateTemporaryProject(app); var envPath = python.PrefixPath; var env = app.AddProjectLocalCustomEnvironment(project, envPath, "Test", python.Configuration.Version.ToString(), python.Architecture.ToString(), out string envName); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); Assert.AreEqual( string.Format("Test", python.Version.ToVersion().Minor), envName ); } public void ProjectAddExistingEnv(PythonVisualStudioApp app) { var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37 ?? PythonPaths.Python36_x64 ?? PythonPaths.Python36 ?? PythonPaths.Python35_x64 ?? PythonPaths.Python35; python.AssertInstalled(); var project = CreateTemporaryProject(app); var envPath = python.PrefixPath; var env = app.AddExistingEnvironment(project, envPath, out string envName); Assert.IsNotNull(env); Assert.IsNotNull(env.Element); Assert.AreEqual( string.Format("Python 3.{0} (32-bit)", python.Version.ToVersion().Minor), envName ); } public void WorkspaceCreateVEnv(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37); // Create virtual environment dialog, it should by default create it // under the workspace root folder, using the current environment as the base. // Since there's no other virtual env in the workspace, it should be named "env" app.CreateWorkspaceVirtualEnvironment(out string baseEnvDesc, out string envPath); Assert.IsTrue( PathUtils.IsSameDirectory(Path.Combine(workspaceFolder, "env"), envPath), "venv should be created in env subfolder of worskpace" ); Assert.AreEqual( baseEnvDesc, globalDefault37.Configuration.Description, "venv should use current interpreter as base env" ); var expectedEnvName = "env ({0}, {1})".FormatInvariant( globalDefault37.Configuration.Version, globalDefault37.Configuration.ArchitectureString ); CheckSwitcherEnvironment(app, expectedEnvName); } } public void WorkspaceCreateCondaEnvFromPackages(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37); // Create conda environment dialog, using a list of packages app.CreateWorkspaceCondaEnvironment("python=3.7 requests", null, null, out _, out string envPath, out string envDesc); try { CheckSwitcherEnvironment(app, envDesc); } finally { FileUtils.DeleteDirectory(envPath); } } } public void WorkspaceCreateCondaEnvFromNoPackages(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37); // Create conda environment dialog with no packages app.CreateWorkspaceCondaEnvironment("", null, null, out _, out string envPath, out string envDesc); try { CheckSwitcherEnvironment(app, envDesc); } finally { FileUtils.DeleteDirectory(envPath); } } } public void WorkspaceCreateCondaEnvFromEnvFile(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37); var envFilePath = CreateTempEnvYml(); // Create conda environment dialog, using a environment.yml // that is located outside of workspace root. app.CreateWorkspaceCondaEnvironment(null, envFilePath, null, out _, out string envPath, out string envDesc); try { CheckSwitcherEnvironment(app, envDesc); } finally { FileUtils.DeleteDirectory(envPath); } } } public void WorkspaceAddExistingEnv(PythonVisualStudioApp app) { var python37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; python37.AssertInstalled(); var python27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27; python27.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(python27)) { var workspaceFolder = CreateAndOpenWorkspace(app, python27); // Add existing environment dialog, selecting an already detected environment app.AddWorkspaceExistingEnvironment(python37.PrefixPath, out string envDesc); Assert.AreEqual( string.Format("Python {0} ({1})", python37.Version.ToVersion(), python37.Architecture), envDesc ); CheckSwitcherEnvironment(app, envDesc); } } public void WorkspaceAddCustomEnvLocal(PythonVisualStudioApp app) { var python27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27; python27.AssertInstalled(); var basePython = PythonPaths.Python37_x64 ?? PythonPaths.Python37; basePython.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(python27)) { var workspaceFolder = CreateAndOpenWorkspace(app, python27); // Create a virtual environment in a folder outside the workspace // Note: we need to use a real virtual env for this, because the // workspace factory provider runs the env's python.exe. var envPath = basePython.CreateVirtualEnv(VirtualEnvName.First); // Add existing virtual environment dialog, custom path to a // virtual env located outside of workspace root. app.AddWorkspaceLocalCustomEnvironment( envPath, null, basePython.Configuration.Version.ToString(), basePython.Architecture.ToString() ); var envDesc = string.Format("testenv ({0}, {1})", basePython.Version.ToVersion(), basePython.Architecture); CheckSwitcherEnvironment(app, envDesc); } } public void LaunchUnknownEnvironment(PythonVisualStudioApp app) { var sln = app.CopyProjectForTest(@"TestData\Environments\Unknown.sln"); var project = app.OpenProject(sln); app.ExecuteCommand("Debug.Start"); app.CheckMessageBox(MessageBoxButton.Close, "Global|PythonCore|2.8|x86", "incorrectly configured"); } private void EnvironmentReplWorkingDirectoryTest( PythonVisualStudioApp app, EnvDTE.Project project, TreeNode env ) { var path1 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N")); var path2 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(path1); Directory.CreateDirectory(path2); app.OpenSolutionExplorer().SelectProject(project); app.Dte.ExecuteCommand("Python.Interactive"); using (var window = app.GetInteractiveWindow(string.Format("{0} Interactive", project.Name))) { Assert.IsNotNull(window, string.Format("Failed to find '{0} Interactive'", project.Name)); app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path1)); window.Reset(); window.ExecuteText("import os; os.getcwd()").Wait(); window.WaitForTextEnd( string.Format("'{0}'", path1.Replace("\\", "\\\\")), ">" ); app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path2)); window.Reset(); window.ExecuteText("import os; os.getcwd()").Wait(); window.WaitForTextEnd( string.Format("'{0}'", path2.Replace("\\", "\\\\")), ">" ); } } public void EnvironmentReplWorkingDirectory(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); app.ServiceProvider.GetUIThread().Invoke(() => { var pp = project.GetPythonProject(); pp.AddInterpreter(dis.CurrentDefault.Configuration.Id); }); var envName = dis.CurrentDefault.Configuration.Description; var sln = app.OpenSolutionExplorer(); var env = sln.FindChildOfProject(project, Strings.Environments, envName); EnvironmentReplWorkingDirectoryTest(app, project, env); } } public void VirtualEnvironmentReplWorkingDirectory(PythonVisualStudioApp app) { using (var dis = InitPython3(app)) { var project = CreateTemporaryProject(app); var env = app.CreateProjectVirtualEnvironment(project, out _); EnvironmentReplWorkingDirectoryTest(app, project, env); } } public void SwitcherSingleProject(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); var added27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27; added27.AssertInstalled(); var added36 = PythonPaths.Python36_x64 ?? PythonPaths.Python36; added36.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { // Project has no references, uses global default var project = CreateTemporaryProject(app); CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description); // Project has one referenced interpreter app.ServiceProvider.GetUIThread().Invoke(() => { var pp = project.GetPythonProject(); pp.AddInterpreter(added27.Configuration.Id); }); CheckSwitcherEnvironment(app, added27.Configuration.Description); // Project has two referenced interpreters (active remains the same) app.ServiceProvider.GetUIThread().Invoke(() => { var pp = project.GetPythonProject(); pp.AddInterpreter(added36.Configuration.Id); }); CheckSwitcherEnvironment(app, added27.Configuration.Description); // No switcher visible when solution closed and no file opened app.Dte.Solution.Close(SaveFirst: false); CheckSwitcherEnvironment(app, null); } } public void SwitcherWorkspace(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); var python27 = PythonPaths.Python27_x64; python27.AssertInstalled(); var folders = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath("TestData", "EnvironmentsSwitcherFolders"), folders); var folder1 = Path.Combine(folders, "WorkspaceWithoutSettings"); var folder2 = Path.Combine(folders, "WorkspaceWithSettings"); var folder3 = Path.Combine(folders, "WorkspaceNoPython"); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { // Hidden before any file is opened CheckSwitcherEnvironment(app, null); // Workspace without PythonSettings.json shows global default app.OpenFolder(folder1); app.OpenDocument(Path.Combine(folder1, "app1.py")); CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description); // Workspace with PythonSettings.json - Python 2.7 (64-bit) app.OpenFolder(folder2); app.OpenDocument(Path.Combine(folder2, "app2.py")); CheckSwitcherEnvironment(app, python27.Configuration.Description); // Keep showing even after opening non-python files app.OpenDocument(Path.Combine(folder2, "app2.cpp")); CheckSwitcherEnvironment(app, python27.Configuration.Description); // Workspace without python file app.OpenFolder(folder3); CheckSwitcherEnvironment(app, null); app.OpenDocument(Path.Combine(folder3, "app3.cpp")); CheckSwitcherEnvironment(app, null); app.Dte.Solution.Close(); CheckSwitcherEnvironment(app, null); } } public void SwitcherNoProject(PythonVisualStudioApp app) { var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37; globalDefault37.AssertInstalled(); using (var dis = app.SelectDefaultInterpreter(globalDefault37)) { // Loose Python file shows global default app.OpenDocument(TestData.GetPath("TestData", "Environments", "Program.py")); CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description); // No switcher visible when solution closed and no file opened app.Dte.ActiveWindow.Close(); CheckSwitcherEnvironment(app, null); // No switcher visible when loose cpp file open app.OpenDocument(TestData.GetPath("TestData", "Environments", "Program.cpp")); CheckSwitcherEnvironment(app, null); } } private string CreateAndOpenWorkspace(PythonVisualStudioApp app, PythonVersion expectedFactory) { var workspaceFolder = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath("TestData", "EnvironmentsSwitcherFolders", "WorkspaceWithoutSettings"), workspaceFolder); app.OpenFolder(workspaceFolder); app.OpenDocument(Path.Combine(workspaceFolder, "app1.py")); CheckSwitcherEnvironment(app, expectedFactory.Configuration.Description); return workspaceFolder; } private static string CreateTempEnvYml() { var envFileContents = @"name: test dependencies: - cookies==2.2.1"; var envFilePath = Path.Combine(TestData.GetTempPath("EnvFiles"), "environment.yml"); File.WriteAllText(envFilePath, envFileContents); return envFilePath; } private void CheckSwitcherEnvironment(PythonVisualStudioApp app, string expectedDescription) { var expectedVisible = expectedDescription != null; var switchMgr = app.PythonToolsService.EnvironmentSwitcherManager; for (int i = 10; i >= 0; i--) { var actualVisible = UIContext.FromUIContextGuid(CommonGuidList.guidPythonToolbarUIContext).IsActive; var actualDescription = switchMgr.CurrentFactory?.Configuration.Description; if (actualVisible == expectedVisible && actualDescription == expectedDescription) { return; } if (i == 0) { Assert.AreEqual(expectedVisible, actualVisible); Assert.AreEqual(expectedDescription, actualDescription); } else { Thread.Sleep(500); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Localization; using OrchardCore.Data; using OrchardCore.Email; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Models; using OrchardCore.Modules; using OrchardCore.Mvc.Utilities; using OrchardCore.Recipes.Models; using OrchardCore.Setup.Services; using OrchardCore.Tenants.ViewModels; namespace OrchardCore.Tenants.Controllers { [Route("api/tenants")] [ApiController] [Authorize(AuthenticationSchemes = "Api"), IgnoreAntiforgeryToken, AllowAnonymous] public class ApiController : Controller { private readonly IShellHost _shellHost; private readonly IShellSettingsManager _shellSettingsManager; private readonly IEnumerable<DatabaseProvider> _databaseProviders; private readonly IAuthorizationService _authorizationService; private readonly IDataProtectionProvider _dataProtectorProvider; private readonly ISetupService _setupService; private readonly ShellSettings _currentShellSettings; private readonly IClock _clock; private readonly IEmailAddressValidator _emailAddressValidator; private readonly IStringLocalizer S; public ApiController( IShellHost shellHost, ShellSettings currentShellSettings, IAuthorizationService authorizationService, IShellSettingsManager shellSettingsManager, IEnumerable<DatabaseProvider> databaseProviders, IDataProtectionProvider dataProtectorProvider, ISetupService setupService, IClock clock, IEmailAddressValidator emailAddressValidator, IStringLocalizer<AdminController> stringLocalizer) { _dataProtectorProvider = dataProtectorProvider; _setupService = setupService; _clock = clock; _shellHost = shellHost; _authorizationService = authorizationService; _shellSettingsManager = shellSettingsManager; _databaseProviders = databaseProviders; _currentShellSettings = currentShellSettings; _emailAddressValidator = emailAddressValidator ?? throw new ArgumentNullException(nameof(emailAddressValidator)); S = stringLocalizer; } [HttpPost] [Route("create")] public async Task<IActionResult> Create(CreateApiViewModel model) { if (!IsDefaultShell()) { return Forbid(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return this.ChallengeOrForbid("Api"); } if (!String.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) { ModelState.AddModelError(nameof(CreateApiViewModel.Name), S["Invalid tenant name. Must contain characters only and no spaces."]); } // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.State = TenantState.Uninitialized; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["Secret"] = Guid.NewGuid().ToString(); shellSettings["RecipeName"] = model.RecipeName; if (String.IsNullOrWhiteSpace(shellSettings.RequestUrlHost) && String.IsNullOrWhiteSpace(shellSettings.RequestUrlPrefix)) { ModelState.AddModelError(nameof(CreateApiViewModel.RequestUrlPrefix), S["Host and url prefix can not be empty at the same time."]); } if (!String.IsNullOrWhiteSpace(shellSettings.RequestUrlPrefix)) { if (shellSettings.RequestUrlPrefix.Contains('/')) { ModelState.AddModelError(nameof(CreateApiViewModel.RequestUrlPrefix), S["The url prefix can not contain more than one segment."]); } } if (ModelState.IsValid) { if (_shellHost.TryGetSettings(model.Name, out var settings)) { // Site already exists, return 201 for indempotency purpose var token = CreateSetupToken(settings); return StatusCode(201, GetEncodedUrl(settings, token)); } else { await _shellHost.UpdateShellSettingsAsync(shellSettings); var token = CreateSetupToken(shellSettings); return Ok(GetEncodedUrl(shellSettings, token)); } } return BadRequest(ModelState); } [HttpPost] [Route("setup")] public async Task<ActionResult> Setup(SetupApiViewModel model) { if (!IsDefaultShell()) { return this.ChallengeOrForbid("Api"); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return this.ChallengeOrForbid("Api"); } if (!ModelState.IsValid) { return BadRequest(); } if (!_emailAddressValidator.Validate(model.Email)) { return BadRequest(S["Invalid email."]); } if (!_shellHost.TryGetSettings(model.Name, out var shellSettings)) { ModelState.AddModelError(nameof(SetupApiViewModel.Name), S["Tenant not found: '{0}'", model.Name]); } if (shellSettings.State == TenantState.Running) { return StatusCode(201); } if (shellSettings.State != TenantState.Uninitialized) { return BadRequest(S["The tenant can't be setup."]); } var databaseProvider = shellSettings["DatabaseProvider"]; if (String.IsNullOrEmpty(databaseProvider)) { databaseProvider = model.DatabaseProvider; } var selectedProvider = _databaseProviders.FirstOrDefault(x => String.Equals(x.Value, databaseProvider, StringComparison.OrdinalIgnoreCase)); if (selectedProvider == null) { return BadRequest(S["The database provider is not defined."]); } var tablePrefix = shellSettings["TablePrefix"]; if (String.IsNullOrEmpty(tablePrefix)) { tablePrefix = model.TablePrefix; } var connectionString = shellSettings["connectionString"]; if (String.IsNullOrEmpty(connectionString)) { connectionString = model.ConnectionString; } if (selectedProvider.HasConnectionString && String.IsNullOrEmpty(connectionString)) { return BadRequest(S["The connection string is required for this database provider."]); } var recipeName = shellSettings["RecipeName"]; if (String.IsNullOrEmpty(recipeName)) { recipeName = model.RecipeName; } RecipeDescriptor recipeDescriptor = null; if (String.IsNullOrEmpty(recipeName)) { if (model.Recipe == null) { return BadRequest(S["Either 'Recipe' or 'RecipeName' is required."]); } var tempFilename = Path.GetTempFileName(); using (var fs = System.IO.File.Create(tempFilename)) { await model.Recipe.CopyToAsync(fs); } var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(tempFilename)); recipeDescriptor = new RecipeDescriptor { FileProvider = fileProvider, BasePath = "", RecipeFileInfo = fileProvider.GetFileInfo(Path.GetFileName(tempFilename)) }; } else { var setupRecipes = await _setupService.GetSetupRecipesAsync(); recipeDescriptor = setupRecipes.FirstOrDefault(x => String.Equals(x.Name, recipeName, StringComparison.OrdinalIgnoreCase)); if (recipeDescriptor == null) { return BadRequest(S["Recipe '{0}' not found.", recipeName]); } } var setupContext = new SetupContext { ShellSettings = shellSettings, SiteName = model.SiteName, EnabledFeatures = null, // default list, AdminUsername = model.UserName, AdminEmail = model.Email, AdminPassword = model.Password, Errors = new Dictionary<string, string>(), Recipe = recipeDescriptor, SiteTimeZone = model.SiteTimeZone, DatabaseProvider = selectedProvider.Value, DatabaseConnectionString = connectionString, DatabaseTablePrefix = tablePrefix }; var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return StatusCode(500, ModelState); } return Ok(executionId); } private bool IsDefaultShell() { return String.Equals(_currentShellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase); } private string GetEncodedUrl(ShellSettings shellSettings, string token) { var requestHost = Request.Host; var host = shellSettings.RequestUrlHost?.Split(',', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? requestHost.Host; var port = requestHost.Port; if (port.HasValue) { host += ":" + port; } var hostString = new HostString(host); var pathString = HttpContext.Features.Get<ShellContextFeature>().OriginalPathBase; if (!String.IsNullOrEmpty(shellSettings.RequestUrlPrefix)) { pathString = pathString.Add('/' + shellSettings.RequestUrlPrefix); } QueryString queryString; if (!String.IsNullOrEmpty(token)) { queryString = QueryString.Create("token", token); } return $"{Request.Scheme}://{hostString + pathString + queryString}"; } private string CreateSetupToken(ShellSettings shellSettings) { // Create a public url to setup the new tenant var dataProtector = _dataProtectorProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); var token = dataProtector.Protect(shellSettings["Secret"], _clock.UtcNow.Add(new TimeSpan(24, 0, 0))); return token; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Partitions { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; /// <summary> /// Base class for classes which represent a disk partitioning scheme. /// </summary> /// <remarks>After modifying the table, by creating or deleting a partition assume that any /// previously stored partition indexes of higher value are no longer valid. Re-enumerate /// the partitions to discover the next index-to-partition mapping.</remarks> public abstract class PartitionTable { private static List<PartitionTableFactory> s_factories; /// <summary> /// Gets the GUID that uniquely identifies this disk, if supported (else returns <c>null</c>). /// </summary> public abstract Guid DiskGuid { get; } /// <summary> /// Gets the list of partitions that contain user data (i.e. non-system / empty). /// </summary> public abstract ReadOnlyCollection<PartitionInfo> Partitions { get; } /// <summary> /// Gets the number of User partitions on the disk. /// </summary> public int Count { get { return Partitions.Count; } } private static List<PartitionTableFactory> Factories { get { if (s_factories == null) { List<PartitionTableFactory> factories = new List<PartitionTableFactory>(); foreach (var type in ReflectionHelper.GetAssembly(typeof(VolumeManager)).GetTypes()) { foreach (PartitionTableFactoryAttribute attr in ReflectionHelper.GetCustomAttributes(type, typeof(PartitionTableFactoryAttribute), false)) { factories.Add((PartitionTableFactory)Activator.CreateInstance(type)); } } s_factories = factories; } return s_factories; } } /// <summary> /// Gets information about a particular User partition. /// </summary> /// <param name="index">The index of the partition.</param> /// <returns>Information about the partition.</returns> public PartitionInfo this[int index] { get { return Partitions[index]; } } /// <summary> /// Determines if a disk is partitioned with a known partitioning scheme. /// </summary> /// <param name="content">The content of the disk to check.</param> /// <returns><c>true</c> if the disk is partitioned, else <c>false</c>.</returns> public static bool IsPartitioned(Stream content) { foreach (var partTableFactory in Factories) { if (partTableFactory.DetectIsPartitioned(content)) { return true; } } return false; } /// <summary> /// Determines if a disk is partitioned with a known partitioning scheme. /// </summary> /// <param name="disk">The disk to check.</param> /// <returns><c>true</c> if the disk is partitioned, else <c>false</c>.</returns> public static bool IsPartitioned(VirtualDisk disk) { return IsPartitioned(disk.Content); } /// <summary> /// Gets all of the partition tables found on a disk. /// </summary> /// <param name="disk">The disk to inspect.</param> /// <returns>It is rare for a disk to have multiple partition tables, but theoretically /// possible.</returns> public static IList<PartitionTable> GetPartitionTables(VirtualDisk disk) { List<PartitionTable> tables = new List<PartitionTable>(); foreach (var factory in Factories) { PartitionTable table = factory.DetectPartitionTable(disk); if (table != null) { tables.Add(table); } } return tables; } /// <summary> /// Gets all of the partition tables found on a disk. /// </summary> /// <param name="contentStream">The content of the disk to inspect.</param> /// <returns>It is rare for a disk to have multiple partition tables, but theoretically /// possible.</returns> public static IList<PartitionTable> GetPartitionTables(Stream contentStream) { return GetPartitionTables(new Raw.Disk(contentStream, Ownership.None)); } /// <summary> /// Creates a new partition that encompasses the entire disk. /// </summary> /// <param name="type">The partition type.</param> /// <param name="active">Whether the partition is active (bootable).</param> /// <returns>The index of the partition.</returns> /// <remarks>The partition table must be empty before this method is called, /// otherwise IOException is thrown.</remarks> public abstract int Create(WellKnownPartitionType type, bool active); /// <summary> /// Creates a new partition with a target size. /// </summary> /// <param name="size">The target size (in bytes).</param> /// <param name="type">The partition type.</param> /// <param name="active">Whether the partition is active (bootable).</param> /// <returns>The index of the new partition.</returns> public abstract int Create(long size, WellKnownPartitionType type, bool active); /// <summary> /// Creates a new aligned partition that encompasses the entire disk. /// </summary> /// <param name="type">The partition type.</param> /// <param name="active">Whether the partition is active (bootable).</param> /// <param name="alignment">The alignment (in byte).</param> /// <returns>The index of the partition.</returns> /// <remarks>The partition table must be empty before this method is called, /// otherwise IOException is thrown.</remarks> /// <remarks> /// Traditionally partitions were aligned to the physical structure of the underlying disk, /// however with modern storage greater efficiency is acheived by aligning partitions on /// large values that are a power of two. /// </remarks> public abstract int CreateAligned(WellKnownPartitionType type, bool active, int alignment); /// <summary> /// Creates a new aligned partition with a target size. /// </summary> /// <param name="size">The target size (in bytes).</param> /// <param name="type">The partition type.</param> /// <param name="active">Whether the partition is active (bootable).</param> /// <param name="alignment">The alignment (in byte).</param> /// <returns>The index of the new partition.</returns> /// <remarks> /// Traditionally partitions were aligned to the physical structure of the underlying disk, /// however with modern storage greater efficiency is achieved by aligning partitions on /// large values that are a power of two. /// </remarks> public abstract int CreateAligned(long size, WellKnownPartitionType type, bool active, int alignment); /// <summary> /// Deletes a partition at a given index. /// </summary> /// <param name="index">The index of the partition.</param> public abstract void Delete(int index); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. 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 NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Lists; using osu.Framework.Threading; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneDelayedLoadUnloadWrapper : FrameworkTestScene { private const int panel_count = 1024; private FillFlowContainer<Container> flow; private TestScrollContainer scroll; [Resolved] private Game game { get; set; } [SetUp] public void SetUp() => Schedule(() => { Children = new Drawable[] { scroll = new TestScrollContainer { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { flow = new FillFlowContainer<Container> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, } } } }; }); [Test] public void TestUnloadViaScroll() { WeakList<Container> references = new WeakList<Container>(); AddStep("populate panels", () => { references.Clear(); for (int i = 0; i < 16; i++) { flow.Add(new Container { Size = new Vector2(128), Children = new Drawable[] { new DelayedLoadUnloadWrapper(() => { var container = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new TestBox { RelativeSizeAxes = Axes.Both } }, }; references.Add(container); return container; }, 500, 2000), new SpriteText { Text = i.ToString() }, } }); } flow.Add( new Container { Size = new Vector2(128, 1280), }); }); AddUntilStep("references loaded", () => references.Count() == 16 && references.All(c => c.IsLoaded)); AddStep("scroll to end", () => scroll.ScrollToEnd()); AddUntilStep("references lost", () => { GC.Collect(); return !references.Any(); }); AddStep("scroll to start", () => scroll.ScrollToStart()); AddUntilStep("references restored", () => references.Count() == 16); } [Test] public void TestTasksCanceledDuringLoadSequence() { var references = new WeakList<TestBox>(); AddStep("populate panels", () => { references.Clear(); for (int i = 0; i < 16; i++) { DelayedLoadUnloadWrapper loadUnloadWrapper; flow.Add(new Container { Size = new Vector2(128), Child = loadUnloadWrapper = new DelayedLoadUnloadWrapper(() => { var content = new TestBox { RelativeSizeAxes = Axes.Both }; references.Add(content); return content; }, 0), }); // cancel load tasks after the delayed load has started. loadUnloadWrapper.DelayedLoadStarted += _ => game.Schedule(() => loadUnloadWrapper.UnbindAllBindables()); } }); AddStep("remove all panels", () => flow.Clear(false)); AddUntilStep("references lost", () => { GC.Collect(); return !references.Any(); }); } [Test] public void TestRemovedStillUnload() { WeakList<Container> references = new WeakList<Container>(); AddStep("populate panels", () => { references.Clear(); for (int i = 0; i < 16; i++) { flow.Add(new Container { Size = new Vector2(128), Children = new Drawable[] { new DelayedLoadUnloadWrapper(() => { var container = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new TestBox { RelativeSizeAxes = Axes.Both } }, }; references.Add(container); return container; }, 500, 2000), new SpriteText { Text = i.ToString() }, } }); } }); AddUntilStep("references loaded", () => references.Count() == 16 && references.All(c => c.IsLoaded)); AddStep("Remove all panels", () => flow.Clear(false)); AddUntilStep("references lost", () => { GC.Collect(); return !references.Any(); }); } [Test] public void TestRemoveThenAdd() { WeakList<Container> references = new WeakList<Container>(); int loadCount = 0; AddStep("populate panels", () => { references.Clear(); loadCount = 0; for (int i = 0; i < 16; i++) { flow.Add(new Container { Size = new Vector2(128), Children = new Drawable[] { new DelayedLoadUnloadWrapper(() => { TestBox testBox; var container = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { testBox = new TestBox { RelativeSizeAxes = Axes.Both } }, }; testBox.OnLoadComplete += _ => { references.Add(container); loadCount++; }; return container; }, 500, 2000), new SpriteText { Text = i.ToString() }, } }); } }); IReadOnlyList<Container> previousChildren = null; AddUntilStep("all loaded", () => loadCount == 16); AddStep("Remove all panels", () => { previousChildren = flow.Children.ToList(); flow.Clear(false); }); AddStep("Add panels back", () => flow.Children = previousChildren); AddWaitStep("wait for potential unload", 20); AddAssert("load count hasn't changed", () => loadCount == 16); } [Test] public void TestManyChildrenUnload() { int loaded = 0; AddStep("populate panels", () => { loaded = 0; for (int i = 1; i < panel_count; i++) { flow.Add(new Container { Size = new Vector2(128), Children = new Drawable[] { new DelayedLoadUnloadWrapper(() => new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new TestBox(() => loaded++) { RelativeSizeAxes = Axes.Both } } }, 500, 2000), new SpriteText { Text = i.ToString() }, } }); } }); int childrenWithAvatarsLoaded() => flow.Children.Count(c => c.Children.OfType<DelayedLoadWrapper>().First().Content?.IsLoaded ?? false); int loadCount1 = 0; int loadCount2 = 0; AddUntilStep("wait for load", () => loaded > 0); AddStep("scroll down", () => { loadCount1 = loaded; scroll.ScrollToEnd(); }); AddUntilStep("more loaded", () => { loadCount2 = childrenWithAvatarsLoaded(); return loaded > loadCount1; }); AddAssert("not too many loaded", () => childrenWithAvatarsLoaded() < panel_count / 4); AddUntilStep("wait some unloaded", () => childrenWithAvatarsLoaded() < loadCount2); } [Test] public void TestWrapperExpiry() { var wrappers = new List<DelayedLoadUnloadWrapper>(); AddStep("populate panels", () => { for (int i = 1; i < 16; i++) { var wrapper = new DelayedLoadUnloadWrapper(() => new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new TestBox { RelativeSizeAxes = Axes.Both } } }, 500, 2000); wrappers.Add(wrapper); flow.Add(new Container { Size = new Vector2(128), Children = new Drawable[] { wrapper, new SpriteText { Text = i.ToString() }, } }); } }); int childrenWithAvatarsLoaded() => flow.Children.Count(c => c.Children.OfType<DelayedLoadWrapper>().FirstOrDefault()?.Content?.IsLoaded ?? false); AddUntilStep("wait some loaded", () => childrenWithAvatarsLoaded() > 5); AddStep("expire wrappers", () => wrappers.ForEach(w => w.Expire())); AddAssert("all unloaded", () => childrenWithAvatarsLoaded() == 0); } [Test] public void TestUnloadWithNonOptimisingParent() { DelayedLoadUnloadWrapper wrapper = null; AddStep("add panel", () => { Add(new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(128), Masking = true, Child = wrapper = new DelayedLoadUnloadWrapper(() => new TestBox { RelativeSizeAxes = Axes.Both }, 0, 1000) }); }); AddUntilStep("wait for load", () => wrapper.Content?.IsLoaded == true); AddStep("move wrapper outside", () => wrapper.X = 129); AddUntilStep("wait for unload", () => wrapper.Content?.IsLoaded != true); } [Test] public void TestUnloadWithOffscreenParent() { Container parent = null; DelayedLoadUnloadWrapper wrapper = null; AddStep("add panel", () => { Add(parent = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(128), Masking = true, Child = wrapper = new DelayedLoadUnloadWrapper(() => new TestBox { RelativeSizeAxes = Axes.Both }, 0, 1000) }); }); AddUntilStep("wait for load", () => wrapper.Content?.IsLoaded == true); AddStep("move parent offscreen", () => parent.X = 1000000); // Should be offscreen AddUntilStep("wait for unload", () => wrapper.Content?.IsLoaded != true); } [Test] public void TestUnloadWithParentRemovedFromHierarchy() { Container parent = null; DelayedLoadUnloadWrapper wrapper = null; AddStep("add panel", () => { Add(parent = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(128), Masking = true, Child = wrapper = new DelayedLoadUnloadWrapper(() => new TestBox { RelativeSizeAxes = Axes.Both }, 0, 1000) }); }); AddUntilStep("wait for load", () => wrapper.Content?.IsLoaded == true); AddStep("remove parent", () => Remove(parent)); AddUntilStep("wait for unload", () => wrapper.Content?.IsLoaded != true); } [Test] public void TestUnloadedWhenAsyncLoadCompletedAndMaskedAway() { BasicScrollContainer scrollContainer = null; DelayedLoadTestDrawable child = null; AddStep("add panel", () => { Child = scrollContainer = new BasicScrollContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(128), Child = new Container { RelativeSizeAxes = Axes.X, Height = 1000, Child = new Container { RelativeSizeAxes = Axes.X, Height = 128, Child = new DelayedLoadUnloadWrapper(() => child = new DelayedLoadTestDrawable { RelativeSizeAxes = Axes.Both }, 0, 1000) { RelativeSizeAxes = Axes.X, Height = 128 } } } }; }); // Check that the child is disposed when its async-load completes while the wrapper is masked away. AddAssert("wait for load to begin", () => child?.LoadState == LoadState.Loading); AddStep("scroll to end", () => scrollContainer.ScrollToEnd(false)); AddStep("allow load", () => child.AllowLoad.Set()); AddUntilStep("drawable disposed", () => child.IsDisposed); // Check that reuse of the child is not attempted. Drawable lastChild = null; AddStep("store child", () => lastChild = child); AddStep("scroll to start", () => scrollContainer.ScrollToStart(false)); AddWaitStep("wait some frames", 2); AddAssert("child not loaded", () => lastChild.LoadState != LoadState.Loaded); } public class TestScrollContainer : BasicScrollContainer { public new Scheduler Scheduler => base.Scheduler; } public class TestBox : Container { private readonly Action onLoadAction; public TestBox(Action onLoadAction = null) { this.onLoadAction = onLoadAction; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { onLoadAction?.Invoke(); Child = new SpriteText { Colour = Color4.Yellow, Text = @"loaded", Anchor = Anchor.Centre, Origin = Anchor.Centre, }; } } public class DelayedLoadTestDrawable : CompositeDrawable { public readonly ManualResetEventSlim AllowLoad = new ManualResetEventSlim(false); [BackgroundDependencyLoader] private void load() { if (!AllowLoad.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } } } }
// // PangoUtils.cs // // Author: // Michael Hutchinson <[email protected]> // // Copyright (c) 2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Gtk; using System.Runtime.InteropServices; using System.Collections.Generic; using Xwt.Drawing; namespace Xwt.GtkBackend { public static class GtkInterop { internal const string LIBATK = "libatk-1.0-0.dll"; internal const string LIBGLIB = "libglib-2.0-0.dll"; internal const string LIBGOBJECT = "libgobject-2.0-0.dll"; internal const string LIBPANGO = "libpango-1.0-0.dll"; internal const string LIBPANGOCAIRO = "libpangocairo-1.0-0.dll"; internal const string LIBFONTCONFIG = "fontconfig"; #if XWT_GTK3 internal const string LIBGTK = "libgtk-3-0.dll"; internal const string LIBGDK = "libgdk-3-0.dll"; internal const string LIBGTKGLUE = "gtksharpglue-3"; internal const string LIBGLIBGLUE = "glibsharpglue-3"; internal const string LIBWEBKIT = "libwebkitgtk-3.0-0.dll"; #else internal const string LIBGTK = "libgtk-win32-2.0-0.dll"; internal const string LIBGDK = "libgdk-win32-2.0-0.dll"; internal const string LIBGTKGLUE = "gtksharpglue-2"; internal const string LIBGLIBGLUE = "glibsharpglue-2"; internal const string LIBWEBKIT = "libwebkitgtk-1.0-0.dll"; #endif } /// <summary> /// This creates a Pango list and applies attributes to it with *much* less overhead than the GTK# version. /// </summary> internal class FastPangoAttrList : IDisposable { IntPtr list; public FastPangoAttrList () { list = pango_attr_list_new (); } public void AddAttributes (TextIndexer indexer, IEnumerable<TextAttribute> attrs) { foreach (var attr in attrs) AddAttribute (indexer, attr); } public void AddAttribute (TextIndexer indexer, TextAttribute attr) { var start = (uint) indexer.IndexToByteIndex (attr.StartIndex); var end = (uint) indexer.IndexToByteIndex (attr.StartIndex + attr.Count); if (attr is BackgroundTextAttribute) { var xa = (BackgroundTextAttribute)attr; AddBackgroundAttribute (xa.Color.ToGtkValue (), start, end); } else if (attr is ColorTextAttribute) { var xa = (ColorTextAttribute)attr; AddForegroundAttribute (xa.Color.ToGtkValue (), start, end); } else if (attr is FontWeightTextAttribute) { var xa = (FontWeightTextAttribute)attr; AddWeightAttribute ((Pango.Weight)(int)xa.Weight, start, end); } else if (attr is FontStyleTextAttribute) { var xa = (FontStyleTextAttribute)attr; AddStyleAttribute ((Pango.Style)(int)xa.Style, start, end); } else if (attr is UnderlineTextAttribute) { var xa = (UnderlineTextAttribute)attr; AddUnderlineAttribute (xa.Underline ? Pango.Underline.Single : Pango.Underline.None, start, end); } else if (attr is StrikethroughTextAttribute) { var xa = (StrikethroughTextAttribute)attr; AddStrikethroughAttribute (xa.Strikethrough, start, end); } else if (attr is FontTextAttribute) { var xa = (FontTextAttribute)attr; AddFontAttribute ((Pango.FontDescription)Toolkit.GetBackend (xa.Font), start, end); } else if (attr is LinkTextAttribute) { AddUnderlineAttribute (Pango.Underline.Single, start, end); AddForegroundAttribute (Colors.Blue.ToGtkValue (), start, end); } } public IntPtr Handle { get { return list; } } public void AddStyleAttribute (Pango.Style style, uint start, uint end) { Add (pango_attr_style_new (style), start, end); } public void AddWeightAttribute (Pango.Weight weight, uint start, uint end) { Add (pango_attr_weight_new (weight), start, end); } public void AddForegroundAttribute (Gdk.Color color, uint start, uint end) { Add (pango_attr_foreground_new (color.Red, color.Green, color.Blue), start, end); } public void AddBackgroundAttribute (Gdk.Color color, uint start, uint end) { Add (pango_attr_background_new (color.Red, color.Green, color.Blue), start, end); } public void AddUnderlineAttribute (Pango.Underline underline, uint start, uint end) { Add (pango_attr_underline_new (underline), start, end); } public void AddStrikethroughAttribute (bool strikethrough, uint start, uint end) { Add (pango_attr_strikethrough_new (strikethrough), start, end); } public void AddFontAttribute (Pango.FontDescription font, uint start, uint end) { Add (pango_attr_font_desc_new (font.Handle), start, end); } void Add (IntPtr attribute, uint start, uint end) { unsafe { PangoAttribute *attPtr = (PangoAttribute *) attribute; attPtr->start_index = start; attPtr->end_index = end; } pango_attr_list_insert (list, attribute); } [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_style_new (Pango.Style style); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_stretch_new (Pango.Stretch stretch); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_weight_new (Pango.Weight weight); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_foreground_new (ushort red, ushort green, ushort blue); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_background_new (ushort red, ushort green, ushort blue); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_underline_new (Pango.Underline underline); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_strikethrough_new (bool strikethrough); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_font_desc_new (IntPtr desc); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern IntPtr pango_attr_list_new (); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_unref (IntPtr list); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_insert (IntPtr list, IntPtr attr); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_layout_set_attributes (IntPtr layout, IntPtr attrList); [DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)] static extern void pango_attr_list_splice (IntPtr attr_list, IntPtr other, Int32 pos, Int32 len); public void Splice (Pango.AttrList attrs, int pos, int len) { pango_attr_list_splice (list, attrs.Handle, pos, len); } public void AssignTo (Pango.Layout layout) { pango_layout_set_attributes (layout.Handle, list); } [StructLayout (LayoutKind.Sequential)] struct PangoAttribute { public IntPtr klass; public uint start_index; public uint end_index; } public void Dispose () { pango_attr_list_unref (list); list = IntPtr.Zero; } } internal class TextIndexer { int[] indexToByteIndex; int[] byteIndexToIndex; public TextIndexer (string text) { SetupTables (text); } public int IndexToByteIndex (int i) { if (i >= indexToByteIndex.Length) return i; return indexToByteIndex[i]; } public int ByteIndexToIndex (int i) { return byteIndexToIndex[i]; } public void SetupTables (string text) { if (text == null) { this.indexToByteIndex = new int[0]; this.byteIndexToIndex = new int[0]; return; } var arr = text.ToCharArray (); int byteIndex = 0; int[] indexToByteIndex = new int[arr.Length]; var byteIndexToIndex = new List<int> (); for (int i = 0; i < arr.Length; i++) { indexToByteIndex[i] = byteIndex; byteIndex += System.Text.Encoding.UTF8.GetByteCount (arr, i, 1); while (byteIndexToIndex.Count < byteIndex) byteIndexToIndex.Add (i); } this.indexToByteIndex = indexToByteIndex; this.byteIndexToIndex = byteIndexToIndex.ToArray (); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace tdbadmin { /// <summary> /// Main Form for Season (saison) table. /// </summary> public class FSeason : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label Sai_e_id; private System.Windows.Forms.TextBox Sai_e_bez; private System.Windows.Forms.TextBox Sai_e_code; private System.Windows.Forms.TextBox Sai_e_text; private System.Windows.Forms.Label Sai_l_text; private System.Windows.Forms.Label Sai_l_code; private System.Windows.Forms.Label Sai_l_bez; private System.Windows.Forms.Label Sai_l_id; private System.Windows.Forms.Label Sai_l_bis; private System.Windows.Forms.Label Sai_l_von; private System.Windows.Forms.MonthCalendar Sai_e_bis; private System.Windows.Forms.MonthCalendar Sai_e_von; private System.Windows.Forms.GroupBox TDB_abgrp; private System.Windows.Forms.Button TDB_ab_clr; private System.Windows.Forms.Button TDB_ab_sel; private System.Windows.Forms.Button TDB_ab_exit; private System.Windows.Forms.Button TDB_ab_del; private System.Windows.Forms.Button TDB_ab_upd; private System.Windows.Forms.Button TDB_ab_ins; private tdbgui.GUIsai Sai; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FSeason() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // Sai = new tdbgui.GUIsai(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.Sai_e_id = new System.Windows.Forms.Label(); this.Sai_e_bez = new System.Windows.Forms.TextBox(); this.Sai_e_code = new System.Windows.Forms.TextBox(); this.Sai_e_text = new System.Windows.Forms.TextBox(); this.Sai_l_text = new System.Windows.Forms.Label(); this.Sai_l_code = new System.Windows.Forms.Label(); this.Sai_l_bez = new System.Windows.Forms.Label(); this.Sai_l_id = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.Sai_l_bis = new System.Windows.Forms.Label(); this.Sai_l_von = new System.Windows.Forms.Label(); this.Sai_e_bis = new System.Windows.Forms.MonthCalendar(); this.Sai_e_von = new System.Windows.Forms.MonthCalendar(); this.TDB_abgrp = new System.Windows.Forms.GroupBox(); this.TDB_ab_clr = new System.Windows.Forms.Button(); this.TDB_ab_sel = new System.Windows.Forms.Button(); this.TDB_ab_exit = new System.Windows.Forms.Button(); this.TDB_ab_del = new System.Windows.Forms.Button(); this.TDB_ab_upd = new System.Windows.Forms.Button(); this.TDB_ab_ins = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.TDB_abgrp.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.Sai_e_id); this.groupBox1.Controls.Add(this.Sai_e_bez); this.groupBox1.Controls.Add(this.Sai_e_code); this.groupBox1.Controls.Add(this.Sai_e_text); this.groupBox1.Controls.Add(this.Sai_l_text); this.groupBox1.Controls.Add(this.Sai_l_code); this.groupBox1.Controls.Add(this.Sai_l_bez); this.groupBox1.Controls.Add(this.Sai_l_id); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(608, 192); this.groupBox1.TabIndex = 12; this.groupBox1.TabStop = false; this.groupBox1.Text = "Season Description"; // // Sai_e_id // this.Sai_e_id.Location = new System.Drawing.Point(136, 24); this.Sai_e_id.Name = "Sai_e_id"; this.Sai_e_id.Size = new System.Drawing.Size(64, 16); this.Sai_e_id.TabIndex = 9; // // Sai_e_bez // this.Sai_e_bez.Location = new System.Drawing.Point(136, 40); this.Sai_e_bez.Name = "Sai_e_bez"; this.Sai_e_bez.Size = new System.Drawing.Size(456, 20); this.Sai_e_bez.TabIndex = 0; this.Sai_e_bez.Text = ""; // // Sai_e_code // this.Sai_e_code.Location = new System.Drawing.Point(136, 64); this.Sai_e_code.Name = "Sai_e_code"; this.Sai_e_code.Size = new System.Drawing.Size(456, 20); this.Sai_e_code.TabIndex = 1; this.Sai_e_code.Text = ""; // // Sai_e_text // this.Sai_e_text.Location = new System.Drawing.Point(136, 88); this.Sai_e_text.Multiline = true; this.Sai_e_text.Name = "Sai_e_text"; this.Sai_e_text.Size = new System.Drawing.Size(456, 88); this.Sai_e_text.TabIndex = 2; this.Sai_e_text.Text = ""; // // Sai_l_text // this.Sai_l_text.Location = new System.Drawing.Point(8, 121); this.Sai_l_text.Name = "Sai_l_text"; this.Sai_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Sai_l_text.TabIndex = 4; this.Sai_l_text.Text = "Description"; // // Sai_l_code // this.Sai_l_code.Location = new System.Drawing.Point(8, 63); this.Sai_l_code.Name = "Sai_l_code"; this.Sai_l_code.TabIndex = 3; this.Sai_l_code.Text = "Code"; // // Sai_l_bez // this.Sai_l_bez.Location = new System.Drawing.Point(8, 39); this.Sai_l_bez.Name = "Sai_l_bez"; this.Sai_l_bez.TabIndex = 2; this.Sai_l_bez.Text = "Title"; // // Sai_l_id // this.Sai_l_id.Location = new System.Drawing.Point(8, 21); this.Sai_l_id.Name = "Sai_l_id"; this.Sai_l_id.TabIndex = 1; this.Sai_l_id.Text = "ID"; // // groupBox2 // this.groupBox2.Controls.Add(this.Sai_l_bis); this.groupBox2.Controls.Add(this.Sai_l_von); this.groupBox2.Controls.Add(this.Sai_e_bis); this.groupBox2.Controls.Add(this.Sai_e_von); this.groupBox2.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox2.Location = new System.Drawing.Point(0, 192); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(608, 208); this.groupBox2.TabIndex = 11; this.groupBox2.TabStop = false; this.groupBox2.Text = "From / To"; // // Sai_l_bis // this.Sai_l_bis.Location = new System.Drawing.Point(232, 24); this.Sai_l_bis.Name = "Sai_l_bis"; this.Sai_l_bis.Size = new System.Drawing.Size(100, 16); this.Sai_l_bis.TabIndex = 3; this.Sai_l_bis.Text = "To date"; // // Sai_l_von // this.Sai_l_von.Location = new System.Drawing.Point(8, 24); this.Sai_l_von.Name = "Sai_l_von"; this.Sai_l_von.Size = new System.Drawing.Size(100, 16); this.Sai_l_von.TabIndex = 2; this.Sai_l_von.Text = "From date"; // // Sai_e_bis // this.Sai_e_bis.Location = new System.Drawing.Point(232, 40); this.Sai_e_bis.Name = "Sai_e_bis"; this.Sai_e_bis.ShowWeekNumbers = true; this.Sai_e_bis.TabIndex = 4; // // Sai_e_von // this.Sai_e_von.Location = new System.Drawing.Point(8, 40); this.Sai_e_von.Name = "Sai_e_von"; this.Sai_e_von.ShowWeekNumbers = true; this.Sai_e_von.TabIndex = 3; // // TDB_abgrp // this.TDB_abgrp.Controls.Add(this.TDB_ab_clr); this.TDB_abgrp.Controls.Add(this.TDB_ab_sel); this.TDB_abgrp.Controls.Add(this.TDB_ab_exit); this.TDB_abgrp.Controls.Add(this.TDB_ab_del); this.TDB_abgrp.Controls.Add(this.TDB_ab_upd); this.TDB_abgrp.Controls.Add(this.TDB_ab_ins); this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Fill; this.TDB_abgrp.Location = new System.Drawing.Point(0, 400); this.TDB_abgrp.Name = "TDB_abgrp"; this.TDB_abgrp.Size = new System.Drawing.Size(608, 53); this.TDB_abgrp.TabIndex = 2; this.TDB_abgrp.TabStop = false; this.TDB_abgrp.Text = "Actions"; // // TDB_ab_clr // this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16); this.TDB_ab_clr.Name = "TDB_ab_clr"; this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34); this.TDB_ab_clr.TabIndex = 10; this.TDB_ab_clr.Text = "Clear"; this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click); // // TDB_ab_sel // this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255))); this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16); this.TDB_ab_sel.Name = "TDB_ab_sel"; this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34); this.TDB_ab_sel.TabIndex = 8; this.TDB_ab_sel.Text = "Select"; this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click); // // TDB_ab_exit // this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16); this.TDB_ab_exit.Name = "TDB_ab_exit"; this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34); this.TDB_ab_exit.TabIndex = 9; this.TDB_ab_exit.Text = "Exit"; this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click); // // TDB_ab_del // this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_del.Location = new System.Drawing.Point(153, 16); this.TDB_ab_del.Name = "TDB_ab_del"; this.TDB_ab_del.Size = new System.Drawing.Size(75, 34); this.TDB_ab_del.TabIndex = 7; this.TDB_ab_del.Text = "Delete"; this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click); // // TDB_ab_upd // this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16); this.TDB_ab_upd.Name = "TDB_ab_upd"; this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34); this.TDB_ab_upd.TabIndex = 6; this.TDB_ab_upd.Text = "Update"; this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click); // // TDB_ab_ins // this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16); this.TDB_ab_ins.Name = "TDB_ab_ins"; this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34); this.TDB_ab_ins.TabIndex = 5; this.TDB_ab_ins.Text = "Insert"; this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click); // // Season // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 453); this.Controls.Add(this.TDB_abgrp); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "Season"; this.Text = "Season"; this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.TDB_abgrp.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Season callbacks private void TDB_ab_sel_Click(object sender, System.EventArgs e) { SelForm Fsel = new SelForm(); Sai.Sel(Fsel.GetLV); Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return); Fsel.ShowDialog(this); } void TDB_ab_sel_Click_Return(object sender, EventArgs e) { int id = -1, rows = 0; SelForm Fsel = (SelForm)sender; id = Fsel.GetID; Sai.Get(id, ref rows); Sai_e_id.Text = Sai.ObjId.ToString(); Sai_e_bez.Text = Sai.ObjBez; Sai_e_code.Text = Sai.ObjCode; Sai_e_text.Text = Sai.ObjText; Sai_e_von.SetDate(Sai.ObjFrom); Sai_e_bis.SetDate(Sai.ObjTo); } private void TDB_ab_exit_Click(object sender, System.EventArgs e) { Close(); } private void TDB_ab_ins_Click(object sender, System.EventArgs e) { Sai.InsUpd(true, Sai_e_bez.Text, Sai_e_code.Text, Sai_e_von.SelectionStart , Sai_e_bis.SelectionStart, Sai_e_text.Text); Sai_e_id.Text = Sai.ObjId.ToString(); } private void TDB_ab_upd_Click(object sender, System.EventArgs e) { Sai.InsUpd(false, Sai_e_bez.Text, Sai_e_code.Text, Sai_e_von.SelectionStart , Sai_e_bis.SelectionStart, Sai_e_text.Text); } private void TDB_ab_del_Click(object sender, System.EventArgs e) { int rows = 0; Sai.Get(Convert.ToInt32(Sai_e_id.Text), ref rows); Sai.Delete(); } private void TDB_ab_clr_Click(object sender, System.EventArgs e) { DateTime now = DateTime.Now; Sai_e_id.Text = ""; Sai_e_bez.Text = ""; Sai_e_code.Text = ""; Sai_e_text.Text = ""; this.Sai_e_von.SetDate(now); this.Sai_e_bis.SetDate(now); } #endregion } }
using System; using System.Linq; using System.IO; using System.Collections.Generic; namespace FastCgiNet.Streams { /// <summary> /// A stream that represents a single record's contents. When in memory, this stream is implemented in a way that avoids /// unnecessary byte copying for socket operations. It also checks for invalid operations when it comes to FastCgi records. /// </summary> public class RecordContentsStream : Stream { //TODO: Watch out for large byte arrays, since this would promote them straight to Gen2 of the GC, // while they are in fact short lived objects private long position; /// <summary> /// The position of the first byte of this stream in the supplied stream. /// </summary> private long secondaryStoragePosition; private Stream secondaryStorageStream; /// <summary> /// Indicates whether the contents of this stream are stored in secondary storage. /// </summary> public bool InSecondaryStorage { get { return secondaryStorageStream != null; } } /// <summary> /// If not stored in secondary storage, this list represents all the the data that has been written to this stream. /// When using secondary storage, this is <c>null</c>. /// </summary> internal LinkedList<byte[]> MemoryBlocks; private int length; /// <summary> /// Whether this record's contents reached its maximum size. /// </summary> public bool IsFull { get { return length == RecordBase.MaxContentLength; } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); else if (buffer.Length < offset + count) throw new ArgumentException("The sum of offset and count is larger than the buffer length"); else if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException("offset or count is negative"); if (position == length) return 0; // 1. If we are reading from secondary storage, it is quite straight forward if (secondaryStorageStream != null) { var dataStream = secondaryStorageStream; dataStream.Seek(secondaryStoragePosition + position, SeekOrigin.Begin); return dataStream.Read(buffer, offset, count); } // 2. If we are reading from memory, then it is not so simple int positionSoFar = 0; int bytesCopied = 0; foreach (var arr in MemoryBlocks) { if (positionSoFar + arr.Length > position && positionSoFar < position + count) { int toArrayOffset = offset + bytesCopied; int startCopyingFrom = (int)position - positionSoFar; if (startCopyingFrom < 0) startCopyingFrom = 0; int copyLength = count - bytesCopied; if (copyLength + startCopyingFrom > arr.Length) copyLength = arr.Length - startCopyingFrom; Array.Copy(arr, startCopyingFrom, buffer, toArrayOffset, copyLength); bytesCopied += copyLength; } positionSoFar += arr.Length; } // Advances the stream position += bytesCopied; return bytesCopied; } public override long Seek(long offset, SeekOrigin origin) { // Users can seek anywhere, they just can't write or read out of bounds.. if (origin == SeekOrigin.Begin) position = offset; else if (origin == SeekOrigin.Current) position = position + offset; else if (origin == SeekOrigin.End) position = length + offset; return position; } public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Writes to this stream, effectively copying bytes from <paramref name="buffer"/> to internal buffers or to secondary storage accordingly. /// </summary> public override void Write(byte[] buffer, int offset, int count) { //TODO: Proper Write in positions other than the end of the stream if (position != length) throw new NotImplementedException("At the moment, only writing at the end of the stream is supported"); // 1. Secondary storage if (secondaryStorageStream != null) { var dataStream = secondaryStorageStream; dataStream.Write(buffer, offset, count); } // 2. In memory storage else { var internalBuffer = new byte[count]; Array.Copy(buffer, offset, internalBuffer, 0, count); MemoryBlocks.AddLast(internalBuffer); } length += count; position += count; // Check that we didn't go over the size limit if (length > RecordBase.MaxContentLength) throw new InvalidOperationException("You can't write more than " + RecordBase.MaxContentLength + " bytes to a record's contents"); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override long Length { get { return length; } } public override long Position { get { return position; } set { Seek(value, SeekOrigin.Begin); } } public override bool Equals (object obj) { if (obj == null) return false; var b = obj as RecordContentsStream; if (b == null) return false; // Check lengths first if (this.Length != b.Length) return false; // Compare byte by byte.. kind of expensive //TODO: Do we really need such a strict equality criterium? byte[] bufForB = new byte[128]; byte[] bufForA = new byte[128]; this.Position = 0; b.Position = 0; while (b.Read(bufForB, 0, bufForB.Length) > 0) { this.Read(bufForA, 0, bufForA.Length); if (!ByteUtils.AreEqual(bufForA, bufForB)) return false; } return true; } public override int GetHashCode() { // We are very lax here.. no need to read from secondary storage or go over every single byte // just to hash this stream return length + 31 * MemoryBlocks.Take(1).Sum(mb => mb.GetHashCode()); } /// <summary> /// Creates a stream that stores one record's contents in memory. /// </summary> public RecordContentsStream() { MemoryBlocks = new LinkedList<byte[]>(); secondaryStorageStream = null; length = 0; position = 0; } /// <summary> /// Creates a single record's stream that stores its contents in the supplied stream, <paramref name="secondaryStorageStream"/>. /// The supplied stream will be written to from its current position, and this newly created <see cref="RecordContentsStream"/> will /// mark this initial position internally to be able to find its contents. The life cycle of the supplied stream is not /// related to this class, i.e. the supplied stream will not be disposed of when this object is disposed. /// Typical usage of this constructor is when you want to store a request's contents in secondary storage. In fact, it is assumed /// that when using this constructor you are storing this stream's contents in secondary storage /// </summary> /// <param name="secondaryStorageStream"> /// A stream that will hold this and possibly other records' contents in secondary storage. /// </param> public RecordContentsStream(Stream secondaryStorageStream) { if (secondaryStorageStream == null) throw new ArgumentNullException("secondaryStorageStream"); if (!secondaryStorageStream.CanSeek) throw new ArgumentException("The supplied secondary storage stream must be seekable"); this.secondaryStorageStream = secondaryStorageStream; secondaryStoragePosition = secondaryStorageStream.Position; length = 0; position = 0; } } }
/* Copyright 2006-2017 Cryptany, 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.Text; using System.Data; using System.Data.SqlClient; using Cryptany.Core.DPO.MetaObjects; using Cryptany.Core.DPO.Sql; namespace Cryptany.Core.DPO { public enum StorageAccessMediatorType { DataSet, MsSql } public abstract class StorageAccessMediator { protected StorageAccessMediatorType _mediatorType; protected bool _locked = false; public bool Locked { get { return _locked; } } public abstract void Reset(); public abstract void BeginCollectData(); public abstract void AddCommand(StorageCommand command); public abstract void EndCollectData(); public abstract StorageCommandResult EndCollectAndFlushData(); public abstract void CancelCollectData(); public abstract StorageCommandResult FlushData(); } public class DataSetStorageAccessMediator : StorageAccessMediator { private DataSet _dataset = null; protected StorageCommandResult _commandResult; public DataSetStorageAccessMediator(DataSet dataSet) { _dataset = dataSet; _mediatorType = StorageAccessMediatorType.DataSet; } public StorageCommandResult LastCommandResult { get { return _commandResult; } } public override void BeginCollectData() { throw new Exception("The method or operation is not implemented."); } public override void AddCommand(StorageCommand command) { throw new Exception("The method or operation is not implemented."); } public override void EndCollectData() { throw new Exception("The method or operation is not implemented."); } public override StorageCommandResult EndCollectAndFlushData() { throw new Exception("The method or operation is not implemented."); } public override void CancelCollectData() { throw new Exception("The method or operation is not implemented."); } public override StorageCommandResult FlushData() { throw new Exception("The method or operation is not implemented."); } public override void Reset() { throw new Exception("The method or operation is not implemented."); } } public class MsSqlStorageAccessMediator : StorageAccessMediator { private SqlConnection _connection = null; private List<StorageCommand> _list = new List<StorageCommand>(); private Dictionary<PropertyDescription, List<EntityBase>> _mtmRelationships = new Dictionary<PropertyDescription, List<EntityBase>>(); private string _script; private PersistentStorage _ps; private Dictionary<Type, SqlScriptBuilder> _builders = new Dictionary<Type, SqlScriptBuilder>(); public MsSqlStorageAccessMediator(PersistentStorage ps, SqlConnection connection) { _connection = connection; _mediatorType = StorageAccessMediatorType.MsSql; _ps = ps; } public PersistentStorage Ps { get { return _ps; } } public override void BeginCollectData() { if ( _locked ) throw new Exception("Cannot begin collect data while in collecting state"); _list.Clear(); _mtmRelationships.Clear(); _script = ""; _locked = false; } public override void AddCommand(StorageCommand command) { if (_locked) throw new Exception("The mediator is locked"); if ( command.Mode == StorageCommandMode.Entity ) { if ( !_builders.ContainsKey(command.EntityType) ) _builders.Add(command.EntityType, new SqlScriptBuilder(new Mapper(command.EntityType, _ps), _ps)); _list.Add(command); } else { if ( !_mtmRelationships.ContainsKey(command.ManyToManyProperty) ) { List<EntityBase> l = new List<EntityBase>(); l.AddRange(command.Entities); _mtmRelationships.Add(command.ManyToManyProperty, l); } else foreach ( EntityBase e in command.Entities ) if ( !_mtmRelationships[command.ManyToManyProperty].Contains(e) ) _mtmRelationships[command.ManyToManyProperty].Add(e); } } public override void EndCollectData() { _locked = true; foreach ( StorageCommand command in _list ) { string script; switch (command.CommandType) { case StorageCommandType.Insert: script = _builders[command.EntityType].CreateInsertStatement(command.Entities); break; case StorageCommandType.Update: script = _builders[command.EntityType].CreateUpdateStatement(command.Entities); break; default: script = _builders[command.EntityType].CreateDeleteStatement(command.Entities); break; } _script += script + "\r\n\r\n"; } string clearMtm = ""; string addMtm = ""; foreach (PropertyDescription pd in _mtmRelationships.Keys) { clearMtm += SqlScriptBuilder.CreateMtmDelete(pd, _ps, _mtmRelationships[pd]) + "\r\n"; addMtm += SqlScriptBuilder.CreateMtmInsert(pd, _ps, _mtmRelationships[pd]) + "\r\n"; } _script = clearMtm + "\r\n\r\n" + _script + "\r\n\r\n" + addMtm; string guid = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); _script = "DECLARE @status int\r\nDECLARE @msg VARCHAR(255)\r\n" + "BEGIN TRAN savetran" + guid + "\r\n\r\n" + "BEGIN TRY\r\n\r\n" + _script + "SELECT @status = 1\r\nCOMMIT TRAN savetran" + guid + "\r\n" + "END TRY\r\n" + "BEGIN CATCH\r\nROLLBACK TRAN savetran" + guid + "\r\n" + "SELECT @status = 0\r\n" + "SET @Msg =ERROR_MESSAGE()\r\nRAISERROR(@Msg,16,1)\r\nEND CATCH\r\nSELECT 'SUCCESS'"; } public override StorageCommandResult EndCollectAndFlushData() { EndCollectData(); return FlushData(); } public override void CancelCollectData() { _locked = false; _script = ""; _mtmRelationships.Clear(); _list.Clear(); } public override StorageCommandResult FlushData() { using ( SqlConnection c = new SqlConnection(_connection.ConnectionString) ) { c.Open(); using (SqlCommand command = new SqlCommand(_script, c)) { command.CommandTimeout = 300; object result = command.ExecuteScalar(); return new StorageCommandResult(StorageCommandResultState.Success, "Command succeded.", result); } } return new StorageCommandResult(StorageCommandResultState.Failed, "Command failed.", 0); } public override void Reset() { _locked = false; BeginCollectData(); } } public enum StorageCommandType { Insert, Update, Delete, Select } public enum StorageCommandResultState { Success, Failed } public class StorageCommandResult { private StorageCommandResultState _state; private string _message; private object _result; internal StorageCommandResult(StorageCommandResultState state, string message, object result) { _state = state; _message = message; _result = result; } public object Result { get { return _result; } } public string Message { get { return _message; } } public StorageCommandResultState State { get { return _state; } } } public enum StorageCommandMode { Entity, MtmRelation } public class StorageCommand { //public static StorageCommand Create(object argument) protected StorageCommandType _commandType; protected List<EntityBase> _entities = new List<EntityBase>(); protected PropertyDescription _propertyDescription; protected StorageCommandMode _mode; private readonly Type _entityType; protected SqlScriptBuilder _builder; internal StorageCommand(EntityBase argument) { if ( argument == null ) throw new Exception("The entity should be null"); _entities.Add(argument); _entityType = argument.GetType(); _mode = StorageCommandMode.Entity; SetCommandType(); } internal StorageCommand(EntityBase entity, PropertyDescription pd) { if ( entity == null ) throw new Exception("The entity should be null"); _propertyDescription = pd; if ( !_propertyDescription.IsManyToManyRelation ) throw new Exception("A many-to-many relation expected"); _entities.Add(entity); _entityType = entity.GetType(); _mode = StorageCommandMode.MtmRelation; SetCommandType(); } internal StorageCommand(List<EntityBase> argument) { if ( argument == null || argument.Count == 0 ) throw new Exception("The entity list should not be empty"); _entityType = argument[0].GetType(); foreach ( EntityBase e in argument ) if ( e.GetType() != _entityType ) throw new Exception("All element of the entity list must of the same type"); _entities = argument; _mode = StorageCommandMode.Entity; SetCommandType(); } internal StorageCommand(List<EntityBase> entities, PropertyDescription pd) { if ( entities == null || entities.Count == 0 ) throw new Exception("The entity list should not be empty"); if ( !_propertyDescription.IsManyToManyRelation ) throw new Exception("A many-to-many relation expected"); _entityType = entities[0].GetType(); foreach ( EntityBase e in entities ) if ( e.GetType() != _entityType ) throw new Exception("All element of the entity list must of the same type"); _propertyDescription = pd; _entities = entities; SetCommandType(); _mode = StorageCommandMode.MtmRelation; } public Type EntityType { get { return _entityType; } } private void SetCommandType() { switch ( _entities[0].State ) { case EntityState.New: _commandType = StorageCommandType.Insert; break; case EntityState.Deleted: _commandType = StorageCommandType.Delete; break; case EntityState.Changed: _commandType = StorageCommandType.Update; break; default: throw new Exception("Invalid entity state"); } } public List<EntityBase> Entities { get { return _entities; } } public StorageCommandType CommandType { get { return _commandType; } } public PropertyDescription ManyToManyProperty { get { return _propertyDescription; } } public StorageCommandMode Mode { get { return _mode; } } public string GenerateScript() { if ( Mode == StorageCommandMode.Entity ) return null; return null; } } }
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Xml.Linq; namespace Xunit.ConsoleClient { public class Program { volatile static bool cancel; static bool failed; static readonly ConcurrentDictionary<string, ExecutionSummary> completionMessages = new ConcurrentDictionary<string, ExecutionSummary>(); [STAThread] public static int Main(string[] args) { try { Console.ForegroundColor = ConsoleColor.White; #if !NETCORE var netVersion = Environment.Version; #else var netVersion = "Core"; #endif Console.WriteLine("xUnit.net console test runner ({0}-bit .NET {1})", IntPtr.Size * 8, netVersion); Console.WriteLine("Copyright (C) 2014 Outercurve Foundation."); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; if (args.Length == 0 || args[0] == "-?") { PrintUsage(); return 1; } #if !NETCORE AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; #endif Console.CancelKeyPress += (sender, e) => { if (!cancel) { Console.WriteLine("Canceling... (Press Ctrl+C again to terminate)"); cancel = true; e.Cancel = true; } }; var defaultDirectory = Directory.GetCurrentDirectory(); if (!defaultDirectory.EndsWith(new String(new[] { Path.DirectorySeparatorChar }))) defaultDirectory += Path.DirectorySeparatorChar; var commandLine = CommandLine.Parse(args); var failCount = RunProject(defaultDirectory, commandLine.Project, commandLine.TeamCity, commandLine.AppVeyor, commandLine.ShowProgress, commandLine.ParallelizeAssemblies, commandLine.ParallelizeTestCollections, commandLine.MaxParallelThreads); if (commandLine.Wait) { Console.WriteLine(); Console.Write("Press enter key to continue..."); Console.ReadLine(); Console.WriteLine(); } return failCount; } catch (ArgumentException ex) { Console.WriteLine("error: {0}", ex.Message); return 1; } catch (BadImageFormatException ex) { Console.WriteLine("{0}", ex.Message); return 1; } finally { Console.ResetColor(); } } #if !NETCORE static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = e.ExceptionObject as Exception; if (ex != null) Console.WriteLine(ex.ToString()); else Console.WriteLine("Error of unknown type thrown in application domain"); Environment.Exit(1); } #endif static void PrintUsage() { #if !NETCORE var executableName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetLocalCodeBase()); #else var executableName = "xunit.console.netcore"; #endif Console.WriteLine("usage: {0} <assemblyFile> [configFile] [assemblyFile [configFile]...] [options]", executableName); Console.WriteLine(); Console.WriteLine("Note: Configuration files must end in .config"); Console.WriteLine(); Console.WriteLine("Valid options:"); Console.WriteLine(" -parallel option : set parallelization based on option"); Console.WriteLine(" : none - turn off all parallelization"); Console.WriteLine(" : collections - only parallelize collections"); Console.WriteLine(" : assemblies - only parallelize assemblies"); Console.WriteLine(" : all - parallelize assemblies & collections"); Console.WriteLine(" -maxthreads count : maximum thread count for collection parallelization"); Console.WriteLine(" : 0 - run with unbounded thread count"); Console.WriteLine(" : >0 - limit task thread pool size to 'count'"); Console.WriteLine(" -noshadow : do not shadow copy assemblies"); #if !NETCORE Console.WriteLine(" -teamcity : forces TeamCity mode (normally auto-detected)"); Console.WriteLine(" -appveyor : forces AppVeyor CI mode (normally auto-detected)"); #endif Console.WriteLine(" -showprogress : display the names of tests as they start and finish"); Console.WriteLine(" -wait : wait for input after completion"); Console.WriteLine(" -trait \"name=value\" : only run tests with matching name/value traits"); Console.WriteLine(" : if specified more than once, acts as an OR operation"); Console.WriteLine(" -notrait \"name=value\" : do not run tests with matching name/value traits"); Console.WriteLine(" : if specified more than once, acts as an AND operation"); Console.WriteLine(" -method \"name\" : run a given test method (should be fully specified;"); Console.WriteLine(" : i.e., 'MyNamespace.MyClass.MyTestMethod')"); Console.WriteLine(" : if specified more than once, acts as an OR operation"); Console.WriteLine(" -class \"name\" : run all methods in a given test class (should be fully"); Console.WriteLine(" : specified; i.e., 'MyNamespace.MyClass')"); Console.WriteLine(" : if specified more than once, acts as an OR operation"); TransformFactory.AvailableTransforms.ForEach( transform => Console.WriteLine(" {0} : {1}", String.Format("-{0} <filename>", transform.CommandLine).PadRight(22).Substring(0, 22), transform.Description) ); } static int RunProject(string defaultDirectory, XunitProject project, bool teamcity, bool appVeyor, bool showProgress, bool? parallelizeAssemblies, bool? parallelizeTestCollections, int? maxThreadCount) { XElement assembliesElement = null; var xmlTransformers = TransformFactory.GetXmlTransformers(project); var needsXml = xmlTransformers.Count > 0; var consoleLock = new object(); if (!parallelizeAssemblies.HasValue) parallelizeAssemblies = project.All(assembly => assembly.Configuration.ParallelizeAssembly ?? false); if (needsXml) assembliesElement = new XElement("assemblies"); var originalWorkingFolder = Directory.GetCurrentDirectory(); using (AssemblyHelper.SubscribeResolve()) { var clockTime = Stopwatch.StartNew(); if (parallelizeAssemblies.GetValueOrDefault()) { var tasks = project.Assemblies.Select(assembly => Task.Run(() => ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, showProgress, parallelizeTestCollections, maxThreadCount, project.Filters))); var results = Task.WhenAll(tasks).GetAwaiter().GetResult(); foreach (var assemblyElement in results.Where(result => result != null)) assembliesElement.Add(assemblyElement); } else { foreach (var assembly in project.Assemblies) { var assemblyElement = ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, showProgress, parallelizeTestCollections, maxThreadCount, project.Filters); if (assemblyElement != null) assembliesElement.Add(assemblyElement); } } clockTime.Stop(); if (completionMessages.Count > 0) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(); Console.WriteLine("=== TEST EXECUTION SUMMARY ==="); Console.ForegroundColor = ConsoleColor.Gray; var totalTestsRun = completionMessages.Values.Sum(summary => summary.Total); var totalTestsFailed = completionMessages.Values.Sum(summary => summary.Failed); var totalTestsSkipped = completionMessages.Values.Sum(summary => summary.Skipped); var totalTime = completionMessages.Values.Sum(summary => summary.Time).ToString("0.000s"); var totalErrors = completionMessages.Values.Sum(summary => summary.Errors); var longestAssemblyName = completionMessages.Keys.Max(key => key.Length); var longestTotal = totalTestsRun.ToString().Length; var longestFailed = totalTestsFailed.ToString().Length; var longestSkipped = totalTestsSkipped.ToString().Length; var longestTime = totalTime.Length; var longestErrors = totalErrors.ToString().Length; foreach (var message in completionMessages.OrderBy(m => m.Key)) Console.WriteLine(" {0} Total: {1}, Errors: {2}, Failed: {3}, Skipped: {4}, Time: {5}", message.Key.PadRight(longestAssemblyName), message.Value.Total.ToString().PadLeft(longestTotal), message.Value.Errors.ToString().PadLeft(longestErrors), message.Value.Failed.ToString().PadLeft(longestFailed), message.Value.Skipped.ToString().PadLeft(longestSkipped), message.Value.Time.ToString("0.000s").PadLeft(longestTime)); if (completionMessages.Count > 1) Console.WriteLine(" {0} {1} {2} {3} {4} {5}" + Environment.NewLine + " {6} {7} {8} {9} {10} {11} ({12})", " ".PadRight(longestAssemblyName), "-".PadRight(longestTotal, '-'), "-".PadRight(longestErrors, '-'), "-".PadRight(longestFailed, '-'), "-".PadRight(longestSkipped, '-'), "-".PadRight(longestTime, '-'), "GRAND TOTAL:".PadLeft(longestAssemblyName), totalTestsRun, totalErrors, totalTestsFailed, totalTestsSkipped, totalTime, clockTime.Elapsed.TotalSeconds.ToString("0.000s")); } } Directory.SetCurrentDirectory(originalWorkingFolder); xmlTransformers.ForEach(transformer => transformer(assembliesElement)); return failed ? 1 : completionMessages.Values.Sum(summary => summary.Failed); } static XmlTestExecutionVisitor CreateVisitor(object consoleLock, string defaultDirectory, XElement assemblyElement, bool teamCity, bool appVeyor, bool showProgress) { #if !NETCORE if (teamCity) return new TeamCityVisitor(assemblyElement, () => cancel); else if (appVeyor) return new AppVeyorVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages); #endif return new StandardOutputVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages, showProgress); } static XElement ExecuteAssembly(object consoleLock, string defaultDirectory, XunitProjectAssembly assembly, bool needsXml, bool teamCity, bool appVeyor, bool showProgress, bool? parallelizeTestCollections, int? maxThreadCount, XunitFilters filters) { if (cancel) return null; var assemblyElement = needsXml ? new XElement("assembly") : null; try { if (!ValidateFileExists(consoleLock, assembly.AssemblyFilename) || !ValidateFileExists(consoleLock, assembly.ConfigFilename)) return null; // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner assembly.Configuration.PreEnumerateTheories = false; var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration); var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration); if (maxThreadCount.HasValue) executionOptions.SetMaxParallelThreads(maxThreadCount.GetValueOrDefault()); if (parallelizeTestCollections.HasValue) executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault()); lock (consoleLock) { if (assembly.Configuration.DiagnosticMessages ?? false) Console.WriteLine("Discovering: {0} (method display = {1}, parallel test collections = {2}, max threads = {3})", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename), discoveryOptions.GetMethodDisplay(), !executionOptions.GetDisableParallelization(), executionOptions.GetMaxParallelThreads()); else Console.WriteLine("Discovering: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); } using (var controller = new XunitFrontController(AppDomainSupport.Denied, assembly.AssemblyFilename, assembly.ConfigFilename, assembly.Configuration.ShadowCopyOrDefault)) using (var discoveryVisitor = new TestDiscoveryVisitor()) { controller.Find(includeSourceInformation: false, messageSink: discoveryVisitor, discoveryOptions: discoveryOptions); discoveryVisitor.Finished.WaitOne(); lock (consoleLock) Console.WriteLine("Discovered: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); var resultsVisitor = CreateVisitor(consoleLock, defaultDirectory, assemblyElement, teamCity, appVeyor, showProgress); var filteredTestCases = discoveryVisitor.TestCases.Where(filters.Filter).ToList(); if (filteredTestCases.Count == 0) { lock (consoleLock) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Info: {0} has no tests to run", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); Console.ForegroundColor = ConsoleColor.Gray; } } else { controller.RunTests(filteredTestCases, resultsVisitor, executionOptions); resultsVisitor.Finished.WaitOne(); } } } catch (Exception ex) { Console.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message); failed = true; } return assemblyElement; } static bool ValidateFileExists(object consoleLock, string fileName) { if (String.IsNullOrWhiteSpace(fileName) || File.Exists(fileName)) return true; lock (consoleLock) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("File not found: {0}", fileName); Console.ForegroundColor = ConsoleColor.Gray; } return false; } } }
using System; using System.Runtime.InteropServices; using Vanara.Extensions; namespace Vanara.PInvoke { public static partial class AdvApi32 { /// <summary> /// <para> /// The <c>LSA_OBJECT_ATTRIBUTES</c> structure is used with the LsaOpenPolicy function to specify the attributes of the connection to /// the Policy object. /// </para> /// <para> /// When you call LsaOpenPolicy, initialize the members of this structure to <c>NULL</c> or zero because the function does not use /// the information. /// </para> /// </summary> /// <remarks> /// <para>The <c>LSA_OBJECT_ATTRIBUTES</c> structure is defined in the LsaLookup.h header file.</para> /// <para> /// <c>Windows Server 2008 with SP2 and earlier, Windows Vista with SP2 and earlier, Windows Server 2003, Windows XP/2000:</c> The /// <c>LSA_OBJECT_ATTRIBUTES</c> structure is defined in the NTSecAPI.h header file. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/lsalookup/ns-lsalookup-_lsa_object_attributes typedef struct // _LSA_OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PLSA_UNICODE_STRING ObjectName; ULONG Attributes; PVOID // SecurityDescriptor; PVOID SecurityQualityOfService; } LSA_OBJECT_ATTRIBUTES, *PLSA_OBJECT_ATTRIBUTES; [PInvokeData("lsalookup.h", MSDNShortId = "ad05cb52-8e58-46a9-b3e8-0c9c2a24a997")] [StructLayout(LayoutKind.Sequential)] public struct LSA_OBJECT_ATTRIBUTES { /// <summary>Specifies the size, in bytes, of the LSA_OBJECT_ATTRIBUTES structure.</summary> public int Length; /// <summary>Should be <c>NULL</c>.</summary> public IntPtr RootDirectory; /// <summary>Should be <c>NULL</c>.</summary> public IntPtr ObjectName; /// <summary>Should be zero.</summary> public int Attributes; /// <summary>Should be <c>NULL</c>.</summary> public IntPtr SecurityDescriptor; /// <summary>Should be <c>NULL</c>.</summary> public IntPtr SecurityQualityOfService; /// <summary>Returns a completely empty reference. This value should be used when calling <see cref="LsaOpenPolicy(string, in LSA_OBJECT_ATTRIBUTES, LsaPolicyRights, out SafeLSA_HANDLE)"/>.</summary> /// <value>An <see cref="LSA_OBJECT_ATTRIBUTES"/> instance with all members set to <c>NULL</c> or zero.</value> public static LSA_OBJECT_ATTRIBUTES Empty { get; } = new LSA_OBJECT_ATTRIBUTES(); } /// <summary> /// The LSA_STRING structure is used by various Local Security Authority (LSA) functions to specify a string. Also an example of /// unnecessary over-engineering and re-engineering. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Size = 8)] [PInvokeData("LsaLookup.h", MSDNShortId = "aa378522")] public struct LSA_STRING { /// <summary> /// Specifies the length, in bytes, of the string pointed to by the Buffer member, not including the terminating null character, /// if any. /// </summary> public ushort length; /// <summary> /// Specifies the total size, in bytes, of the memory allocated for Buffer. Up to MaximumLength bytes can be written into the /// buffer without trampling memory. /// </summary> public ushort MaximumLength; /// <summary>Pointer to a string. Note that the strings returned by the various LSA functions might not be null-terminated.</summary> public string Buffer; /// <summary>Initializes a new instance of the <see cref="LSA_STRING"/> struct from a string.</summary> /// <param name="s">The string value.</param> /// <exception cref="ArgumentException">String exceeds 32Kb of data.</exception> public LSA_STRING(string s) { if (s == null) { length = MaximumLength = 0; Buffer = null; } else { var l = s.Length; if (l >= ushort.MaxValue) throw new ArgumentException("String too long"); Buffer = s; length = (ushort)l; MaximumLength = (ushort)(l + 1); } } /// <summary>Gets the number of characters in the string.</summary> public int Length => length; /// <summary>Returns a <see cref="string"/> that represents this instance.</summary> /// <returns>A <see cref="string"/> that represents this instance.</returns> public override string ToString() => Buffer.Substring(0, Length); /// <summary>Performs an implicit conversion from <see cref="LSA_STRING"/> to <see cref="string"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator string(LSA_STRING value) => value.ToString(); } /// <summary> /// <para> /// The <c>LSA_TRANSLATED_NAME</c> structure is used with the LsaLookupSids function to return information about the account /// identified by a SID. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/lsalookup/ns-lsalookup-_lsa_translated_name typedef struct // _LSA_TRANSLATED_NAME { SID_NAME_USE Use; LSA_UNICODE_STRING Name; LONG DomainIndex; } LSA_TRANSLATED_NAME, *PLSA_TRANSLATED_NAME; [PInvokeData("lsalookup.h", MSDNShortId = "edea8317-5cdf-4d1e-9e6d-fcf17b91adb7")] [StructLayout(LayoutKind.Sequential)] public struct LSA_TRANSLATED_NAME { /// <summary>An SID_NAME_USE enumeration value that identifies the type of SID.</summary> public SID_NAME_USE Use; /// <summary> /// An LSA_UNICODE_STRING structure that contains the isolated name of the translated SID. An isolated name is a user, group, or /// local group account name without the domain name (for example, user_name, rather than Acctg\user_name). /// </summary> public LSA_UNICODE_STRING Name; /// <summary> /// The index of an entry in a related LSA_REFERENCED_DOMAIN_LIST data structure which describes the domain that owns the /// account. If there is no corresponding reference domain for an entry, then DomainIndex will contain a negative value. /// </summary> public int DomainIndex; } /// <summary> /// <para> /// The <c>LSA_TRANSLATED_SID2</c> structure contains SIDs that are retrieved based on account names. This structure is used by the /// LsaLookupNames2 function. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/lsalookup/ns-lsalookup-_lsa_translated_sid2 typedef struct // _LSA_TRANSLATED_SID2 { SID_NAME_USE Use; PSID Sid; LONG DomainIndex; ULONG Flags; } LSA_TRANSLATED_SID2, *PLSA_TRANSLATED_SID2; [PInvokeData("lsalookup.h", MSDNShortId = "792de958-8e24-46d8-b484-159435bc96e3")] [StructLayout(LayoutKind.Sequential)] public struct LSA_TRANSLATED_SID2 { /// <summary> /// An SID_NAME_USE enumeration value that identifies the use of the SID. If this value is SidTypeUnknown or SidTypeInvalid, the /// rest of the information in the structure is not valid and should be ignored. /// </summary> public SID_NAME_USE Use; /// <summary>The complete SID of the account.</summary> public PSID Sid; /// <summary> /// The index of an entry in a related LSA_REFERENCED_DOMAIN_LIST data structure which describes the domain that owns the /// account. If there is no corresponding reference domain for an entry, then DomainIndex will contain a negative value. /// </summary> public int DomainIndex; /// <summary>Not used.</summary> public uint Flags; } /// <summary>A custom marshaler for functions using LSA_STRING so that managed strings can be used.</summary> /// <seealso cref="ICustomMarshaler"/> internal class LsaStringMarshaler : ICustomMarshaler { public static ICustomMarshaler GetInstance(string cookie) => new LsaStringMarshaler(); public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) return; Marshal.FreeCoTaskMem(pNativeData); pNativeData = IntPtr.Zero; } public int GetNativeDataSize() => Marshal.SizeOf(typeof(LSA_STRING)); public IntPtr MarshalManagedToNative(object ManagedObj) { var s = ManagedObj as string; if (s == null) return IntPtr.Zero; var str = new LSA_STRING(s); return str.MarshalToPtr(Marshal.AllocCoTaskMem, out var _); } public object MarshalNativeToManaged(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) return null; var ret = pNativeData.ToStructure<LSA_STRING>(); var s = (string)ret.ToString().Clone(); //LsaFreeMemory(pNativeData); return s; } } } }
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using NuGetConsole.Implementation.Console; using NuGetConsole.Implementation.PowerConsole; namespace NuGetConsole.Implementation { /// <summary> /// This class implements the tool window. /// </summary> [Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")] public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget { /// <summary> /// Get VS IComponentModel service. /// </summary> private IComponentModel ComponentModel { get { return this.GetService<IComponentModel>(typeof(SComponentModel)); } } private IProductUpdateService ProductUpdateService { get { return ComponentModel.GetService<IProductUpdateService>(); } } private IPackageRestoreManager PackageRestoreManager { get { return ComponentModel.GetService<IPackageRestoreManager>(); } } private PowerConsoleWindow PowerConsoleWindow { get { return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow; } } private IVsUIShell VsUIShell { get { return this.GetService<IVsUIShell>(typeof(SVsUIShell)); } } private bool IsToolbarEnabled { get { return _wpfConsole != null && _wpfConsole.Dispatcher.IsStartCompleted && _wpfConsole.Host != null && _wpfConsole.Host.IsCommandEnabled; } } /// <summary> /// Standard constructor for the tool window. /// </summary> public PowerConsoleToolWindow() : base(null) { this.Caption = Resources.ToolWindowTitle; this.BitmapResourceID = 301; this.BitmapIndex = 0; this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar); } protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { // Get list command for the Feed combo CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList); mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID)); // invoke command for the Feed combo CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources); mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID)); // get default project command CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList); mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID)); // invoke command for the Default project combo CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects); mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID)); // clear console command CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost); mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID)); // terminate command execution command CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost); mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID)); } } public override void OnToolWindowCreated() { // Register key bindings to use in the editor var windowFrame = (IVsWindowFrame)Frame; Guid cmdUi = VSConstants.GUID_TextEditorFactory; windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi); // pause for a tiny moment to let the tool window open before initializing the host var timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(0); timer.Tick += (o, e) => { timer.Stop(); LoadConsoleEditor(); }; timer.Start(); base.OnToolWindowCreated(); } protected override void OnClose() { base.OnClose(); WpfConsole.Dispose(); } /// <summary> /// This override allows us to forward these messages to the editor instance as well /// </summary> /// <param name="m"></param> /// <returns></returns> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane; if (vsWindowPane != null) { MSG[] pMsg = new MSG[1]; pMsg[0].hwnd = m.HWnd; pMsg[0].message = (uint)m.Msg; pMsg[0].wParam = m.WParam; pMsg[0].lParam = m.LParam; return vsWindowPane.TranslateAccelerator(pMsg) == 0; } return base.PreProcessMessage(ref m); } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // examine buttons within our toolbar if (pguidCmdGroup == GuidList.guidNuGetCmdSet) { bool isEnabled = IsToolbarEnabled; if (isEnabled) { bool isStopButton = (prgCmds[0].cmdID == 0x0600); // 0x0600 is the Command ID of the Stop button, defined in .vsct // when command is executing: enable stop button and disable the rest // when command is not executing: disable the stop button and enable the rest isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand; } if (isEnabled) { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); } else { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } return VSConstants.S_OK; } int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } return hr; } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } return hr; } private void SourcesList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Sources_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) // Selected a feed { int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length) { PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index]; } } else if (args.OutValue != IntPtr.Zero) // Query selected feed name { string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } private void ProjectsList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } // get project list here Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Projects_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) { // Selected a default projects int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length) { PowerConsoleWindow.SetDefaultProjectIndex(index); } } else if (args.OutValue != IntPtr.Zero) { string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } /// <summary> /// ClearHost command handler. /// </summary> private void ClearHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Dispatcher.ClearConsole(); } } private void StopHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Host.Abort(); } } private HostInfo ActiveHostInfo { get { return PowerConsoleWindow.ActiveHostInfo; } } private void LoadConsoleEditor() { if (WpfConsole != null) { // allow the console to start writing output WpfConsole.StartWritingOutput(); FrameworkElement consolePane = WpfConsole.Content as FrameworkElement; ConsoleParentPane.AddConsoleEditor(consolePane); // WPF doesn't handle input focus automatically in this scenario. We // have to set the focus manually, otherwise the editor is displayed but // not focused and not receiving keyboard inputs until clicked. if (consolePane != null) { PendingMoveFocus(consolePane); } } } /// <summary> /// Set pending focus to a console pane. At the time of setting active host, /// the pane (UIElement) is usually not loaded yet and can't receive focus. /// In this case, we need to set focus in its Loaded event. /// </summary> /// <param name="consolePane"></param> private void PendingMoveFocus(FrameworkElement consolePane) { if (consolePane.IsLoaded && consolePane.IsConnectedToPresentationSource()) { PendingFocusPane = null; MoveFocus(consolePane); } else { PendingFocusPane = consolePane; } } private FrameworkElement _pendingFocusPane; private FrameworkElement PendingFocusPane { get { return _pendingFocusPane; } set { if (_pendingFocusPane != null) { _pendingFocusPane.Loaded -= PendingFocusPane_Loaded; } _pendingFocusPane = value; if (_pendingFocusPane != null) { _pendingFocusPane.Loaded += PendingFocusPane_Loaded; } } } private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e) { MoveFocus(PendingFocusPane); PendingFocusPane = null; } private void MoveFocus(FrameworkElement consolePane) { // TAB focus into editor (consolePane.Focus() does not work due to editor layouts) consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); // Try start the console session now. This needs to be after the console // pane getting focus to avoid incorrect initial editor layout. StartConsoleSession(consolePane); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] private void StartConsoleSession(FrameworkElement consolePane) { if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null) { try { if (WpfConsole.Dispatcher.IsStartCompleted) { OnDispatcherStartCompleted(); // if the dispatcher was started before we reach here, // it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false). // enable key input now. WpfConsole.Dispatcher.AcceptKeyInput(); } else { WpfConsole.Dispatcher.StartCompleted += (sender, args) => OnDispatcherStartCompleted(); WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey; WpfConsole.Dispatcher.Start(); } } catch (Exception x) { // hide the text "initialize host" when an error occurs. ConsoleParentPane.NotifyInitializationCompleted(); WpfConsole.WriteLine(x.GetBaseException().ToString()); ExceptionHelper.WriteToActivityLog(x); } } else { ConsoleParentPane.NotifyInitializationCompleted(); } } private void OnDispatcherStartWaitingKey(object sender, EventArgs args) { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; // we want to hide the text "initialize host..." when waiting for key input ConsoleParentPane.NotifyInitializationCompleted(); } private void OnDispatcherStartCompleted() { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; ConsoleParentPane.NotifyInitializationCompleted(); // force the UI to update the toolbar VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */); } private IWpfConsole _wpfConsole; /// <summary> /// Get the WpfConsole of the active host. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private IWpfConsole WpfConsole { get { if (_wpfConsole == null) { Debug.Assert(ActiveHostInfo != null); try { _wpfConsole = ActiveHostInfo.WpfConsole; } catch (Exception x) { _wpfConsole = ActiveHostInfo.WpfConsole; _wpfConsole.Write(x.ToString()); } } return _wpfConsole; } } private IVsTextView _vsTextView; /// <summary> /// Get the VsTextView of current WpfConsole if exists. /// </summary> private IVsTextView VsTextView { get { if (_vsTextView == null && _wpfConsole != null) { _vsTextView = (IVsTextView)(WpfConsole.VsTextView); } return _vsTextView; } } private ConsoleContainer _consoleParentPane; /// <summary> /// Get the parent pane of console panes. This serves as the Content of this tool window. /// </summary> private ConsoleContainer ConsoleParentPane { get { if (_consoleParentPane == null) { _consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager); } return _consoleParentPane; } } public override object Content { get { return this.ConsoleParentPane; } set { base.Content = value; } } } }