context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 CarrylessMultiplyInt640() { var test = new PclmulqdqOpTest__CarrylessMultiplyInt640(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Pclmulqdq.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 (Pclmulqdq.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Pclmulqdq.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class PclmulqdqOpTest__CarrylessMultiplyInt640 { private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(PclmulqdqOpTest__CarrylessMultiplyInt640 testClass) { var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[2] {-2, -20}; private static Int64[] _data2 = new Int64[2] {25, 65535}; private static Int64[] _expectedRet = new Int64[2] {-18, 8}; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static PclmulqdqOpTest__CarrylessMultiplyInt640() { Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public PclmulqdqOpTest__CarrylessMultiplyInt640() { Succeeded = true; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Pclmulqdq.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Pclmulqdq.CarrylessMultiply( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Pclmulqdq.CarrylessMultiply( Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Pclmulqdq.CarrylessMultiply( Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)), 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Pclmulqdq).GetMethod(nameof(Pclmulqdq.CarrylessMultiply), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Pclmulqdq.CarrylessMultiply( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Pclmulqdq.CarrylessMultiply(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Pclmulqdq.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Pclmulqdq.CarrylessMultiply(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Pclmulqdq.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Pclmulqdq.CarrylessMultiply(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new PclmulqdqOpTest__CarrylessMultiplyInt640(); var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Pclmulqdq.CarrylessMultiply(_fld1, _fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Pclmulqdq.CarrylessMultiply(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(outArray, method); } private void ValidateResult(Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < result.Length; i++) { if (result[i] != _expectedRet[i] ) { succeeded = false; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Pclmulqdq)}.{nameof(Pclmulqdq.CarrylessMultiply)}<Int64>(Vector128<Int64>, 0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2022, SIL International. All Rights Reserved. // <copyright from='2011' to='2022' company='SIL International'> // Copyright (c) 2022, SIL International. All Rights Reserved. // // Distributable under the terms of the MIT License (https://sil.mit-license.org/) // </copyright> #endregion // -------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using L10NSharp; using SIL.CommandLineProcessing; using SIL.IO; using SIL.Extensions; using SIL.Progress; using SIL.Reporting; using HearThis.Script; using NAudio.Wave; using static System.Int32; using static System.IO.Path; using static System.String; namespace HearThis.Publishing { /// <summary> /// Each script block is recorded and each clip stored as its own file. This class manages that collection of files. /// </summary> public static class ClipRepository { private const string kSkipFileExtension = "skip"; #region Retrieval and Deletion methods /// <summary> /// Gets the path to the indicated line. If a script provider is provided that implements IActorCharacterProvider /// and there is a current character, lineNumber is relative to the lines for that character. /// </summary> /// <param name="projectName">Paratext short name, text Release Bundle project name /// (language code + underscore + internal name), or multi-voice recording project /// name 9with GUID)</param> /// <param name="bookName">English Scripture book name (spelled out)</param> /// <param name="chapterNumber">1-based (0 represents the introduction)</param> /// <param name="lineNumber">0-based (does not necessarily/typically correspond to verse /// numbers). When called for a project that uses a filtered set of blocks, this should /// be the filtered/apparent block number. In this case, the scriptProvider MUST be /// supplied in order for this to be translated into a real (persisted) block number. /// </param> /// <param name="scriptProvider">Used to translate a filtered/apparent block number /// into a real (persisted) block number. Optional if project does not use a script that /// involves this kind of filtering.</param> /// <returns>The actual file name of the .wav file, with fully-qualified path.</returns> public static string GetPathToLineRecording(string projectName, string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider = null) { return GetClipFileInfo(projectName, bookName, chapterNumber, lineNumber, scriptProvider, out _); } /// <summary> /// Gets the path to the indicated line. If a script provider is provided that implements IActorCharacterProvider /// and there is a current character, lineNumber is relative to the lines for that character. /// </summary> /// <param name="projectName">Paratext short name, text Release Bundle project name /// (language code + underscore + internal name), or multi-voice recording project /// name 9with GUID)</param> /// <param name="bookName">English Scripture book name (spelled out)</param> /// <param name="chapterNumber">1-based (0 represents the introduction)</param> /// <param name="lineNumber">0-based (does not necessarily/typically correspond to verse /// numbers). When called for a project that uses a filtered set of blocks, this should /// be the filtered/apparent block number. In this case, the scriptProvider MUST be /// supplied in order for this to be translated into a real (persisted) block number. /// </param> /// <param name="scriptProvider">Used to translate a filtered/apparent block number /// into a real (persisted) block number. Optional if project does not use a script that /// involves this kind of filtering.</param> /// <returns>An object representing the clip file</returns> public static IClipFile GetClipFile(string projectName, string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider = null) { var filePath = GetClipFileInfo(projectName, bookName, chapterNumber, lineNumber, scriptProvider, out var fileNumber); return new BlockClipOrSkipFile(filePath, fileNumber); } private static string GetClipFileInfo(string projectName, string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider, out int fileNumber) { var chapter = GetChapterFolder(projectName, bookName, chapterNumber); fileNumber = GetRealLineNumber(bookName, chapterNumber, lineNumber, scriptProvider); return Combine(chapter, fileNumber + ".wav"); } public static string GetPathToLineRecordingUnfiltered(string projectName, string bookName, int chapterNumber, int lineNumber) { // Not passing a script provider means that line number won't get adjusted. return GetPathToLineRecording(projectName, bookName, chapterNumber, lineNumber); } // When HearThis is filtering by character, generally it pretends the only blocks a chapter has are the ones that // character is supposed to record. However, the recording file has to use the real block number (actually one less // than the number recorded in the block) so that recordings from different files don't overwrite each other. // This routine converts from a possibly-filtered block number address to a real one. private static int GetRealLineNumber(string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider) { var adjustedLineNumber = lineNumber; if (scriptProvider != null) { var bookNumber = scriptProvider.VersificationInfo.GetBookNumber(bookName); // We do sometimes find ourselves in an unrecorded chapter asking for the path to block 0. // That will crash GetBlock, so check. if (scriptProvider.GetScriptBlockCount(bookNumber, chapterNumber) > lineNumber) { var block = scriptProvider.GetBlock(bookNumber, chapterNumber, lineNumber); adjustedLineNumber = block.Number - 1; } } return adjustedLineNumber; } /// <summary> /// See whether we have the specified clip. If a scriptProvider is passed which implements IActorCharacterProvider /// and it has a current character, lineNumber is relative to the lines for that character. /// </summary> public static bool GetHaveClip(string projectName, string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider = null) { var path = GetPathToLineRecording(projectName, bookName, chapterNumber, lineNumber, scriptProvider); return File.Exists(path); } public static bool GetHaveClipUnfiltered(string projectName, string bookName, int chapterNumber, int lineNumber) { // Not passing a script provider ensures that the line number won't get adjusted. return GetHaveClip(projectName, bookName, chapterNumber, lineNumber); } public static string GetChapterFolder(string projectName, string bookName, int chapterNumber) { var book = GetBookFolder(projectName, bookName); var chapter = Utils.CreateDirectory(book, chapterNumber.ToString()); return chapter; } private static string GetBookFolder(string projectName, string bookName) { var project = GetProjectFolder(projectName); var book = Utils.CreateDirectory(project, bookName.Trim()); return book; } public static string GetProjectFolder(string projectName) { return Program.GetApplicationDataFolder(projectName); } public static int GetCountOfRecordingsInFolder(string path, IScriptProvider scriptProvider) { if (!Directory.Exists(path)) return 0; var provider = scriptProvider as IActorCharacterProvider; var soundFilesInFolder = GetSoundFilesInFolder(path); if (provider == null) return soundFilesInFolder.Length; if (!TryParse(GetFileName(path), out var chapter)) return 0; // Probably a copy of a folder made for "backup" purposes - don't count it. (Note: Current production code can't hit this, but since this is a public method, we'll play it safe.) var bookName = GetFileName(GetDirectoryName(path)); int book = scriptProvider.VersificationInfo.GetBookNumber(bookName); return soundFilesInFolder.Count(f => { if (!TryParse(GetFileNameWithoutExtension(f), out var lineNo0Based)) return false; // don't count files whose names don't parse as numbers return provider.IsBlockInCharacter(book, chapter, lineNo0Based); }); } /// <summary> /// Checks to see whether the given file is not a valid WAV file. If it isn't, /// it deletes it. /// </summary> public static bool IsInvalidClipFile(string filename, IProgress progress = null) { if (!File.Exists(filename)) throw new FileNotFoundException("Cannot check validity of nonexistent file", filename); try { using (var _ = new WaveFileReader(filename)) return false; } catch (Exception e) { var msg = Format(LocalizationManager.GetString("ClipRepository.InvalidClip", "Invalid WAV file {0}\r\n{1}\r\n{2} will attempt to delete it.", "Param 0: WAV file name; " + "Param 1: Error message; " + "Param 2: \"HearThis\" (product name)"), filename, e.Message, Program.kProduct); Logger.WriteEvent(msg); progress?.WriteError(msg); } try { RobustFile.Delete(filename); } catch (Exception e) { var msg = Format(LocalizationManager.GetString("ClipRepository.DeleteInvalidClipProblem", "Failed to delete invalid WAV file: {0}", "Param is WAV file name."), filename); Console.WriteLine(msg); if (progress == null) { ErrorReport.ReportNonFatalExceptionWithMessage(e, msg); } else { progress.WriteException(e); progress.WriteError(msg); throw; } } return true; } private static IEnumerable<string> GetNumericDirectories(string path) { if (Directory.Exists(path)) return Directory.GetDirectories(path).Where(dir => TryParse(GetFileName(dir), out int _)); throw new DirectoryNotFoundException($"GetNumericDirectories called with invalid path: {path}"); } public static int GetCountOfRecordingsForBook(string projectName, string name, IScriptProvider scriptProvider) { var path = GetBookFolder(projectName, name); if (!Directory.Exists(path)) return 0; return GetNumericDirectories(path).Sum(directory => GetCountOfRecordingsInFolder(directory, scriptProvider)); } public static bool HasRecordingsForProject(string projectName) { return Directory.GetDirectories(Program.GetApplicationDataFolder(projectName)) .Any(bookDirectory => GetNumericDirectories(bookDirectory).Any(chDirectory => GetSoundFilesInFolder(chDirectory).Length > 0)); } // line number is not character-filtered. public static bool DeleteLineRecording(string projectName, string bookName, int chapterNumber, int lineNumber, IScriptProvider scriptProvider = null) { // just being careful... if (GetHaveClipUnfiltered(projectName, bookName, chapterNumber, lineNumber)) { var path = GetPathToLineRecordingUnfiltered(projectName, bookName, chapterNumber, lineNumber); try { RobustFile.Delete(path); return true; } catch (IOException err) { ErrorReport.NotifyUserOfProblem(err, Format(LocalizationManager.GetString("ClipRepository.DeleteClipProblem", "HearThis was unable to delete this clip. File may be locked. Restarting HearThis might solve this problem. File: {0}"), path)); } } return false; } /// <summary> /// Class representing a (WAV) file that stores either a recorded audio clip or a "skip" /// file corresponding to a block in the script. Note: a "skip" file indicates the user /// decided not to record the corresponding block. /// </summary> private class BlockClipOrSkipFile : IClipFile { public string FilePath { get; private set; } public int Number { get; private set; } private FileInfo _fileInfo; /// <summary> /// Constructor /// </summary> /// <param name="filePath">The actual file name of the .wav or .skip file, with /// fully-qualified path.</param> /// <param name="fileNumber">The numeric value corresponding to the file name. /// This is a 0-based block number. (Note: the Block/Line numbers displayed to /// the user and stored in the the chapter info files are 1-based.)</param> public BlockClipOrSkipFile(string filePath, int fileNumber) { FilePath = filePath; Number = fileNumber; } public void Delete() { RobustFile.Delete(FilePath); FilePath = null; Number = MinValue; _fileInfo = null; } /// <summary> /// Shift file the specified number of block positions. Caller is responsible for /// ensuring that the destination position is free of a conflicting clip or skip /// file. /// </summary> /// <param name="positions">The number of positions forward (positive) or backward /// (negative) to move the file</param> public void ShiftPosition(int positions) { var destPath = GetIntendedDestinationPath(positions); // This intentionally does NOT overwrite. It will fail if caller attempts to // move a clip or skip file to a destination file that exists. RobustFile.Move(FilePath, destPath); FilePath = destPath; Number += positions; _fileInfo = null; } public string GetIntendedDestinationPath(int positions) => Combine(Directory, ChangeExtension((Number + positions).ToString(), Extension)); private FileInfo FileInfo => _fileInfo ?? (_fileInfo = new FileInfo(FilePath)); public DateTime LastWriteTimeUtc => FileInfo.LastWriteTimeUtc; private string Directory { get { var directory = GetDirectoryName(FilePath); if (directory == null) throw new ArgumentException($"ClipOrSkipFile created using a filename that is not valid: {FilePath}"); return GetDirectoryName(FilePath); } } private string Extension => GetExtension(FilePath); } private class BlockClipOrSkipFileComparer : IComparer<BlockClipOrSkipFile> { private readonly int _direction; public BlockClipOrSkipFileComparer(bool ascending) { _direction = ascending ? 1 : -1; } public int Compare(BlockClipOrSkipFile x, BlockClipOrSkipFile y) { if (ReferenceEquals(x, y)) return 0; if (ReferenceEquals(null, y)) return 1 * _direction; if (ReferenceEquals(null, x)) return -1 * _direction; return x.Number.CompareTo(y.Number) * _direction; } } private static IEnumerable<BlockClipOrSkipFile> AllClipAndSkipFiles(IEnumerable<string> allFiles) { foreach (var file in allFiles) { var extension = GetExtension(file); if ((extension == ".wav" || extension == ".skip") && TryParse(GetFileNameWithoutExtension(file), out var lineNumberForFile)) yield return new BlockClipOrSkipFile(file, lineNumberForFile); } } /// <summary> /// lineNumber is unfiltered /// </summary> public static void DeleteAllClipsAfterLine(string projectName, string bookName, int chapterNumber, int lineNumber) { var chapterFolder = GetChapterFolder(projectName, bookName, chapterNumber); foreach (var file in AllClipAndSkipFiles(Directory.GetFiles(chapterFolder))) { if (file.Number > lineNumber) file.Delete(); } } public static void BackUpRecordingForSkippedLine(string projectName, string bookName, int chapterNumber1Based, int block, IScriptProvider scriptProvider = null) { var recordingPath = GetPathToLineRecording(projectName, bookName, chapterNumber1Based, block, scriptProvider); if (File.Exists(recordingPath)) RobustFile.Move(recordingPath, ChangeExtension(recordingPath, kSkipFileExtension), true); } public static bool RestoreBackedUpClip(string projectName, string bookName, int chapterNumber1Based, int block, IScriptProvider scriptProvider = null) { var recordingPath = GetPathToLineRecording(projectName, bookName, chapterNumber1Based, block, scriptProvider); var skipPath = ChangeExtension(recordingPath, kSkipFileExtension); if (File.Exists(skipPath)) { RobustFile.Move(skipPath, recordingPath); return true; } return false; } /// <summary> /// Shifts the requested clip files and adjusts the Number of their corresponding /// ChapterInfo records (if they exist) /// </summary> /// <param name="projectName">The name of the HearThis project</param> /// <param name="bookName">The English (short) name of the Scripture book</param> /// <param name="chapterNumber1Based">The chapter (0 => intro)</param> /// <param name="iBlock">The 0-based index of the first clip to shift (corresponds /// to the actual number/name of the file)</param> /// <param name="blockCount">The number of clips to shift. (Assuming caller wants to /// shift a contiguous run of clips, caller is responsible for ensuring that there are /// no gaps in the existing sequence of clips. (Gaps are not counted as clips.) If /// this number is greater than the number of existing clips starting from /// <see cref="iBlock"/>, all the remaining clips will be shifted. This might include /// clips that are "extras" (beyond the clips accounted for by the source text).</param> /// <param name="offset">The number of positions to shift clips forward (positive) or /// backward (negative). A value of 0 is not an error but it results in no change.</param> /// <param name="getRecordingInfo">A function to get the recording information for the /// chapter specified by <see cref="chapterNumber1Based"/>.</param> /// <returns>A result indicating the actual number of clips that were attempted to be /// shifted, the number successfully shifted and any error that occurred. Note that the /// number attempted will typically be <see cref="blockCount"/> but can be less if the /// caller requested to shift more clips than were present.</returns> public static ClipShiftingResult ShiftClips(string projectName, string bookName, int chapterNumber1Based, int iBlock, int blockCount, int offset, Func<ChapterRecordingInfoBase> getRecordingInfo) { if (offset == 0) // meaningless return new ClipShiftingResult(0); return ShiftClips(projectName, bookName, chapterNumber1Based, iBlock, offset, getRecordingInfo, blockCount); } // HT-376: Unfortunately, HT v. 2.0.3 introduced a change whereby the numbering of // existing clips could be out of sync with the data, so any chapter with one of the // new default SkippedParagraphStyles that has not had anything recorded since the // migration to that version needs to have clips shifted forward to account for the // new blocks (even though they are most likely skipped). (Any chapter where the user // has recorded something since the migration to that version could also be affected, // but the user will have to migrate it manually -- unless ALL the clips in that // chapter were recorded after the migration -- because we can't know which clips // might need to be moved.) If a "default" cutoff date is specified, then we can // safely migrate any affected chapters. If this returns false, it indicates that this // chapter might require manual cleanup. public static bool ShiftClipsAtOrAfterBlockIfAllClipsAreBeforeDate(string projectName, string bookName, int chapterNumber1Based, int iBlock, DateTime cutoff, Func<ChapterRecordingInfoBase> getRecordingInfo) { var result = ShiftClips(projectName, bookName, chapterNumber1Based, iBlock, 1, getRecordingInfo, cutoff:cutoff); if (result.Error != null) throw result.Error; return result.Attempted == result.SuccessfulMoves; } private static ClipShiftingResult ShiftClips(string projectName, string bookName, int chapterNumber, int iStartBlock, int offset, Func<ChapterRecordingInfoBase> getRecordingInfo, int blockCount = MaxValue, DateTime cutoff = default) { Debug.Assert(offset != 0); ClipShiftingResult result = null; try { var chapterFolder = GetChapterFolder(projectName, bookName, chapterNumber); var allFilesAfterBlock = AllClipAndSkipFiles(Directory.GetFiles(chapterFolder)) .Where(f => f.Number >= iStartBlock).ToArray(); if (allFilesAfterBlock.Length == 0) return new ClipShiftingResult(0); if (cutoff != default && allFilesAfterBlock.Any(f => f.LastWriteTimeUtc >= cutoff)) return new ClipShiftingResult(allFilesAfterBlock.All(f => f.LastWriteTimeUtc >= cutoff) ? 0 : allFilesAfterBlock.Length); BlockClipOrSkipFile[] filesToShift; if (blockCount >= allFilesAfterBlock.Length) { // We have to move them in the correct order to avoid clobbering the next one. allFilesAfterBlock.Sort(new BlockClipOrSkipFileComparer(offset < 0)); filesToShift = allFilesAfterBlock; } else { // We first have to sort them in ascending order to get the correct ones allFilesAfterBlock.Sort(new BlockClipOrSkipFileComparer(true)); var theFilesWeWant = allFilesAfterBlock.Take(blockCount); // Now get them in the correct order to avoid clobbering the next one. filesToShift = offset > 0 ? theFilesWeWant.Reverse().ToArray() : theFilesWeWant.ToArray(); } result = new ClipShiftingResult(filesToShift.Length); foreach (var file in filesToShift) { result.LastAttemptedMove = file; file.ShiftPosition(offset); result.SuccessfulMoves++; } result.LastAttemptedMove = null; getRecordingInfo().AdjustLineNumbers(iStartBlock, offset, blockCount); } catch (Exception e) { if (result == null) result = new ClipShiftingResult(-1); result.Error = e; } return result; } public class ClipShiftingResult { public int Attempted { get; } public int SuccessfulMoves { get; internal set; } public IClipFile LastAttemptedMove { get; internal set; } public Exception Error; internal ClipShiftingResult(int plannedMoves) { Attempted = plannedMoves; } } #endregion #region Publishing methods public static void PublishAllBooks(PublishingModel publishingModel, string projectName, string publishRoot, IProgress progress) { if (!RobustIO.DeleteDirectoryAndContents(publishRoot)) { progress.WriteError(Format(LocalizationManager.GetString("ClipRepository.DeleteFolder", "Existing folder could not be deleted: {0}"), publishRoot)); return; } var bookNames = new List<string>(Directory.GetDirectories(Program.GetApplicationDataFolder(projectName)).Select(GetFileName)); bookNames.Sort(publishingModel.PublishingInfoProvider.BookNameComparer); foreach (string bookName in bookNames) { if (progress.CancelRequested) return; PublishAllChapters(publishingModel, projectName, bookName, publishRoot, progress); if (progress.ErrorEncountered) return; } } public static void PublishAllChapters(PublishingModel publishingModel, string projectName, string bookName, string publishRoot, IProgress progress) { if (!publishingModel.IncludeBook(bookName)) // Maybe book has been deleted in Paratext. return; var bookFolder = GetBookFolder(projectName, bookName); var chapters = new List<int>(GetNumericDirectories(bookFolder).Select(dir => Parse(GetFileName(dir)))); chapters.Sort(); foreach (var chapterNumber in chapters) { if (progress.CancelRequested) return; PublishSingleChapter(publishingModel, projectName, bookName, chapterNumber, publishRoot, progress); if (progress.ErrorEncountered) return; } } private static string[] GetSoundFilesInFolder(string path) => Directory.GetFiles(path, "*.wav"); public static bool GetDoAnyClipsExistForProject(string projectName) { return Directory.GetFiles(Program.GetApplicationDataFolder(projectName), "*.wav", SearchOption.AllDirectories).Any(); } private static void PublishSingleChapter(PublishingModel publishingModel, string projectName, string bookName, int chapterNumber, string rootPath, IProgress progress) { try { var clipFiles = GetSoundFilesInFolder(GetChapterFolder(projectName, bookName, chapterNumber)); if (clipFiles.Length == 0) return; // If a clip file is invalid, it will cause the export to abort. Although rare, it // is annoying and confusing to users. Better to just delete the bogus file and let // the user know. RemoveInvalidWavFiles(progress, ref clipFiles); clipFiles = clipFiles.OrderBy(name => { int result; if (TryParse(GetFileNameWithoutExtension(name), out result)) return result; throw new Exception(Format(LocalizationManager.GetString("ClipRepository.UnexpectedWavFile", "Unexpected WAV file: {0}"), name)); }).ToArray(); publishingModel.FilesInput += clipFiles.Length; publishingModel.FilesOutput++; progress.WriteMessage("{0} {1}", bookName, chapterNumber.ToString()); string pathToJoinedWavFile = GetTempPath().CombineForPath("joined.wav"); using (TempFile.TrackExisting(pathToJoinedWavFile)) { MergeAudioFiles(clipFiles, pathToJoinedWavFile, progress); PublishVerseIndexFiles(rootPath, bookName, chapterNumber, clipFiles, publishingModel, progress); var lastClipFile = clipFiles.LastOrDefault(); if (lastClipFile != null) { int lineNumber = Parse(GetFileNameWithoutExtension(lastClipFile)); try { publishingModel.PublishingInfoProvider.GetUnfilteredBlock(bookName, chapterNumber, lineNumber); } catch (ArgumentOutOfRangeException) { progress.WriteWarning(Format(LocalizationManager.GetString("ClipRepository.ExtraneousClips", "Unexpected recordings (i.e., clips) were encountered in the folder for {0} {1}."), bookName, chapterNumber)); } } publishingModel.PublishingMethod.PublishChapter(rootPath, bookName, chapterNumber, pathToJoinedWavFile, progress); } } catch (Exception error) { progress.WriteError(error.Message); } } private static void RemoveInvalidWavFiles(IProgress progress, ref string[] clipFiles) { // Although it is rare, we occasionally encounter a clip file that is corrupt // (usually empty). We don't know what causes this. It could be something in // HearThis, but I'm guessing that it is some kind of hardware glitch or system // software failure. This causes the export to fail, and sadly the // only recourse is to re-record it (or restore it from a backup if a valid // backup exists). var removedAny = false; for (var i = 0; i < clipFiles.Length; i++) { if (IsInvalidClipFile(clipFiles[i], progress)) { clipFiles[i] = null; removedAny = true; } } if (removedAny) clipFiles = clipFiles.Where(f => f != null).ToArray(); } internal static void MergeAudioFiles(IReadOnlyCollection<string> files, string pathToJoinedWavFile, IProgress progress) { var outputDirectoryName = GetDirectoryName(pathToJoinedWavFile); if (files.Count == 1) { RobustFile.Copy(files.First(), pathToJoinedWavFile, true); } else { var fileList = GetTempFileName(); File.WriteAllLines(fileList, files.ToArray()); progress.WriteMessage(" " + LocalizationManager.GetString("ClipRepository.MergeAudioProgress", "Joining recorded clips", "Appears in progress indicator")); string arguments = Format("join -d \"{0}\" -F \"{1}\" -O always -r none", outputDirectoryName, fileList); RunCommandLine(progress, FileLocationUtilities.GetFileDistributedWithApplication(false, "shntool.exe"), arguments); // Passing just the directory name for output file means the output file is ALWAYS joined.wav. // It's possible to pass more of a file name, but that just makes things more complex, because // shntool will always prepend 'joined' to the name we really want. // Some callers actually want the name to be 'joined.wav'. If not, we just rename it afterwards. var outputFilePath = pathToJoinedWavFile; if (GetFileName(pathToJoinedWavFile) != "joined.wav") { outputFilePath = Combine(outputDirectoryName, "joined.wav"); } if (!File.Exists(outputFilePath)) { throw new ApplicationException( "Um... shntool.exe failed to produce the file of the joined clips. Reroute the power to the secondary transfer conduit."); } if (GetFileName(pathToJoinedWavFile) != "joined.wav") { RobustFile.Delete(pathToJoinedWavFile); RobustFile.Move(outputFilePath, pathToJoinedWavFile); } } } public static void RunCommandLine(IProgress progress, string exePath, string arguments) { progress.WriteVerbose(exePath + " " + arguments); ExecutionResult result = CommandLineRunner.Run(exePath, arguments, null, 60*10, progress); result.RaiseExceptionIfFailed(""); } /// <summary> /// Publish Audacity Label Files or cue sheet to text files /// </summary> public static void PublishVerseIndexFiles(string rootPath, string bookName, int chapterNumber, string[] verseFiles, PublishingModel publishingModel, IProgress progress) { // get the output path var outputPath = ChangeExtension( publishingModel.PublishingMethod.GetFilePathWithoutExtension(rootPath, bookName, chapterNumber), "txt"); try { // clear the text file if it already exists RobustFile.Delete(outputPath); } catch (Exception error) { progress.WriteError(error.Message); } if (publishingModel.VerseIndexFormat != PublishingModel.VerseIndexFormatType.None) { string contents = GetVerseIndexFileContents(bookName, chapterNumber, verseFiles, publishingModel.VerseIndexFormat, publishingModel.PublishingInfoProvider, outputPath); if (contents == null) return; try { using (StreamWriter writer = new StreamWriter(outputPath, false)) writer.Write(contents); } catch (Exception error) { progress.WriteError(error.Message); } } } internal static string GetVerseIndexFileContents(string bookName, int chapterNumber, string[] verseFiles, PublishingModel.VerseIndexFormatType verseIndexFormat, IPublishingInfoProvider publishingInfoProvider, string outputPath) { switch (verseIndexFormat) { case PublishingModel.VerseIndexFormatType.AudacityLabelFileVerseLevel: return chapterNumber == 0 ? null : GetAudacityLabelFileContents(verseFiles, publishingInfoProvider, bookName, chapterNumber, false); case PublishingModel.VerseIndexFormatType.AudacityLabelFilePhraseLevel: return GetAudacityLabelFileContents(verseFiles, publishingInfoProvider, bookName, chapterNumber, true); case PublishingModel.VerseIndexFormatType.CueSheet: return GetCueSheetContents(verseFiles, publishingInfoProvider, bookName, chapterNumber, outputPath); default: throw new InvalidEnumArgumentException("verseIndexFormat", (int)verseIndexFormat, typeof(PublishingModel.VerseIndexFormatType)); } } internal static string GetCueSheetContents(string[] verseFiles, IPublishingInfoProvider infoProvider, string bookName, int chapterNumber, string outputPath) { var bldr = new StringBuilder(); bldr.AppendFormat("FILE \"{0}\"", outputPath); bldr.AppendLine(); TimeSpan indextime = new TimeSpan(0, 0, 0, 0); for (int i = 0; i < verseFiles.Length; i++) { bldr.AppendLine(Format(" TRACK {0:000} AUDIO", (i + 1))); // " TRACK 0" + (i + 1) + " AUDIO"); //else // " TRACK " + (i + 1) + " AUDIO"; bldr.AppendLine(" TITLE 00000-" + bookName + chapterNumber + "-tnnC001 "); bldr.AppendLine(" INDEX 01 " + indextime); // get the length of the block using (var b = new NAudio.Wave.WaveFileReader(verseFiles[i])) { TimeSpan wavlength = b.TotalTime; //update the indextime for the verse indextime = indextime.Add(wavlength); } } return bldr.ToString(); } internal static string GetAudacityLabelFileContents(string[] verseFiles, IPublishingInfoProvider infoProvider, string bookName, int chapterNumber, bool phraseLevel) { var audacityLabelFileBuilder = new AudacityLabelFileBuilder(verseFiles, infoProvider, bookName, chapterNumber, phraseLevel); return audacityLabelFileBuilder.ToString(); } #region AudacityLabelFileBuilder class private class AudacityLabelFileBuilder { private readonly string[] verseFiles; private readonly IPublishingInfoProvider infoProvider; private readonly string bookName; private readonly int chapterNumber; private readonly bool phraseLevel; private readonly StringBuilder bldr = new StringBuilder(); private readonly Dictionary<string, int> headingCounters = new Dictionary<string, int>(); private ScriptLine block; private double startTime, endTime; private string prevVerse = null; private double accumClipTimeFromPrevBlocks = 0.0; private string currentVerse = null; private string nextVerse; private int subPhrase = -1; public AudacityLabelFileBuilder(string[] verseFiles, IPublishingInfoProvider infoProvider, string bookName, int chapterNumber, bool phraseLevel) { this.verseFiles = verseFiles; this.infoProvider = infoProvider; this.bookName = bookName; this.chapterNumber = chapterNumber; this.phraseLevel = phraseLevel; } public override string ToString() { for (int i = 0; i < verseFiles.Length; i++) { // get the length of the block double clipLength; using (var b = new NAudio.Wave.WaveFileReader(verseFiles[i])) { clipLength = b.TotalTime.TotalSeconds; //update the endTime for the verse endTime = endTime + clipLength; } // REVIEW: Use TryParse to avoid failure for extraneous filename? int lineNumber = Parse(GetFileNameWithoutExtension(verseFiles[i])); block = GetUnfilteredBlock(lineNumber); if (block == null) break; nextVerse = null; string label; if (block.Heading) { subPhrase = -1; label = GetHeadingBlockLabel(); } else { if (chapterNumber == 0) { // Intro material subPhrase++; label = Empty; } else { ScriptLine nextBlock = null; if (i < verseFiles.Length - 1) { // Check next block int nextLineNumber = Parse(GetFileNameWithoutExtension(verseFiles[i + 1])); nextBlock = GetUnfilteredBlock(nextLineNumber); if (nextBlock != null) { nextVerse = nextBlock.CrossesVerseBreak ? nextBlock.Verse.Substring(0, nextBlock.Verse.IndexOf('~')) : nextBlock.Verse; } } if (block.CrossesVerseBreak) { MakeLabelsForApproximateVerseLocationsInBlock(clipLength); continue; } // Current block is a normal verse or explicit verse bridge currentVerse = block.Verse; if (nextBlock != null) { Debug.Assert(currentVerse != null); if (phraseLevel) { // If this is the same as the next verse but different from the previous one, start // a new sub-verse sequence. if (!nextBlock.Heading && prevVerse != currentVerse && (currentVerse == nextBlock.Verse || (nextBlock.CrossesVerseBreak && currentVerse == nextBlock.Verse.Substring(0, nextBlock.Verse.IndexOf('~'))))) { subPhrase = 0; } } else if (!nextBlock.Heading && currentVerse == nextVerse) { // Same verse number. // For verse-level highlighting, postpone appending until we have the whole verse. prevVerse = currentVerse; accumClipTimeFromPrevBlocks += endTime - startTime; continue; } } label = currentVerse; UpdateSubPhrase(); } } AppendLabel(startTime, endTime, label); // update start time for the next verse startTime = endTime; prevVerse = currentVerse; } return bldr.ToString(); } private ScriptLine GetUnfilteredBlock(int lineNumber) { try { return infoProvider.GetUnfilteredBlock(bookName, chapterNumber, lineNumber); } catch (Exception) { return null; } } private void MakeLabelsForApproximateVerseLocationsInBlock(double clipLength) { // Unless/until SAB can handle implicit verse bridges, we want to create a label // at approximately the right place (based on verse number offsets in text) for // each verse in the block. int ichVerse = 0; var verseOffsets = block.VerseOffsets.ToList(); var textLen = block.Text.Length; verseOffsets.Add(textLen); int prevOffset = 0; double start = 0.0; foreach (var verseOffset in verseOffsets) { int ichVerseLim = block.Verse.IndexOf('~', ichVerse); if (ichVerseLim == -1) { currentVerse = block.Verse.Substring(ichVerse); } else { Debug.Assert(ichVerseLim <= block.Verse.Length - 2); currentVerse = block.Verse.Substring(ichVerse, ichVerseLim - ichVerse); ichVerse = ichVerseLim + 1; } double end = FindEndOfVerse(clipLength, start, prevOffset, verseOffset, block.Text); if (phraseLevel || currentVerse != prevVerse || currentVerse != nextVerse) { if (!phraseLevel && currentVerse == nextVerse) { accumClipTimeFromPrevBlocks += end - start; prevVerse = currentVerse; continue; } UpdateSubPhrase(); end += accumClipTimeFromPrevBlocks; AppendLabel(startTime + start, startTime + end, currentVerse); } prevVerse = currentVerse; start = end; prevOffset = verseOffset; } startTime = endTime - accumClipTimeFromPrevBlocks; } private string GetHeadingBlockLabel() { var headingType = block.HeadingType.TrimEnd('1', '2', '3', '4'); if (headingType == "c" || headingType == "mt") return headingType; int headingCounter; if (!headingCounters.TryGetValue(headingType, out headingCounter)) headingCounter = 1; else headingCounter++; headingCounters[headingType] = headingCounter; return headingType + headingCounter; } private double FindEndOfVerse(double clipLength, double start, int prevOffset, int verseOffset, string text) { double percentage = (verseOffset - prevOffset) / (double) text.Length; return start + clipLength * percentage; } private void UpdateSubPhrase() { if (subPhrase >= 0 && prevVerse == currentVerse) subPhrase++; // if (!block.Heading && currentVerse == prevVerseEnd) // return 1; else if (subPhrase > 0 && prevVerse != currentVerse) subPhrase = -1; if (subPhrase == -1 && currentVerse == nextVerse) subPhrase = 0; } private void AppendLabel(double start, double end, string label) { string timeRange = Format("{0:0.######}\t{1:0.######}\t", start, end); bldr.AppendLine(timeRange + label + (subPhrase >= 0 ? ((char)('a' + subPhrase)).ToString() : Empty)); accumClipTimeFromPrevBlocks = 0.0; } } #endregion //AudacityLabelFileBuilder class #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Rest.Generator.Azure.Python.Properties; using Microsoft.Rest.Generator.Azure.Python.Templates; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python; using Microsoft.Rest.Generator.Python.Templates; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Microsoft.Rest.Generator.Azure.Python { public class AzurePythonCodeGenerator : PythonCodeGenerator { private const string ClientRuntimePackage = "msrestazure version 0.4.0"; // page extensions class dictionary. private IList<PageTemplateModel> pageModels; public AzurePythonCodeGenerator(Settings settings) : base(settings) { pageModels = new List<PageTemplateModel>(); Namer = new AzurePythonCodeNamer(); } public override string Name { get { return "Azure.Python"; } } public override string Description { // TODO resource string. get { return "Azure specific Python code generator."; } } public override string UsageInstructions { get { return string.Format(CultureInfo.InvariantCulture, Resources.UsageInformation, ClientRuntimePackage); } } /// <summary> /// Normalizes client model by updating names and types to be language specific. /// </summary> /// <param name="serviceClient"></param> public override void NormalizeClientModel(ServiceClient serviceClient) { // Don't add pagable/longrunning method since we already handle ourself. Settings.AddCredentials = true; AzureExtensions.ProcessClientRequestIdExtension(serviceClient); AzureExtensions.UpdateHeadMethods(serviceClient); AzureExtensions.ParseODataExtension(serviceClient); Extensions.FlattenModels(serviceClient); ParameterGroupExtensionHelper.AddParameterGroups(serviceClient); AzureExtensions.AddAzureProperties(serviceClient); AzureExtensions.SetDefaultResponses(serviceClient); CorrectFilterParameters(serviceClient); base.NormalizeClientModel(serviceClient); NormalizeApiVersion(serviceClient); NormalizePaginatedMethods(serviceClient); } private static void NormalizeApiVersion(ServiceClient serviceClient) { serviceClient.Properties.Where( p => p.SerializedName.Equals(AzureExtensions.ApiVersion, StringComparison.OrdinalIgnoreCase)) .ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'")); serviceClient.Properties.Where( p => p.SerializedName.Equals(AzureExtensions.AcceptLanguage, StringComparison.OrdinalIgnoreCase)) .ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'")); } private string GetPagingSetting(Dictionary<string, object> extensions, string valueTypeName) { var ext = extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer; string nextLinkName = (string)ext["nextLinkName"] ?? "nextLink"; string itemName = (string)ext["itemName"] ?? "value"; string className = (string)ext["className"]; if (string.IsNullOrEmpty(className)) { className = valueTypeName + "Paged"; ext["className"] = className; } var pageModel = new PageTemplateModel(className, nextLinkName, itemName, valueTypeName); if (!pageModels.Contains(pageModel)) { pageModels.Add(pageModel); } return className; } /// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> private void NormalizePaginatedMethods(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var convertedTypes = new Dictionary<IType, Response>(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key)) { var compositType = (CompositeType)method.Responses[responseStatus].Body; var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if (sequenceType != null) { string pagableTypeName = GetPagingSetting(method.Extensions, sequenceType.ElementType.Name); CompositeType pagedResult = new CompositeType { Name = pagableTypeName }; convertedTypes[compositType] = new Response(pagedResult, null); method.Responses[responseStatus] = convertedTypes[compositType]; break; } } if (convertedTypes.ContainsKey(method.ReturnType.Body)) { method.ReturnType = convertedTypes[method.ReturnType.Body]; } } Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name))); } /// <summary> /// Corrects type of the filter parameter. Currently typization of filters isn't /// supported and therefore we provide to user an opportunity to pass it in form /// of raw string. /// </summary> /// <param name="serviceClient">The service client.</param> public static void CorrectFilterParameters(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.ODataExtension))) { var filterParameter = method.Parameters.FirstOrDefault(p => p.SerializedName.Equals("$filter", StringComparison.OrdinalIgnoreCase) && p.Location == ParameterLocation.Query && p.Type is CompositeType); if (filterParameter != null) { filterParameter.Type = new PrimaryType(KnownPrimaryType.String); } } } /// <summary> /// Generate Python client code for given ServiceClient. /// </summary> /// <param name="serviceClient"></param> /// <returns></returns> public override async Task Generate(ServiceClient serviceClient) { var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient); if (!string.IsNullOrWhiteSpace(Version)) { serviceClientTemplateModel.Version = Version; } // Service client var setupTemplate = new SetupTemplate { Model = serviceClientTemplateModel }; await Write(setupTemplate, "setup.py"); var serviceClientInitTemplate = new ServiceClientInitTemplate { Model = serviceClientTemplateModel }; await Write(serviceClientInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "__init__.py")); var serviceClientTemplate = new AzureServiceClientTemplate { Model = serviceClientTemplateModel, }; await Write(serviceClientTemplate, Path.Combine(serviceClientTemplateModel.PackageName, serviceClientTemplateModel.Name.ToPythonCase() + ".py")); var versionTemplate = new VersionTemplate { Model = serviceClientTemplateModel, }; await Write(versionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "version.py")); var exceptionTemplate = new ExceptionTemplate { Model = serviceClientTemplateModel, }; await Write(exceptionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "exceptions.py")); var credentialTemplate = new CredentialTemplate { Model = serviceClientTemplateModel, }; await Write(credentialTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "credentials.py")); //Models if (serviceClientTemplateModel.ModelTemplateModels.Any()) { var modelInitTemplate = new AzureModelInitTemplate { Model = new AzureModelInitTemplateModel(serviceClient, pageModels.Select(t => t.TypeDefinitionName)) }; await Write(modelInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", "__init__.py")); foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels) { var modelTemplate = new ModelTemplate { Model = modelType }; await Write(modelTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", modelType.Name.ToPythonCase() + ".py")); } } //MethodGroups if (serviceClientTemplateModel.MethodGroupModels.Any()) { var methodGroupIndexTemplate = new MethodGroupInitTemplate { Model = serviceClientTemplateModel }; await Write(methodGroupIndexTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", "__init__.py")); foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels) { var methodGroupTemplate = new AzureMethodGroupTemplate { Model = methodGroupModel as AzureMethodGroupTemplateModel }; await Write(methodGroupTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", methodGroupModel.MethodGroupType.ToPythonCase() + ".py")); } } // Enums if (serviceClient.EnumTypes.Any()) { var enumTemplate = new EnumTemplate { Model = new EnumTemplateModel(serviceClient.EnumTypes), }; await Write(enumTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", serviceClientTemplateModel.Name.ToPythonCase() + "_enums.py")); } // Page class foreach (var pageModel in pageModels) { var pageTemplate = new PageTemplate { Model = pageModel }; await Write(pageTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", pageModel.TypeDefinitionName.ToPythonCase() + ".py")); } } } }
using System.ComponentModel; using DevExpress.XtraBars; using DevExpress.XtraEditors; using DevExpress.XtraReports.UserDesigner; namespace EIDSS.Reports.Barcode.Designer { public partial class DesignForm : XtraForm { private DevExpress.XtraReports.UserDesigner.XRDesignBarManager xrDesignBarManager1; private Bar bar2; private BarSubItem barSubItem1; private DevExpress.XtraReports.UserDesigner.CommandBarItem biGetOriginal; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem39; private DevExpress.XtraReports.UserDesigner.CommandBarItem biSave; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem40; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem41; private BarSubItem barSubItem2; private DevExpress.XtraReports.UserDesigner.CommandBarItem biUndo; private DevExpress.XtraReports.UserDesigner.CommandBarItem biRedo; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem42; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem43; private BarSubItem barSubItem3; private DevExpress.XtraReports.UserDesigner.BarReportTabButtonsListItem barReportTabButtonsListItem1; private BarSubItem barSubItem4; private DevExpress.XtraReports.UserDesigner.XRBarToolbarsListItem xrBarToolbarsListItem1; private BarSubItem barSubItem5; private DevExpress.XtraReports.UserDesigner.BarDockPanelsListItem barDockPanelsListItem1; private BarSubItem barSubItem6; private BarSubItem barSubItem7; private BarSubItem barSubItem8; private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyLeft; private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyCenter; private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyRight; private DevExpress.XtraReports.UserDesigner.CommandBarItem biJustifyJustify; private BarSubItem barSubItem9; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem9; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem10; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem11; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem12; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem13; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem14; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem8; private BarSubItem barSubItem10; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem15; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem16; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem17; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem18; private BarSubItem barSubItem11; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem19; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem20; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem21; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem22; private BarSubItem barSubItem12; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem23; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem24; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem25; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem26; private BarSubItem barSubItem13; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem27; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem28; private BarSubItem barSubItem14; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem29; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem30; private BarSubItem barSubItem15; private DevExpress.XtraReports.UserDesigner.CommandBarCheckItem commandBarCheckItem1; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem44; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem45; private DevExpress.XtraReports.UserDesigner.CommandBarItem commandBarItem46; private BarMdiChildrenListItem barMdiChildrenListItem1; private BarSubItem bsiLookAndFeel; private DevExpress.XtraReports.UserDesigner.DesignBar designBar2; private DevExpress.XtraReports.UserDesigner.DesignBar designBar3; private BarEditItem biFontName; private DevExpress.XtraReports.UserDesigner.RecentlyUsedItemsComboBox recentlyUsedItemsComboBox1; private BarEditItem biFontSize; private DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox designRepositoryItemComboBox1; private DevExpress.XtraReports.UserDesigner.CommandBarItem biZoomOut; private DevExpress.XtraReports.UserDesigner.XRZoomBarEditItem biZoom; private DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox designRepositoryItemComboBox2; private DevExpress.XtraReports.UserDesigner.CommandBarItem biZoomIn; private DevExpress.XtraReports.UserDesigner.XRDesignDockManager xrDesignDockManager1; private DevExpress.XtraReports.UserDesigner.XRDesignMdiController xrDesignMdiController1; private DevExpress.XtraTabbedMdi.XtraTabbedMdiManager xtraTabbedMdiManager1; private CommandBarItem commandBarItem49; private DevExpress.XtraBars.Docking.DockPanel panelContainer3; private GroupAndSortDockPanel groupAndSortDockPanel1; private DesignControlContainer groupAndSortDockPanel1_Container; private ErrorListDockPanel errorListDockPanel1; private DesignControlContainer errorListDockPanel1_Container; private DevExpress.XtraBars.Docking.DockPanel panelContainer1; private DevExpress.XtraBars.Docking.DockPanel panelContainer2; private ReportExplorerDockPanel reportExplorerDockPanel1; private DesignControlContainer reportExplorerDockPanel1_Container; private FieldListDockPanel fieldListDockPanel1; private DesignControlContainer fieldListDockPanel1_Container; private PropertyGridDockPanel propertyGridDockPanel1; private DesignControlContainer propertyGridDockPanel1_Container; private IContainer components; #region Windows Form Designer generated code private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DesignForm)); DevExpress.XtraReports.UserDesigner.BarInfo barInfo1 = new DevExpress.XtraReports.UserDesigner.BarInfo(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener1 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener2 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener3 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener4 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener5 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener6 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); DevExpress.XtraReports.UserDesigner.XRDesignPanelListener xrDesignPanelListener7 = new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener(); this.bar2 = new DevExpress.XtraBars.Bar(); this.xrDesignBarManager1 = new DevExpress.XtraReports.UserDesigner.XRDesignBarManager(); this.designBar2 = new DevExpress.XtraReports.UserDesigner.DesignBar(); this.biGetOriginal = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biSave = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biUndo = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biRedo = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biZoomOut = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biZoom = new DevExpress.XtraReports.UserDesigner.XRZoomBarEditItem(); this.designRepositoryItemComboBox2 = new DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox(); this.biZoomIn = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.designBar3 = new DevExpress.XtraReports.UserDesigner.DesignBar(); this.biFontName = new DevExpress.XtraBars.BarEditItem(); this.recentlyUsedItemsComboBox1 = new DevExpress.XtraReports.UserDesigner.RecentlyUsedItemsComboBox(); this.biFontSize = new DevExpress.XtraBars.BarEditItem(); this.designRepositoryItemComboBox1 = new DevExpress.XtraReports.UserDesigner.DesignRepositoryItemComboBox(); this.biJustifyLeft = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biJustifyCenter = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biJustifyRight = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.biJustifyJustify = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.xrDesignDockManager1 = new DevExpress.XtraReports.UserDesigner.XRDesignDockManager(); this.panelContainer3 = new DevExpress.XtraBars.Docking.DockPanel(); this.groupAndSortDockPanel1 = new DevExpress.XtraReports.UserDesigner.GroupAndSortDockPanel(); this.groupAndSortDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer(); this.errorListDockPanel1 = new DevExpress.XtraReports.UserDesigner.ErrorListDockPanel(); this.errorListDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer(); this.panelContainer1 = new DevExpress.XtraBars.Docking.DockPanel(); this.panelContainer2 = new DevExpress.XtraBars.Docking.DockPanel(); this.reportExplorerDockPanel1 = new DevExpress.XtraReports.UserDesigner.ReportExplorerDockPanel(); this.reportExplorerDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer(); this.fieldListDockPanel1 = new DevExpress.XtraReports.UserDesigner.FieldListDockPanel(); this.fieldListDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer(); this.propertyGridDockPanel1 = new DevExpress.XtraReports.UserDesigner.PropertyGridDockPanel(); this.propertyGridDockPanel1_Container = new DevExpress.XtraReports.UserDesigner.DesignControlContainer(); this.commandBarItem8 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem9 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem10 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem11 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem12 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem13 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem14 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem15 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem16 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem17 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem18 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem19 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem20 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem21 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem22 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem23 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem24 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem25 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem26 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem27 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem28 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem29 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem30 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.barSubItem1 = new DevExpress.XtraBars.BarSubItem(); this.commandBarItem39 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem40 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem49 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem41 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.barSubItem2 = new DevExpress.XtraBars.BarSubItem(); this.commandBarItem42 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem43 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.barSubItem3 = new DevExpress.XtraBars.BarSubItem(); this.barReportTabButtonsListItem1 = new DevExpress.XtraReports.UserDesigner.BarReportTabButtonsListItem(); this.barSubItem4 = new DevExpress.XtraBars.BarSubItem(); this.xrBarToolbarsListItem1 = new DevExpress.XtraReports.UserDesigner.XRBarToolbarsListItem(); this.barSubItem5 = new DevExpress.XtraBars.BarSubItem(); this.barDockPanelsListItem1 = new DevExpress.XtraReports.UserDesigner.BarDockPanelsListItem(); this.barSubItem6 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem7 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem8 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem9 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem10 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem11 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem12 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem13 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem14 = new DevExpress.XtraBars.BarSubItem(); this.barSubItem15 = new DevExpress.XtraBars.BarSubItem(); this.commandBarCheckItem1 = new DevExpress.XtraReports.UserDesigner.CommandBarCheckItem(); this.commandBarItem44 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem45 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.commandBarItem46 = new DevExpress.XtraReports.UserDesigner.CommandBarItem(); this.barMdiChildrenListItem1 = new DevExpress.XtraBars.BarMdiChildrenListItem(); this.bsiLookAndFeel = new DevExpress.XtraBars.BarSubItem(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.xrDesignMdiController1 = new DevExpress.XtraReports.UserDesigner.XRDesignMdiController(); this.xtraTabbedMdiManager1 = new DevExpress.XtraTabbedMdi.XtraTabbedMdiManager(this.components); this.HidePopupTimer = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.xrDesignBarManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.recentlyUsedItemsComboBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrDesignDockManager1)).BeginInit(); this.panelContainer3.SuspendLayout(); this.groupAndSortDockPanel1.SuspendLayout(); this.errorListDockPanel1.SuspendLayout(); this.panelContainer1.SuspendLayout(); this.panelContainer2.SuspendLayout(); this.reportExplorerDockPanel1.SuspendLayout(); this.fieldListDockPanel1.SuspendLayout(); this.propertyGridDockPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiManager1)).BeginInit(); this.SuspendLayout(); // // bar2 // this.bar2.BarName = "Toolbox"; this.bar2.DockCol = 1; this.bar2.DockRow = 0; this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar2.FloatLocation = new System.Drawing.Point(202, 248); this.bar2.OptionsBar.AllowQuickCustomization = false; this.bar2.OptionsBar.DisableClose = true; this.bar2.OptionsBar.DisableCustomization = true; this.bar2.OptionsBar.DrawDragBorder = false; resources.ApplyResources(this.bar2, "bar2"); // // xrDesignBarManager1 // this.xrDesignBarManager1.AllowCustomization = false; this.xrDesignBarManager1.AllowMoveBarOnToolbar = false; this.xrDesignBarManager1.AllowQuickCustomization = false; barInfo1.Bar = this.bar2; barInfo1.ToolboxType = DevExpress.XtraReports.UserDesigner.ToolboxType.Custom; this.xrDesignBarManager1.BarInfos.AddRange(new DevExpress.XtraReports.UserDesigner.BarInfo[] { barInfo1}); this.xrDesignBarManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.designBar2, this.designBar3, this.bar2}); this.xrDesignBarManager1.DockControls.Add(this.barDockControlTop); this.xrDesignBarManager1.DockControls.Add(this.barDockControlBottom); this.xrDesignBarManager1.DockControls.Add(this.barDockControlLeft); this.xrDesignBarManager1.DockControls.Add(this.barDockControlRight); this.xrDesignBarManager1.DockManager = this.xrDesignDockManager1; this.xrDesignBarManager1.FontNameBox = this.recentlyUsedItemsComboBox1; this.xrDesignBarManager1.FontNameEdit = this.biFontName; this.xrDesignBarManager1.FontSizeBox = this.designRepositoryItemComboBox1; this.xrDesignBarManager1.FontSizeEdit = this.biFontSize; this.xrDesignBarManager1.Form = this; this.xrDesignBarManager1.FormattingToolbar = this.designBar3; this.xrDesignBarManager1.HintStaticItem = null; this.xrDesignBarManager1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("xrDesignBarManager1.ImageStream"))); this.xrDesignBarManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.biFontName, this.biFontSize, this.biJustifyLeft, this.biJustifyCenter, this.biJustifyRight, this.biJustifyJustify, this.commandBarItem8, this.commandBarItem9, this.commandBarItem10, this.commandBarItem11, this.commandBarItem12, this.commandBarItem13, this.commandBarItem14, this.commandBarItem15, this.commandBarItem16, this.commandBarItem17, this.commandBarItem18, this.commandBarItem19, this.commandBarItem20, this.commandBarItem21, this.commandBarItem22, this.commandBarItem23, this.commandBarItem24, this.commandBarItem25, this.commandBarItem26, this.commandBarItem27, this.commandBarItem28, this.commandBarItem29, this.commandBarItem30, this.biGetOriginal, this.biSave, this.biUndo, this.biRedo, this.barSubItem1, this.barSubItem2, this.barSubItem3, this.barReportTabButtonsListItem1, this.barSubItem4, this.xrBarToolbarsListItem1, this.barSubItem5, this.barDockPanelsListItem1, this.barSubItem6, this.barSubItem7, this.barSubItem8, this.barSubItem9, this.barSubItem10, this.barSubItem11, this.barSubItem12, this.barSubItem13, this.barSubItem14, this.commandBarItem39, this.commandBarItem40, this.commandBarItem41, this.commandBarItem42, this.commandBarItem43, this.barSubItem15, this.commandBarCheckItem1, this.commandBarItem44, this.commandBarItem45, this.commandBarItem46, this.barMdiChildrenListItem1, this.biZoomOut, this.biZoom, this.biZoomIn, this.bsiLookAndFeel, this.commandBarItem49, this.barButtonItem1}); this.xrDesignBarManager1.LayoutToolbar = null; this.xrDesignBarManager1.MaxItemId = 80; this.xrDesignBarManager1.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.recentlyUsedItemsComboBox1, this.designRepositoryItemComboBox1, this.designRepositoryItemComboBox2}); this.xrDesignBarManager1.Toolbar = this.designBar2; this.xrDesignBarManager1.Updates.AddRange(new string[] { "Toolbox"}); this.xrDesignBarManager1.ZoomItem = this.biZoom; // // designBar2 // this.designBar2.BarName = "Toolbar"; this.designBar2.DockCol = 0; this.designBar2.DockRow = 0; this.designBar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.designBar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biGetOriginal), new DevExpress.XtraBars.LinkPersistInfo(this.biSave), new DevExpress.XtraBars.LinkPersistInfo(this.biUndo, true), new DevExpress.XtraBars.LinkPersistInfo(this.biRedo), new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true), new DevExpress.XtraBars.LinkPersistInfo(this.biZoom), new DevExpress.XtraBars.LinkPersistInfo(this.biZoomIn)}); this.designBar2.OptionsBar.AllowQuickCustomization = false; this.designBar2.OptionsBar.DisableClose = true; this.designBar2.OptionsBar.DisableCustomization = true; this.designBar2.OptionsBar.DrawDragBorder = false; resources.ApplyResources(this.designBar2, "designBar2"); // // biGetOriginal // resources.ApplyResources(this.biGetOriginal, "biGetOriginal"); this.biGetOriginal.Enabled = false; this.biGetOriginal.Glyph = global::EIDSS.Reports.Properties.Resources.restore; this.biGetOriginal.Id = 34; this.biGetOriginal.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R)); this.biGetOriginal.Name = "biGetOriginal"; this.biGetOriginal.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biRestoreDefault_ItemClick); // // biSave // resources.ApplyResources(this.biSave, "biSave"); this.biSave.Enabled = false; this.biSave.Id = 36; this.biSave.ImageIndex = 11; this.biSave.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)); this.biSave.Name = "biSave"; this.biSave.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biSave_ItemClick); // // biUndo // resources.ApplyResources(this.biUndo, "biUndo"); this.biUndo.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Undo; this.biUndo.Enabled = false; this.biUndo.Id = 40; this.biUndo.ImageIndex = 15; this.biUndo.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)); this.biUndo.Name = "biUndo"; // // biRedo // resources.ApplyResources(this.biRedo, "biRedo"); this.biRedo.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Redo; this.biRedo.Enabled = false; this.biRedo.Id = 41; this.biRedo.ImageIndex = 16; this.biRedo.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)); this.biRedo.Name = "biRedo"; // // biZoomOut // resources.ApplyResources(this.biZoomOut, "biZoomOut"); this.biZoomOut.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.ZoomOut; this.biZoomOut.Enabled = false; this.biZoomOut.Id = 71; this.biZoomOut.ImageIndex = 43; this.biZoomOut.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Subtract)); this.biZoomOut.Name = "biZoomOut"; // // biZoom // resources.ApplyResources(this.biZoom, "biZoom"); this.biZoom.Edit = this.designRepositoryItemComboBox2; this.biZoom.Enabled = false; this.biZoom.Id = 72; this.biZoom.Name = "biZoom"; // // designRepositoryItemComboBox2 // this.designRepositoryItemComboBox2.AutoComplete = false; this.designRepositoryItemComboBox2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("designRepositoryItemComboBox2.Buttons"))))}); this.designRepositoryItemComboBox2.Name = "designRepositoryItemComboBox2"; // // biZoomIn // resources.ApplyResources(this.biZoomIn, "biZoomIn"); this.biZoomIn.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.ZoomIn; this.biZoomIn.Enabled = false; this.biZoomIn.Id = 73; this.biZoomIn.ImageIndex = 44; this.biZoomIn.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Add)); this.biZoomIn.Name = "biZoomIn"; // // designBar3 // this.designBar3.BarName = "Formatting Toolbar"; this.designBar3.DockCol = 2; this.designBar3.DockRow = 0; this.designBar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.designBar3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.None, false, this.biFontName, false), new DevExpress.XtraBars.LinkPersistInfo(this.biFontSize), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyLeft, true), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyCenter), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyRight), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyJustify)}); this.designBar3.OptionsBar.DisableClose = true; this.designBar3.OptionsBar.DisableCustomization = true; this.designBar3.OptionsBar.DrawDragBorder = false; resources.ApplyResources(this.designBar3, "designBar3"); // // biFontName // resources.ApplyResources(this.biFontName, "biFontName"); this.biFontName.Edit = this.recentlyUsedItemsComboBox1; this.biFontName.Id = 0; this.biFontName.Name = "biFontName"; // // recentlyUsedItemsComboBox1 // resources.ApplyResources(this.recentlyUsedItemsComboBox1, "recentlyUsedItemsComboBox1"); this.recentlyUsedItemsComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("recentlyUsedItemsComboBox1.Buttons"))))}); this.recentlyUsedItemsComboBox1.DropDownRows = 12; this.recentlyUsedItemsComboBox1.Name = "recentlyUsedItemsComboBox1"; // // biFontSize // resources.ApplyResources(this.biFontSize, "biFontSize"); this.biFontSize.Edit = this.designRepositoryItemComboBox1; this.biFontSize.Id = 1; this.biFontSize.Name = "biFontSize"; // // designRepositoryItemComboBox1 // resources.ApplyResources(this.designRepositoryItemComboBox1, "designRepositoryItemComboBox1"); this.designRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("designRepositoryItemComboBox1.Buttons"))))}); this.designRepositoryItemComboBox1.Name = "designRepositoryItemComboBox1"; // // biJustifyLeft // resources.ApplyResources(this.biJustifyLeft, "biJustifyLeft"); this.biJustifyLeft.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyLeft; this.biJustifyLeft.Enabled = false; this.biJustifyLeft.Id = 7; this.biJustifyLeft.ImageIndex = 5; this.biJustifyLeft.Name = "biJustifyLeft"; // // biJustifyCenter // resources.ApplyResources(this.biJustifyCenter, "biJustifyCenter"); this.biJustifyCenter.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyCenter; this.biJustifyCenter.Enabled = false; this.biJustifyCenter.Id = 8; this.biJustifyCenter.ImageIndex = 6; this.biJustifyCenter.Name = "biJustifyCenter"; // // biJustifyRight // resources.ApplyResources(this.biJustifyRight, "biJustifyRight"); this.biJustifyRight.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyRight; this.biJustifyRight.Enabled = false; this.biJustifyRight.Id = 9; this.biJustifyRight.ImageIndex = 7; this.biJustifyRight.Name = "biJustifyRight"; // // biJustifyJustify // resources.ApplyResources(this.biJustifyJustify, "biJustifyJustify"); this.biJustifyJustify.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.JustifyJustify; this.biJustifyJustify.Enabled = false; this.biJustifyJustify.Id = 10; this.biJustifyJustify.ImageIndex = 8; this.biJustifyJustify.Name = "biJustifyJustify"; // // barDockControlTop // this.barDockControlTop.CausesValidation = false; resources.ApplyResources(this.barDockControlTop, "barDockControlTop"); // // barDockControlBottom // this.barDockControlBottom.CausesValidation = false; resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom"); // // barDockControlLeft // this.barDockControlLeft.CausesValidation = false; resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft"); // // barDockControlRight // this.barDockControlRight.CausesValidation = false; resources.ApplyResources(this.barDockControlRight, "barDockControlRight"); // // xrDesignDockManager1 // this.xrDesignDockManager1.Form = this; this.xrDesignDockManager1.HiddenPanels.AddRange(new DevExpress.XtraBars.Docking.DockPanel[] { this.panelContainer3, this.panelContainer1}); this.xrDesignDockManager1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("xrDesignDockManager1.ImageStream"))); this.xrDesignDockManager1.TopZIndexControls.AddRange(new string[] { "DevExpress.XtraBars.BarDockControl", "DevExpress.XtraBars.StandaloneBarDockControl", "System.Windows.Forms.StatusBar", "DevExpress.XtraBars.Ribbon.RibbonStatusBar", "DevExpress.XtraBars.Ribbon.RibbonControl"}); // // panelContainer3 // this.panelContainer3.ActiveChild = this.groupAndSortDockPanel1; this.panelContainer3.Controls.Add(this.groupAndSortDockPanel1); this.panelContainer3.Controls.Add(this.errorListDockPanel1); this.panelContainer3.Dock = DevExpress.XtraBars.Docking.DockingStyle.Bottom; this.panelContainer3.ID = new System.Guid("6027d502-d4b1-488d-b50b-ac2fbbd40bf8"); this.panelContainer3.ImageIndex = 1; resources.ApplyResources(this.panelContainer3, "panelContainer3"); this.panelContainer3.Name = "panelContainer3"; this.panelContainer3.OriginalSize = new System.Drawing.Size(200, 160); this.panelContainer3.SavedDock = DevExpress.XtraBars.Docking.DockingStyle.Bottom; this.panelContainer3.SavedIndex = 1; this.panelContainer3.Tabbed = true; this.panelContainer3.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden; // // groupAndSortDockPanel1 // this.groupAndSortDockPanel1.Controls.Add(this.groupAndSortDockPanel1_Container); this.groupAndSortDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.groupAndSortDockPanel1.ID = new System.Guid("4bab159e-c495-4d67-87dc-f4e895da443e"); this.groupAndSortDockPanel1.ImageIndex = 1; resources.ApplyResources(this.groupAndSortDockPanel1, "groupAndSortDockPanel1"); this.groupAndSortDockPanel1.Name = "groupAndSortDockPanel1"; this.groupAndSortDockPanel1.OriginalSize = new System.Drawing.Size(620, 106); this.groupAndSortDockPanel1.XRDesignPanel = null; // // groupAndSortDockPanel1_Container // resources.ApplyResources(this.groupAndSortDockPanel1_Container, "groupAndSortDockPanel1_Container"); this.groupAndSortDockPanel1_Container.Name = "groupAndSortDockPanel1_Container"; // // errorListDockPanel1 // this.errorListDockPanel1.Controls.Add(this.errorListDockPanel1_Container); this.errorListDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.errorListDockPanel1.ID = new System.Guid("5a9a01fd-6e95-4e81-a8c4-ac63153d7488"); this.errorListDockPanel1.ImageIndex = 5; resources.ApplyResources(this.errorListDockPanel1, "errorListDockPanel1"); this.errorListDockPanel1.Name = "errorListDockPanel1"; this.errorListDockPanel1.OriginalSize = new System.Drawing.Size(620, 106); this.errorListDockPanel1.XRDesignPanel = null; // // errorListDockPanel1_Container // resources.ApplyResources(this.errorListDockPanel1_Container, "errorListDockPanel1_Container"); this.errorListDockPanel1_Container.Name = "errorListDockPanel1_Container"; // // panelContainer1 // this.panelContainer1.Controls.Add(this.panelContainer2); this.panelContainer1.Controls.Add(this.propertyGridDockPanel1); this.panelContainer1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Right; this.panelContainer1.ID = new System.Guid("73163da5-9eeb-4b18-8992-c9a9a9f93986"); resources.ApplyResources(this.panelContainer1, "panelContainer1"); this.panelContainer1.Name = "panelContainer1"; this.panelContainer1.OriginalSize = new System.Drawing.Size(250, 200); this.panelContainer1.SavedDock = DevExpress.XtraBars.Docking.DockingStyle.Right; this.panelContainer1.SavedIndex = 0; this.panelContainer1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden; // // panelContainer2 // this.panelContainer2.ActiveChild = this.reportExplorerDockPanel1; this.panelContainer2.Controls.Add(this.reportExplorerDockPanel1); this.panelContainer2.Controls.Add(this.fieldListDockPanel1); this.panelContainer2.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.panelContainer2.ID = new System.Guid("ec598d35-f04f-46c8-8b97-6b28f6c4dc4f"); this.panelContainer2.ImageIndex = 3; resources.ApplyResources(this.panelContainer2, "panelContainer2"); this.panelContainer2.Name = "panelContainer2"; this.panelContainer2.OriginalSize = new System.Drawing.Size(250, 187); this.panelContainer2.Tabbed = true; // // reportExplorerDockPanel1 // this.reportExplorerDockPanel1.Controls.Add(this.reportExplorerDockPanel1_Container); this.reportExplorerDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.reportExplorerDockPanel1.ID = new System.Guid("fb3ec6cc-3b9b-4b9c-91cf-cff78c1edbf1"); this.reportExplorerDockPanel1.ImageIndex = 3; resources.ApplyResources(this.reportExplorerDockPanel1, "reportExplorerDockPanel1"); this.reportExplorerDockPanel1.Name = "reportExplorerDockPanel1"; this.reportExplorerDockPanel1.OriginalSize = new System.Drawing.Size(244, 133); this.reportExplorerDockPanel1.XRDesignPanel = null; // // reportExplorerDockPanel1_Container // resources.ApplyResources(this.reportExplorerDockPanel1_Container, "reportExplorerDockPanel1_Container"); this.reportExplorerDockPanel1_Container.Name = "reportExplorerDockPanel1_Container"; // // fieldListDockPanel1 // this.fieldListDockPanel1.Controls.Add(this.fieldListDockPanel1_Container); this.fieldListDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.fieldListDockPanel1.ID = new System.Guid("faf69838-a93f-4114-83e8-d0d09cc5ce95"); this.fieldListDockPanel1.ImageIndex = 0; resources.ApplyResources(this.fieldListDockPanel1, "fieldListDockPanel1"); this.fieldListDockPanel1.Name = "fieldListDockPanel1"; this.fieldListDockPanel1.OriginalSize = new System.Drawing.Size(244, 133); this.fieldListDockPanel1.XRDesignPanel = null; // // fieldListDockPanel1_Container // resources.ApplyResources(this.fieldListDockPanel1_Container, "fieldListDockPanel1_Container"); this.fieldListDockPanel1_Container.Name = "fieldListDockPanel1_Container"; // // propertyGridDockPanel1 // this.propertyGridDockPanel1.Controls.Add(this.propertyGridDockPanel1_Container); this.propertyGridDockPanel1.Dock = DevExpress.XtraBars.Docking.DockingStyle.Fill; this.propertyGridDockPanel1.ID = new System.Guid("b38d12c3-cd06-4dec-b93d-63a0088e495a"); this.propertyGridDockPanel1.ImageIndex = 2; resources.ApplyResources(this.propertyGridDockPanel1, "propertyGridDockPanel1"); this.propertyGridDockPanel1.Name = "propertyGridDockPanel1"; this.propertyGridDockPanel1.OriginalSize = new System.Drawing.Size(250, 187); this.propertyGridDockPanel1.XRDesignPanel = null; // // propertyGridDockPanel1_Container // resources.ApplyResources(this.propertyGridDockPanel1_Container, "propertyGridDockPanel1_Container"); this.propertyGridDockPanel1_Container.Name = "propertyGridDockPanel1_Container"; // // commandBarItem8 // resources.ApplyResources(this.commandBarItem8, "commandBarItem8"); this.commandBarItem8.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignToGrid; this.commandBarItem8.Enabled = false; this.commandBarItem8.Id = 11; this.commandBarItem8.ImageIndex = 17; this.commandBarItem8.Name = "commandBarItem8"; // // commandBarItem9 // resources.ApplyResources(this.commandBarItem9, "commandBarItem9"); this.commandBarItem9.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignLeft; this.commandBarItem9.Enabled = false; this.commandBarItem9.Id = 12; this.commandBarItem9.ImageIndex = 18; this.commandBarItem9.Name = "commandBarItem9"; // // commandBarItem10 // resources.ApplyResources(this.commandBarItem10, "commandBarItem10"); this.commandBarItem10.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignVerticalCenters; this.commandBarItem10.Enabled = false; this.commandBarItem10.Id = 13; this.commandBarItem10.ImageIndex = 19; this.commandBarItem10.Name = "commandBarItem10"; // // commandBarItem11 // resources.ApplyResources(this.commandBarItem11, "commandBarItem11"); this.commandBarItem11.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignRight; this.commandBarItem11.Enabled = false; this.commandBarItem11.Id = 14; this.commandBarItem11.ImageIndex = 20; this.commandBarItem11.Name = "commandBarItem11"; // // commandBarItem12 // resources.ApplyResources(this.commandBarItem12, "commandBarItem12"); this.commandBarItem12.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignTop; this.commandBarItem12.Enabled = false; this.commandBarItem12.Id = 15; this.commandBarItem12.ImageIndex = 21; this.commandBarItem12.Name = "commandBarItem12"; // // commandBarItem13 // resources.ApplyResources(this.commandBarItem13, "commandBarItem13"); this.commandBarItem13.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignHorizontalCenters; this.commandBarItem13.Enabled = false; this.commandBarItem13.Id = 16; this.commandBarItem13.ImageIndex = 22; this.commandBarItem13.Name = "commandBarItem13"; // // commandBarItem14 // resources.ApplyResources(this.commandBarItem14, "commandBarItem14"); this.commandBarItem14.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.AlignBottom; this.commandBarItem14.Enabled = false; this.commandBarItem14.Id = 17; this.commandBarItem14.ImageIndex = 23; this.commandBarItem14.Name = "commandBarItem14"; // // commandBarItem15 // resources.ApplyResources(this.commandBarItem15, "commandBarItem15"); this.commandBarItem15.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControlWidth; this.commandBarItem15.Enabled = false; this.commandBarItem15.Id = 18; this.commandBarItem15.ImageIndex = 24; this.commandBarItem15.Name = "commandBarItem15"; // // commandBarItem16 // resources.ApplyResources(this.commandBarItem16, "commandBarItem16"); this.commandBarItem16.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToGrid; this.commandBarItem16.Enabled = false; this.commandBarItem16.Id = 19; this.commandBarItem16.ImageIndex = 25; this.commandBarItem16.Name = "commandBarItem16"; // // commandBarItem17 // resources.ApplyResources(this.commandBarItem17, "commandBarItem17"); this.commandBarItem17.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControlHeight; this.commandBarItem17.Enabled = false; this.commandBarItem17.Id = 20; this.commandBarItem17.ImageIndex = 26; this.commandBarItem17.Name = "commandBarItem17"; // // commandBarItem18 // resources.ApplyResources(this.commandBarItem18, "commandBarItem18"); this.commandBarItem18.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SizeToControl; this.commandBarItem18.Enabled = false; this.commandBarItem18.Id = 21; this.commandBarItem18.ImageIndex = 27; this.commandBarItem18.Name = "commandBarItem18"; // // commandBarItem19 // resources.ApplyResources(this.commandBarItem19, "commandBarItem19"); this.commandBarItem19.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceMakeEqual; this.commandBarItem19.Enabled = false; this.commandBarItem19.Id = 22; this.commandBarItem19.ImageIndex = 28; this.commandBarItem19.Name = "commandBarItem19"; // // commandBarItem20 // resources.ApplyResources(this.commandBarItem20, "commandBarItem20"); this.commandBarItem20.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceIncrease; this.commandBarItem20.Enabled = false; this.commandBarItem20.Id = 23; this.commandBarItem20.ImageIndex = 29; this.commandBarItem20.Name = "commandBarItem20"; // // commandBarItem21 // resources.ApplyResources(this.commandBarItem21, "commandBarItem21"); this.commandBarItem21.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceDecrease; this.commandBarItem21.Enabled = false; this.commandBarItem21.Id = 24; this.commandBarItem21.ImageIndex = 30; this.commandBarItem21.Name = "commandBarItem21"; // // commandBarItem22 // resources.ApplyResources(this.commandBarItem22, "commandBarItem22"); this.commandBarItem22.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.HorizSpaceConcatenate; this.commandBarItem22.Enabled = false; this.commandBarItem22.Id = 25; this.commandBarItem22.ImageIndex = 31; this.commandBarItem22.Name = "commandBarItem22"; // // commandBarItem23 // resources.ApplyResources(this.commandBarItem23, "commandBarItem23"); this.commandBarItem23.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceMakeEqual; this.commandBarItem23.Enabled = false; this.commandBarItem23.Id = 26; this.commandBarItem23.ImageIndex = 32; this.commandBarItem23.Name = "commandBarItem23"; // // commandBarItem24 // resources.ApplyResources(this.commandBarItem24, "commandBarItem24"); this.commandBarItem24.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceIncrease; this.commandBarItem24.Enabled = false; this.commandBarItem24.Id = 27; this.commandBarItem24.ImageIndex = 33; this.commandBarItem24.Name = "commandBarItem24"; // // commandBarItem25 // resources.ApplyResources(this.commandBarItem25, "commandBarItem25"); this.commandBarItem25.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceDecrease; this.commandBarItem25.Enabled = false; this.commandBarItem25.Id = 28; this.commandBarItem25.ImageIndex = 34; this.commandBarItem25.Name = "commandBarItem25"; // // commandBarItem26 // resources.ApplyResources(this.commandBarItem26, "commandBarItem26"); this.commandBarItem26.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.VertSpaceConcatenate; this.commandBarItem26.Enabled = false; this.commandBarItem26.Id = 29; this.commandBarItem26.ImageIndex = 35; this.commandBarItem26.Name = "commandBarItem26"; // // commandBarItem27 // resources.ApplyResources(this.commandBarItem27, "commandBarItem27"); this.commandBarItem27.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.CenterHorizontally; this.commandBarItem27.Enabled = false; this.commandBarItem27.Id = 30; this.commandBarItem27.ImageIndex = 36; this.commandBarItem27.Name = "commandBarItem27"; // // commandBarItem28 // resources.ApplyResources(this.commandBarItem28, "commandBarItem28"); this.commandBarItem28.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.CenterVertically; this.commandBarItem28.Enabled = false; this.commandBarItem28.Id = 31; this.commandBarItem28.ImageIndex = 37; this.commandBarItem28.Name = "commandBarItem28"; // // commandBarItem29 // resources.ApplyResources(this.commandBarItem29, "commandBarItem29"); this.commandBarItem29.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.BringToFront; this.commandBarItem29.Enabled = false; this.commandBarItem29.Id = 32; this.commandBarItem29.ImageIndex = 38; this.commandBarItem29.Name = "commandBarItem29"; // // commandBarItem30 // resources.ApplyResources(this.commandBarItem30, "commandBarItem30"); this.commandBarItem30.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SendToBack; this.commandBarItem30.Enabled = false; this.commandBarItem30.Id = 33; this.commandBarItem30.ImageIndex = 39; this.commandBarItem30.Name = "commandBarItem30"; // // barSubItem1 // resources.ApplyResources(this.barSubItem1, "barSubItem1"); this.barSubItem1.Id = 43; this.barSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biGetOriginal), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem39), new DevExpress.XtraBars.LinkPersistInfo(this.biSave, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem40), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem49), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem41, true)}); this.barSubItem1.Name = "barSubItem1"; // // commandBarItem39 // resources.ApplyResources(this.commandBarItem39, "commandBarItem39"); this.commandBarItem39.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.NewReportWizard; this.commandBarItem39.Enabled = false; this.commandBarItem39.Id = 60; this.commandBarItem39.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.W)); this.commandBarItem39.Name = "commandBarItem39"; // // commandBarItem40 // resources.ApplyResources(this.commandBarItem40, "commandBarItem40"); this.commandBarItem40.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SaveFileAs; this.commandBarItem40.Enabled = false; this.commandBarItem40.Id = 61; this.commandBarItem40.Name = "commandBarItem40"; // // commandBarItem49 // resources.ApplyResources(this.commandBarItem49, "commandBarItem49"); this.commandBarItem49.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Close; this.commandBarItem49.Enabled = false; this.commandBarItem49.Id = 78; this.commandBarItem49.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4)); this.commandBarItem49.Name = "commandBarItem49"; // // commandBarItem41 // resources.ApplyResources(this.commandBarItem41, "commandBarItem41"); this.commandBarItem41.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Exit; this.commandBarItem41.Enabled = false; this.commandBarItem41.Id = 62; this.commandBarItem41.Name = "commandBarItem41"; // // barSubItem2 // resources.ApplyResources(this.barSubItem2, "barSubItem2"); this.barSubItem2.Id = 44; this.barSubItem2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biUndo, true), new DevExpress.XtraBars.LinkPersistInfo(this.biRedo), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem42), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem43, true)}); this.barSubItem2.Name = "barSubItem2"; // // commandBarItem42 // resources.ApplyResources(this.commandBarItem42, "commandBarItem42"); this.commandBarItem42.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.Delete; this.commandBarItem42.Enabled = false; this.commandBarItem42.Id = 63; this.commandBarItem42.Name = "commandBarItem42"; // // commandBarItem43 // resources.ApplyResources(this.commandBarItem43, "commandBarItem43"); this.commandBarItem43.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.SelectAll; this.commandBarItem43.Enabled = false; this.commandBarItem43.Id = 64; this.commandBarItem43.ItemShortcut = new DevExpress.XtraBars.BarShortcut((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)); this.commandBarItem43.Name = "commandBarItem43"; // // barSubItem3 // resources.ApplyResources(this.barSubItem3, "barSubItem3"); this.barSubItem3.Id = 45; this.barSubItem3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barReportTabButtonsListItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem4, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem5, true)}); this.barSubItem3.Name = "barSubItem3"; // // barReportTabButtonsListItem1 // resources.ApplyResources(this.barReportTabButtonsListItem1, "barReportTabButtonsListItem1"); this.barReportTabButtonsListItem1.Id = 46; this.barReportTabButtonsListItem1.Name = "barReportTabButtonsListItem1"; // // barSubItem4 // resources.ApplyResources(this.barSubItem4, "barSubItem4"); this.barSubItem4.Id = 47; this.barSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.xrBarToolbarsListItem1)}); this.barSubItem4.Name = "barSubItem4"; // // xrBarToolbarsListItem1 // resources.ApplyResources(this.xrBarToolbarsListItem1, "xrBarToolbarsListItem1"); this.xrBarToolbarsListItem1.Id = 48; this.xrBarToolbarsListItem1.Name = "xrBarToolbarsListItem1"; // // barSubItem5 // resources.ApplyResources(this.barSubItem5, "barSubItem5"); this.barSubItem5.Id = 49; this.barSubItem5.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barDockPanelsListItem1)}); this.barSubItem5.Name = "barSubItem5"; // // barDockPanelsListItem1 // resources.ApplyResources(this.barDockPanelsListItem1, "barDockPanelsListItem1"); this.barDockPanelsListItem1.Id = 50; this.barDockPanelsListItem1.Name = "barDockPanelsListItem1"; this.barDockPanelsListItem1.ShowCustomizationItem = false; this.barDockPanelsListItem1.ShowDockPanels = true; this.barDockPanelsListItem1.ShowToolbars = false; // // barSubItem6 // resources.ApplyResources(this.barSubItem6, "barSubItem6"); this.barSubItem6.Id = 51; this.barSubItem6.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem7, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem8), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem9, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem10), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem11, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem12), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem13, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem14, true)}); this.barSubItem6.Name = "barSubItem6"; // // barSubItem7 // resources.ApplyResources(this.barSubItem7, "barSubItem7"); this.barSubItem7.Id = 52; this.barSubItem7.Name = "barSubItem7"; // // barSubItem8 // resources.ApplyResources(this.barSubItem8, "barSubItem8"); this.barSubItem8.Id = 53; this.barSubItem8.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyLeft, true), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyCenter), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyRight), new DevExpress.XtraBars.LinkPersistInfo(this.biJustifyJustify)}); this.barSubItem8.Name = "barSubItem8"; // // barSubItem9 // resources.ApplyResources(this.barSubItem9, "barSubItem9"); this.barSubItem9.Id = 54; this.barSubItem9.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem9, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem10), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem11), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem12, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem13), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem14), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem8, true)}); this.barSubItem9.Name = "barSubItem9"; // // barSubItem10 // resources.ApplyResources(this.barSubItem10, "barSubItem10"); this.barSubItem10.Id = 55; this.barSubItem10.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem15, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem16), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem17), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem18)}); this.barSubItem10.Name = "barSubItem10"; // // barSubItem11 // resources.ApplyResources(this.barSubItem11, "barSubItem11"); this.barSubItem11.Id = 56; this.barSubItem11.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem19, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem20), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem21), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem22)}); this.barSubItem11.Name = "barSubItem11"; // // barSubItem12 // resources.ApplyResources(this.barSubItem12, "barSubItem12"); this.barSubItem12.Id = 57; this.barSubItem12.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem23, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem24), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem25), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem26)}); this.barSubItem12.Name = "barSubItem12"; // // barSubItem13 // resources.ApplyResources(this.barSubItem13, "barSubItem13"); this.barSubItem13.Id = 58; this.barSubItem13.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem27, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem28)}); this.barSubItem13.Name = "barSubItem13"; // // barSubItem14 // resources.ApplyResources(this.barSubItem14, "barSubItem14"); this.barSubItem14.Id = 59; this.barSubItem14.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem29, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem30)}); this.barSubItem14.Name = "barSubItem14"; // // barSubItem15 // resources.ApplyResources(this.barSubItem15, "barSubItem15"); this.barSubItem15.Id = 65; this.barSubItem15.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.commandBarCheckItem1, true), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem44), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem45), new DevExpress.XtraBars.LinkPersistInfo(this.commandBarItem46), new DevExpress.XtraBars.LinkPersistInfo(this.barMdiChildrenListItem1, true)}); this.barSubItem15.Name = "barSubItem15"; // // commandBarCheckItem1 // resources.ApplyResources(this.commandBarCheckItem1, "commandBarCheckItem1"); this.commandBarCheckItem1.Checked = true; this.commandBarCheckItem1.CheckedCommand = DevExpress.XtraReports.UserDesigner.ReportCommand.ShowTabbedInterface; this.commandBarCheckItem1.Enabled = false; this.commandBarCheckItem1.Id = 66; this.commandBarCheckItem1.Name = "commandBarCheckItem1"; this.commandBarCheckItem1.UncheckedCommand = DevExpress.XtraReports.UserDesigner.ReportCommand.ShowWindowInterface; // // commandBarItem44 // resources.ApplyResources(this.commandBarItem44, "commandBarItem44"); this.commandBarItem44.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiCascade; this.commandBarItem44.Enabled = false; this.commandBarItem44.Id = 67; this.commandBarItem44.ImageIndex = 40; this.commandBarItem44.Name = "commandBarItem44"; // // commandBarItem45 // resources.ApplyResources(this.commandBarItem45, "commandBarItem45"); this.commandBarItem45.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiTileHorizontal; this.commandBarItem45.Enabled = false; this.commandBarItem45.Id = 68; this.commandBarItem45.ImageIndex = 41; this.commandBarItem45.Name = "commandBarItem45"; // // commandBarItem46 // resources.ApplyResources(this.commandBarItem46, "commandBarItem46"); this.commandBarItem46.Command = DevExpress.XtraReports.UserDesigner.ReportCommand.MdiTileVertical; this.commandBarItem46.Enabled = false; this.commandBarItem46.Id = 69; this.commandBarItem46.ImageIndex = 42; this.commandBarItem46.Name = "commandBarItem46"; // // barMdiChildrenListItem1 // resources.ApplyResources(this.barMdiChildrenListItem1, "barMdiChildrenListItem1"); this.barMdiChildrenListItem1.Id = 70; this.barMdiChildrenListItem1.Name = "barMdiChildrenListItem1"; // // bsiLookAndFeel // resources.ApplyResources(this.bsiLookAndFeel, "bsiLookAndFeel"); this.bsiLookAndFeel.Id = 74; this.bsiLookAndFeel.Name = "bsiLookAndFeel"; // // barButtonItem1 // resources.ApplyResources(this.barButtonItem1, "barButtonItem1"); this.barButtonItem1.Id = 79; this.barButtonItem1.Name = "barButtonItem1"; // // xrDesignMdiController1 // xrDesignPanelListener1.DesignControl = this.xrDesignBarManager1; xrDesignPanelListener2.DesignControl = this.xrDesignDockManager1; xrDesignPanelListener3.DesignControl = this.fieldListDockPanel1; xrDesignPanelListener4.DesignControl = this.propertyGridDockPanel1; xrDesignPanelListener5.DesignControl = this.reportExplorerDockPanel1; xrDesignPanelListener6.DesignControl = this.groupAndSortDockPanel1; xrDesignPanelListener7.DesignControl = this.errorListDockPanel1; this.xrDesignMdiController1.DesignPanelListeners.AddRange(new DevExpress.XtraReports.UserDesigner.XRDesignPanelListener[] { xrDesignPanelListener1, xrDesignPanelListener2, xrDesignPanelListener3, xrDesignPanelListener4, xrDesignPanelListener5, xrDesignPanelListener6, xrDesignPanelListener7}); this.xrDesignMdiController1.Form = this; this.xrDesignMdiController1.XtraTabbedMdiManager = this.xtraTabbedMdiManager1; // // xtraTabbedMdiManager1 // this.xtraTabbedMdiManager1.AllowDragDrop = DevExpress.Utils.DefaultBoolean.False; this.xtraTabbedMdiManager1.ClosePageButtonShowMode = DevExpress.XtraTab.ClosePageButtonShowMode.InActiveTabPageHeader; this.xtraTabbedMdiManager1.CloseTabOnMiddleClick = DevExpress.XtraTabbedMdi.CloseTabOnMiddleClick.Never; this.xtraTabbedMdiManager1.MdiParent = this; this.xtraTabbedMdiManager1.ShowFloatingDropHint = DevExpress.Utils.DefaultBoolean.False; this.xtraTabbedMdiManager1.UseDocumentSelector = DevExpress.Utils.DefaultBoolean.False; this.xtraTabbedMdiManager1.UseFormIconAsPageImage = DevExpress.Utils.DefaultBoolean.False; // // HidePopupTimer // this.HidePopupTimer.Tick += new System.EventHandler(this.HidePopupTimer_Tick); // // DesignForm // resources.ApplyResources(this, "$this"); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.IsMdiContainer = true; this.Name = "DesignForm"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.Load += new System.EventHandler(this.MainForm_Load); ((System.ComponentModel.ISupportInitialize)(this.xrDesignBarManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.recentlyUsedItemsComboBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.designRepositoryItemComboBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrDesignDockManager1)).EndInit(); this.panelContainer3.ResumeLayout(false); this.groupAndSortDockPanel1.ResumeLayout(false); this.errorListDockPanel1.ResumeLayout(false); this.panelContainer1.ResumeLayout(false); this.panelContainer2.ResumeLayout(false); this.reportExplorerDockPanel1.ResumeLayout(false); this.fieldListDockPanel1.ResumeLayout(false); this.propertyGridDockPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiManager1)).EndInit(); this.ResumeLayout(false); } #endregion private BarButtonItem barButtonItem1; private BarDockControl barDockControlTop; private BarDockControl barDockControlBottom; private BarDockControl barDockControlLeft; private BarDockControl barDockControlRight; private System.Windows.Forms.Timer HidePopupTimer; } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public static partial class Console { public static System.ConsoleColor BackgroundColor { get { throw null; } set { } } public static int BufferHeight { get { throw null; } set { } } public static int BufferWidth { get { throw null; } set { } } public static bool CapsLock { get { throw null; } } public static int CursorLeft { get { throw null; } set { } } public static int CursorSize { get { throw null; } set { } } public static int CursorTop { get { throw null; } set { } } public static bool CursorVisible { get { throw null; } set { } } public static System.IO.TextWriter Error { get { throw null; } } public static System.ConsoleColor ForegroundColor { get { throw null; } set { } } public static System.IO.TextReader In { get { throw null; } } public static System.Text.Encoding InputEncoding { get { throw null; } set { } } public static bool IsErrorRedirected { get { throw null; } } public static bool IsInputRedirected { get { throw null; } } public static bool IsOutputRedirected { get { throw null; } } public static bool KeyAvailable { get { throw null; } } public static int LargestWindowHeight { get { throw null; } } public static int LargestWindowWidth { get { throw null; } } public static bool NumberLock { get { throw null; } } public static System.IO.TextWriter Out { get { throw null; } } public static System.Text.Encoding OutputEncoding { get { throw null; } set { } } public static string Title { get { throw null; } set { } } public static bool TreatControlCAsInput { get { throw null; } set { } } public static int WindowHeight { get { throw null; } set { } } public static int WindowLeft { get { throw null; } set { } } public static int WindowTop { get { throw null; } set { } } public static int WindowWidth { get { throw null; } set { } } public static event System.ConsoleCancelEventHandler CancelKeyPress { add { } remove { } } public static void Beep() { } public static void Beep(int frequency, int duration) { } public static void Clear() { } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { } public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, System.ConsoleColor sourceForeColor, System.ConsoleColor sourceBackColor) { } public static System.IO.Stream OpenStandardError() { throw null; } public static System.IO.Stream OpenStandardError(int bufferSize) { throw null; } public static System.IO.Stream OpenStandardInput() { throw null; } public static System.IO.Stream OpenStandardInput(int bufferSize) { throw null; } public static System.IO.Stream OpenStandardOutput() { throw null; } public static System.IO.Stream OpenStandardOutput(int bufferSize) { throw null; } public static int Read() { throw null; } public static System.ConsoleKeyInfo ReadKey() { throw null; } public static System.ConsoleKeyInfo ReadKey(bool intercept) { throw null; } public static string ReadLine() { throw null; } public static void ResetColor() { } public static void SetBufferSize(int width, int height) { } public static void SetCursorPosition(int left, int top) { } public static void SetError(System.IO.TextWriter newError) { } public static void SetIn(System.IO.TextReader newIn) { } public static void SetOut(System.IO.TextWriter newOut) { } public static void SetWindowPosition(int left, int top) { } public static void SetWindowSize(int width, int height) { } public static void Write(bool value) { } public static void Write(char value) { } public static void Write(char[] buffer) { } public static void Write(char[] buffer, int index, int count) { } public static void Write(decimal value) { } public static void Write(double value) { } public static void Write(int value) { } public static void Write(long value) { } public static void Write(object value) { } public static void Write(float value) { } public static void Write(string value) { } public static void Write(string format, object arg0) { } public static void Write(string format, object arg0, object arg1) { } public static void Write(string format, object arg0, object arg1, object arg2) { } public static void Write(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void Write(uint value) { } [System.CLSCompliantAttribute(false)] public static void Write(ulong value) { } public static void WriteLine() { } public static void WriteLine(bool value) { } public static void WriteLine(char value) { } public static void WriteLine(char[] buffer) { } public static void WriteLine(char[] buffer, int index, int count) { } public static void WriteLine(decimal value) { } public static void WriteLine(double value) { } public static void WriteLine(int value) { } public static void WriteLine(long value) { } public static void WriteLine(object value) { } public static void WriteLine(float value) { } public static void WriteLine(string value) { } public static void WriteLine(string format, object arg0) { } public static void WriteLine(string format, object arg0, object arg1) { } public static void WriteLine(string format, object arg0, object arg1, object arg2) { } public static void WriteLine(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(uint value) { } [System.CLSCompliantAttribute(false)] public static void WriteLine(ulong value) { } } public sealed partial class ConsoleCancelEventArgs : System.EventArgs { internal ConsoleCancelEventArgs() { } public bool Cancel { get { throw null; } set { } } public System.ConsoleSpecialKey SpecialKey { get { throw null; } } } public delegate void ConsoleCancelEventHandler(object sender, System.ConsoleCancelEventArgs e); public enum ConsoleColor { Black = 0, Blue = 9, Cyan = 11, DarkBlue = 1, DarkCyan = 3, DarkGray = 8, DarkGreen = 2, DarkMagenta = 5, DarkRed = 4, DarkYellow = 6, Gray = 7, Green = 10, Magenta = 13, Red = 12, White = 15, Yellow = 14, } public enum ConsoleKey { A = 65, Add = 107, Applications = 93, Attention = 246, B = 66, Backspace = 8, BrowserBack = 166, BrowserFavorites = 171, BrowserForward = 167, BrowserHome = 172, BrowserRefresh = 168, BrowserSearch = 170, BrowserStop = 169, C = 67, Clear = 12, CrSel = 247, D = 68, D0 = 48, D1 = 49, D2 = 50, D3 = 51, D4 = 52, D5 = 53, D6 = 54, D7 = 55, D8 = 56, D9 = 57, Decimal = 110, Delete = 46, Divide = 111, DownArrow = 40, E = 69, End = 35, Enter = 13, EraseEndOfFile = 249, Escape = 27, Execute = 43, ExSel = 248, F = 70, F1 = 112, F10 = 121, F11 = 122, F12 = 123, F13 = 124, F14 = 125, F15 = 126, F16 = 127, F17 = 128, F18 = 129, F19 = 130, F2 = 113, F20 = 131, F21 = 132, F22 = 133, F23 = 134, F24 = 135, F3 = 114, F4 = 115, F5 = 116, F6 = 117, F7 = 118, F8 = 119, F9 = 120, G = 71, H = 72, Help = 47, Home = 36, I = 73, Insert = 45, J = 74, K = 75, L = 76, LaunchApp1 = 182, LaunchApp2 = 183, LaunchMail = 180, LaunchMediaSelect = 181, LeftArrow = 37, LeftWindows = 91, M = 77, MediaNext = 176, MediaPlay = 179, MediaPrevious = 177, MediaStop = 178, Multiply = 106, N = 78, NoName = 252, NumPad0 = 96, NumPad1 = 97, NumPad2 = 98, NumPad3 = 99, NumPad4 = 100, NumPad5 = 101, NumPad6 = 102, NumPad7 = 103, NumPad8 = 104, NumPad9 = 105, O = 79, Oem1 = 186, Oem102 = 226, Oem2 = 191, Oem3 = 192, Oem4 = 219, Oem5 = 220, Oem6 = 221, Oem7 = 222, Oem8 = 223, OemClear = 254, OemComma = 188, OemMinus = 189, OemPeriod = 190, OemPlus = 187, P = 80, Pa1 = 253, Packet = 231, PageDown = 34, PageUp = 33, Pause = 19, Play = 250, Print = 42, PrintScreen = 44, Process = 229, Q = 81, R = 82, RightArrow = 39, RightWindows = 92, S = 83, Select = 41, Separator = 108, Sleep = 95, Spacebar = 32, Subtract = 109, T = 84, Tab = 9, U = 85, UpArrow = 38, V = 86, VolumeDown = 174, VolumeMute = 173, VolumeUp = 175, W = 87, X = 88, Y = 89, Z = 90, Zoom = 251, } public readonly partial struct ConsoleKeyInfo { private readonly int _dummy; public ConsoleKeyInfo(char keyChar, System.ConsoleKey key, bool shift, bool alt, bool control) { throw null; } public System.ConsoleKey Key { get { throw null; } } public char KeyChar { get { throw null; } } public System.ConsoleModifiers Modifiers { get { throw null; } } public bool Equals(System.ConsoleKeyInfo obj) { throw null; } public override bool Equals(object value) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; } public static bool operator !=(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; } } [System.FlagsAttribute] public enum ConsoleModifiers { Alt = 1, Control = 4, Shift = 2, } public enum ConsoleSpecialKey { ControlBreak = 1, ControlC = 0, } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { // Struct sizes needed for some custom marshaling. internal static readonly int s_controlDataSize = Marshal.SizeOf<Interop.Winsock.ControlData>(); internal static readonly int s_controlDataIPv6Size = Marshal.SizeOf<Interop.Winsock.ControlDataIPv6>(); internal static readonly int s_wsaMsgSize = Marshal.SizeOf<Interop.Winsock.WSAMsg>(); // Buffer,Offset,Count property variables. private WSABuffer _wsaBuffer; private IntPtr _ptrSingleBuffer; // BufferList property variables. private WSABuffer[] _wsaBufferArray; private bool _bufferListChanged; // Internal buffers for WSARecvMsg private byte[] _wsaMessageBuffer; private GCHandle _wsaMessageBufferGCHandle; private IntPtr _ptrWSAMessageBuffer; private byte[] _controlBuffer; private GCHandle _controlBufferGCHandle; private IntPtr _ptrControlBuffer; private WSABuffer[] _wsaRecvMsgWSABufferArray; private GCHandle _wsaRecvMsgWSABufferArrayGCHandle; private IntPtr _ptrWSARecvMsgWSABufferArray; // Internal buffer for AcceptEx when Buffer not supplied. private IntPtr _ptrAcceptBuffer; // Internal SocketAddress buffer private GCHandle _socketAddressGCHandle; private Internals.SocketAddress _pinnedSocketAddress; private IntPtr _ptrSocketAddressBuffer; private IntPtr _ptrSocketAddressBufferSize; // SendPacketsElements property variables. private SendPacketsElement[] _sendPacketsElementsInternal; private Interop.Winsock.TransmitPacketsElement[] _sendPacketsDescriptor; private int _sendPacketsElementsFileCount; private int _sendPacketsElementsBufferCount; // Internal variables for SendPackets private FileStream[] _sendPacketsFileStreams; private SafeHandle[] _sendPacketsFileHandles; private IntPtr _ptrSendPacketsDescriptor; // Overlapped object related variables. private SafeNativeOverlapped _ptrNativeOverlapped; private PreAllocatedOverlapped _preAllocatedOverlapped; private object[] _objectsToPin; private enum PinState { None = 0, NoBuffer, SingleAcceptBuffer, SingleBuffer, MultipleBuffer, SendPackets } private PinState _pinState; private byte[] _pinnedAcceptBuffer; private byte[] _pinnedSingleBuffer; private int _pinnedSingleBufferOffset; private int _pinnedSingleBufferCount; internal int? SendPacketsDescriptorCount { get { return _sendPacketsDescriptor == null ? null : (int?)_sendPacketsDescriptor.Length; } } private void InitializeInternals() { // Zero tells TransmitPackets to select a default send size. _sendPacketsSendSize = 0; } private void FreeInternals(bool calledFromFinalizer) { // Free native overlapped data. FreeOverlapped(calledFromFinalizer); } private void SetupSingleBuffer() { CheckPinSingleBuffer(true); } private void SetupMultipleBuffers() { _bufferListChanged = true; CheckPinMultipleBuffers(); } private void SetupSendPacketsElements() { _sendPacketsElementsInternal = null; } private void InnerComplete() { CompleteIOCPOperation(); } private unsafe void PrepareIOCPOperation() { Debug.Assert(_currentSocket != null, "_currentSocket is null"); Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null"); Debug.Assert(!_currentSocket.SafeHandle.IsInvalid, "_currentSocket.SafeHandle is invalid"); ThreadPoolBoundHandle boundHandle = _currentSocket.SafeHandle.GetOrAllocateThreadPoolBoundHandle(); NativeOverlapped* overlapped = null; if (_preAllocatedOverlapped != null) { overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::boundHandle#" + LoggingHash.HashString(boundHandle) + "::AllocateNativeOverlapped(m_PreAllocatedOverlapped=" + LoggingHash.HashString(_preAllocatedOverlapped) + "). Returned = " + ((IntPtr)overlapped).ToString("x")); } } else { overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::boundHandle#" + LoggingHash.HashString(boundHandle) + "::AllocateNativeOverlapped(pinData=null)" + "). Returned = " + ((IntPtr)overlapped).ToString("x")); } } Debug.Assert(overlapped != null, "NativeOverlapped is null."); _ptrNativeOverlapped = new SafeNativeOverlapped(_currentSocket.SafeHandle, overlapped); } private void CompleteIOCPOperation() { // TODO: Optimization to remove callbacks if the operations are completed synchronously: // Use SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS). // If SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) is not set on this handle // it is guaranteed that the IOCP operation will be completed in the callback even if Socket.Success was // returned by the Win32 API. // Required to allow another IOCP operation for the same handle. if (_ptrNativeOverlapped != null) { _ptrNativeOverlapped.Dispose(); _ptrNativeOverlapped = null; } } private void InnerStartOperationAccept(bool userSuppliedBuffer) { if (!userSuppliedBuffer) { CheckPinSingleBuffer(false); } } internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = SocketError.Success; if (!socket.AcceptEx( handle, acceptHandle, (_ptrSingleBuffer != IntPtr.Zero) ? _ptrSingleBuffer : _ptrAcceptBuffer, (_ptrSingleBuffer != IntPtr.Zero) ? Count - _acceptAddressBufferCount : 0, _acceptAddressBufferCount / 2, _acceptAddressBufferCount / 2, out bytesTransferred, _ptrNativeOverlapped)) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationConnect() { // ConnectEx uses a sockaddr buffer containing he remote address to which to connect. // It can also optionally take a single buffer of data to send after the connection is complete. // // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. // The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin. PinSocketAddressBuffer(); CheckPinNoBuffer(); } internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = SocketError.Success; if (!socket.ConnectEx( handle, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrSingleBuffer, Count, out bytesTransferred, _ptrNativeOverlapped)) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationDisconnect() { CheckPinNoBuffer(); } private void InnerStartOperationReceive() { // WWSARecv uses a WSABuffer array describing buffers of data to send. // // Single and multiple buffers are handled differently so as to optimize // performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. } internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { PrepareIOCPOperation(); flags = _socketFlags; SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSARecv( handle, ref _wsaBuffer, 1, out bytesTransferred, ref flags, _ptrNativeOverlapped, IntPtr.Zero); } else { // Multi buffer case. socketError = Interop.Winsock.WSARecv( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, ref flags, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationReceiveFrom() { // WSARecvFrom uses e a WSABuffer array describing buffers in which to // receive data and from which to send data respectively. Single and multiple buffers // are handled differently so as to optimize performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. // // WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received. // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); } internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { PrepareIOCPOperation(); flags = _socketFlags; SocketError socketError; if (_buffer != null) { socketError = Interop.Winsock.WSARecvFrom( handle, ref _wsaBuffer, 1, out bytesTransferred, ref flags, _ptrSocketAddressBuffer, _ptrSocketAddressBufferSize, _ptrNativeOverlapped, IntPtr.Zero); } else { socketError = Interop.Winsock.WSARecvFrom( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, ref flags, _ptrSocketAddressBuffer, _ptrSocketAddressBufferSize, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationReceiveMessageFrom() { // WSARecvMsg uses a WSAMsg descriptor. // The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a sockaddr. // The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a WSABuffer array describing data buffers. // WSAMsg also contains a single WSABuffer describing a control buffer. PinSocketAddressBuffer(); // Create and pin a WSAMessageBuffer if none already. if (_wsaMessageBuffer == null) { _wsaMessageBuffer = new byte[s_wsaMsgSize]; _wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned); _ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0); } // Create and pin an appropriately sized control buffer if none already IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null); bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6; if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataSize)) { if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); } _controlBuffer = new byte[s_controlDataSize]; } else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataIPv6Size)) { if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); } _controlBuffer = new byte[s_controlDataIPv6Size]; } if (!_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned); _ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0); } // If single buffer we need a pinned 1 element WSABuffer. if (_buffer != null) { if (_wsaRecvMsgWSABufferArray == null) { _wsaRecvMsgWSABufferArray = new WSABuffer[1]; } _wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer; _wsaRecvMsgWSABufferArray[0].Length = _count; _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned); _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0); } else { // Just pin the multi-buffer WSABuffer. _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned); _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0); } // Fill in WSAMessageBuffer. unsafe { Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ; pMessage->socketAddress = _ptrSocketAddressBuffer; pMessage->addressLength = (uint)_socketAddress.Size; pMessage->buffers = _ptrWSARecvMsgWSABufferArray; if (_buffer != null) { pMessage->count = (uint)1; } else { pMessage->count = (uint)_wsaBufferArray.Length; } if (_controlBuffer != null) { pMessage->controlBuffer.Pointer = _ptrControlBuffer; pMessage->controlBuffer.Length = _controlBuffer.Length; } pMessage->flags = _socketFlags; } } internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = socket.WSARecvMsg( handle, _ptrWSAMessageBuffer, out bytesTransferred, _ptrNativeOverlapped, IntPtr.Zero); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationSend() { // WSASend uses a WSABuffer array describing buffers of data to send. // // Single and multiple buffers are handled differently so as to optimize // performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. } internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSASend( handle, ref _wsaBuffer, 1, out bytesTransferred, _socketFlags, _ptrNativeOverlapped, IntPtr.Zero); } else { // Multi buffer case. socketError = Interop.Winsock.WSASend( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, _socketFlags, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationSendPackets() { // Prevent mutithreaded manipulation of the list. if (_sendPacketsElements != null) { _sendPacketsElementsInternal = (SendPacketsElement[])_sendPacketsElements.Clone(); } // TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as // descriptors for buffers and files to be sent. It also takes a send size // and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle. // This function basically opens the files to get the file handles, pins down any buffers // specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed // to TransmitPackets. // Scan the elements to count files and buffers. _sendPacketsElementsFileCount = 0; _sendPacketsElementsBufferCount = 0; Debug.Assert(_sendPacketsElementsInternal != null); foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._filePath != null) { _sendPacketsElementsFileCount++; } if (spe._buffer != null && spe._count > 0) { _sendPacketsElementsBufferCount++; } } } // Attempt to open the files if any were given. if (_sendPacketsElementsFileCount > 0) { // Create arrays for streams and handles. _sendPacketsFileStreams = new FileStream[_sendPacketsElementsFileCount]; _sendPacketsFileHandles = new SafeHandle[_sendPacketsElementsFileCount]; // Loop through the elements attempting to open each files and get its handle. int index = 0; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null && spe._filePath != null) { Exception fileStreamException = null; try { // Create a FileStream to open the file. _sendPacketsFileStreams[index] = new FileStream(spe._filePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { // Save the exception to throw after closing any previous successful file opens. fileStreamException = ex; } if (fileStreamException != null) { // Got an exception opening a file - do some cleanup then throw. for (int i = 0; i < _sendPacketsElementsFileCount; i++) { // Drop handles. _sendPacketsFileHandles[i] = null; // Close any open streams. if (_sendPacketsFileStreams[i] != null) { _sendPacketsFileStreams[i].Dispose(); _sendPacketsFileStreams[i] = null; } } throw fileStreamException; } // Get the file handle from the stream. _sendPacketsFileHandles[index] = _sendPacketsFileStreams[index].SafeFileHandle; index++; } } } CheckPinSendPackets(); } internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle) { PrepareIOCPOperation(); bool result = socket.TransmitPackets( handle, _ptrSendPacketsDescriptor, _sendPacketsDescriptor.Length, _sendPacketsSendSize, _ptrNativeOverlapped); return result ? SocketError.Success : SocketPal.GetLastSocketError(); } private void InnerStartOperationSendTo() { // WSASendTo uses a WSABuffer array describing buffers in which to // receive data and from which to send data respectively. Single and multiple buffers // are handled differently so as to optimize performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. // // WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received. // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); } internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSASendTo( handle, ref _wsaBuffer, 1, out bytesTransferred, _socketFlags, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrNativeOverlapped, IntPtr.Zero); } else { socketError = Interop.Winsock.WSASendTo( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, _socketFlags, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } // Ensures Overlapped object exists for operations that need no data buffer. private void CheckPinNoBuffer() { // PreAllocatedOverlapped will be reused. if (_pinState == PinState.None) { SetupOverlappedSingle(true); } } // Maintains pinned state of single buffer. private void CheckPinSingleBuffer(bool pinUsersBuffer) { if (pinUsersBuffer) { // Using app supplied buffer. if (_buffer == null) { // No user buffer is set so unpin any existing single buffer pinning. if (_pinState == PinState.SingleBuffer) { FreeOverlapped(false); } } else { if (_pinState == PinState.SingleBuffer && _pinnedSingleBuffer == _buffer) { // This buffer is already pinned - update if offset or count has changed. if (_offset != _pinnedSingleBufferOffset) { _pinnedSingleBufferOffset = _offset; _ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset); _wsaBuffer.Pointer = _ptrSingleBuffer; } if (_count != _pinnedSingleBufferCount) { _pinnedSingleBufferCount = _count; _wsaBuffer.Length = _count; } } else { FreeOverlapped(false); SetupOverlappedSingle(true); } } } else { // Using internal accept buffer. if (!(_pinState == PinState.SingleAcceptBuffer) || !(_pinnedSingleBuffer == _acceptBuffer)) { // Not already pinned - so pin it. FreeOverlapped(false); SetupOverlappedSingle(false); } } } // Ensures Overlapped object exists with appropriate multiple buffers pinned. private void CheckPinMultipleBuffers() { if (_bufferList == null) { // No buffer list is set so unpin any existing multiple buffer pinning. if (_pinState == PinState.MultipleBuffer) { FreeOverlapped(false); } } else { if (!(_pinState == PinState.MultipleBuffer) || _bufferListChanged) { // Need to setup a new Overlapped. _bufferListChanged = false; FreeOverlapped(false); try { SetupOverlappedMultiple(); } catch (Exception) { FreeOverlapped(false); throw; } } } } // Ensures Overlapped object exists with appropriate buffers pinned. private void CheckPinSendPackets() { if (_pinState != PinState.None) { FreeOverlapped(false); } SetupOverlappedSendPackets(); } // Ensures appropriate SocketAddress buffer is pinned. private void PinSocketAddressBuffer() { // Check if already pinned. if (_pinnedSocketAddress == _socketAddress) { return; } // Unpin any existing. if (_socketAddressGCHandle.IsAllocated) { _socketAddressGCHandle.Free(); } // Pin down the new one. _socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned); _socketAddress.CopyAddressSizeIntoBuffer(); _ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0); _ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset()); _pinnedSocketAddress = _socketAddress; } // Cleans up any existing Overlapped object and related state variables. private void FreeOverlapped(bool checkForShutdown) { if (!checkForShutdown || !Environment.HasShutdownStarted) { // Free the overlapped object. if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid) { _ptrNativeOverlapped.Dispose(); _ptrNativeOverlapped = null; } // Free the preallocated overlapped object. This in turn will unpin // any pinned buffers. if (_preAllocatedOverlapped != null) { _preAllocatedOverlapped.Dispose(); _preAllocatedOverlapped = null; _pinState = PinState.None; _pinnedAcceptBuffer = null; _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; } // Free any allocated GCHandles. if (_socketAddressGCHandle.IsAllocated) { _socketAddressGCHandle.Free(); _pinnedSocketAddress = null; } if (_wsaMessageBufferGCHandle.IsAllocated) { _wsaMessageBufferGCHandle.Free(); _ptrWSAMessageBuffer = IntPtr.Zero; } if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated) { _wsaRecvMsgWSABufferArrayGCHandle.Free(); _ptrWSARecvMsgWSABufferArray = IntPtr.Zero; } if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); _ptrControlBuffer = IntPtr.Zero; } } } // Sets up an Overlapped object with either _buffer or _acceptBuffer pinned. unsafe private void SetupOverlappedSingle(bool pinSingleBuffer) { // Pin buffer, get native pointers, and fill in WSABuffer descriptor. if (pinSingleBuffer) { if (_buffer != null) { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = _buffer; _pinnedSingleBufferOffset = _offset; _pinnedSingleBufferCount = _count; _ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset); _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.SingleBuffer; } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; _ptrSingleBuffer = IntPtr.Zero; _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.NoBuffer; } } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedAcceptBuffer = _acceptBuffer; _ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0); _ptrSingleBuffer = IntPtr.Zero; _pinState = PinState.SingleAcceptBuffer; } } // Sets up an Overlapped object with with multiple buffers pinned. unsafe private void SetupOverlappedMultiple() { ArraySegment<byte>[] tempList = new ArraySegment<byte>[_bufferList.Count]; _bufferList.CopyTo(tempList, 0); // Number of things to pin is number of buffers. // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != tempList.Length)) { _objectsToPin = new object[tempList.Length]; } // Fill in object array. for (int i = 0; i < (tempList.Length); i++) { _objectsToPin[i] = tempList[i].Array; } if (_wsaBufferArray == null || _wsaBufferArray.Length != tempList.Length) { _wsaBufferArray = new WSABuffer[tempList.Length]; } // Pin buffers and fill in WSABuffer descriptor pointers and lengths. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." + LoggingHash.HashString(_preAllocatedOverlapped)); } for (int i = 0; i < tempList.Length; i++) { ArraySegment<byte> localCopy = tempList[i]; RangeValidationHelpers.ValidateSegment(localCopy); _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset); _wsaBufferArray[i].Length = localCopy.Count; } _pinState = PinState.MultipleBuffer; } // Sets up an Overlapped object for SendPacketsAsync. unsafe private void SetupOverlappedSendPackets() { int index; // Alloc native descriptor. _sendPacketsDescriptor = new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount]; // Number of things to pin is number of buffers + 1 (native descriptor). // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1)) { _objectsToPin = new object[_sendPacketsElementsBufferCount + 1]; } // Fill in objects to pin array. Native descriptor buffer first and then user specified buffers. _objectsToPin[0] = _sendPacketsDescriptor; index = 1; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null && spe._buffer != null && spe._count > 0) { _objectsToPin[index] = spe._buffer; index++; } } // Pin buffers. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " + LoggingHash.HashString(_preAllocatedOverlapped)); } // Get pointer to native descriptor. _ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0); // Fill in native descriptor. int descriptorIndex = 0; int fileIndex = 0; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._buffer != null && spe._count > 0) { // This element is a buffer. _sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset); _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; descriptorIndex++; } else if (spe._filePath != null) { // This element is a file. _sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle(); _sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset; _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; fileIndex++; descriptorIndex++; } } } _pinState = PinState.SendPackets; } internal void LogBuffer(int size) { switch (_pinState) { case PinState.SingleAcceptBuffer: SocketsEventSource.Dump(_acceptBuffer, 0, size); break; case PinState.SingleBuffer: SocketsEventSource.Dump(_buffer, _offset, size); break; case PinState.MultipleBuffer: foreach (WSABuffer wsaBuffer in _wsaBufferArray) { SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size)); if ((size -= wsaBuffer.Length) <= 0) { break; } } break; default: break; } } internal void LogSendPacketsBuffers(int size) { foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._buffer != null && spe._count > 0) { // This element is a buffer. SocketsEventSource.Dump(spe._buffer, spe._offset, Math.Min(spe._count, size)); } else if (spe._filePath != null) { // This element is a file. SocketsEventSource.Log.NotLoggedFile(spe._filePath, LoggingHash.HashInt(_currentSocket), _completedOperation); } } } } private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress) { SocketError socketError; IntPtr localAddr; int localAddrLength; IntPtr remoteAddr; try { _currentSocket.GetAcceptExSockaddrs( _ptrSingleBuffer != IntPtr.Zero ? _ptrSingleBuffer : _ptrAcceptBuffer, _count != 0 ? _count - _acceptAddressBufferCount : 0, _acceptAddressBufferCount / 2, _acceptAddressBufferCount / 2, out localAddr, out localAddrLength, out remoteAddr, out remoteSocketAddress.InternalSize ); Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size); // Set the socket context. IntPtr handle = _currentSocket.SafeHandle.DangerousGetHandle(); socketError = Interop.Winsock.setsockopt( _acceptSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, ref handle, Marshal.SizeOf(handle)); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } } catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } return socketError; } private SocketError FinishOperationConnect() { SocketError socketError; // Update the socket context. try { socketError = Interop.Winsock.setsockopt( _currentSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateConnectContext, null, 0); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } } catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } return socketError; } private unsafe int GetSocketAddressSize() { return *(int*)_ptrSocketAddressBufferSize; } private unsafe void FinishOperationReceiveMessageFrom() { IPAddress address = null; Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0); if (_controlBuffer.Length == s_controlDataSize) { // IPv4. Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(PtrMessage->controlBuffer.Pointer); if (controlData.length != UIntPtr.Zero) { address = new IPAddress((long)controlData.address); } _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index); } else if (_controlBuffer.Length == s_controlDataIPv6Size) { // IPv6. Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(PtrMessage->controlBuffer.Pointer); if (controlData.length != UIntPtr.Zero) { address = new IPAddress(controlData.address); } _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index); } else { // Other. _receiveMessageFromPacketInfo = new IPPacketInformation(); } } private void FinishOperationSendPackets() { // Close the files if open. if (_sendPacketsFileStreams != null) { for (int i = 0; i < _sendPacketsElementsFileCount; i++) { // Drop handles. _sendPacketsFileHandles[i] = null; // Close any open streams. if (_sendPacketsFileStreams[i] != null) { _sendPacketsFileStreams[i].Dispose(); _sendPacketsFileStreams[i] = null; } } } _sendPacketsFileStreams = null; _sendPacketsFileHandles = null; } private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.CompletionPort); using (GlobalLog.SetThreadKind(ThreadKinds.System)) { GlobalLog.Enter( "CompletionPortCallback", "errorCode: " + errorCode + ", numBytes: " + numBytes + ", overlapped#" + ((IntPtr)nativeOverlapped).ToString("x")); #endif SocketFlags socketFlags = SocketFlags.None; SocketError socketError = (SocketError)errorCode; // This is the same NativeOverlapped* as we already have a SafeHandle for, re-use the original. Debug.Assert((IntPtr)nativeOverlapped == _ptrNativeOverlapped.DangerousGetHandle(), "Handle mismatch"); if (socketError == SocketError.Success) { FinishOperationSuccess(socketError, (int)numBytes, socketFlags); } else { if (socketError != SocketError.OperationAborted) { if (_currentSocket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // The Async IO completed with a failure. // here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error. bool success = Interop.Winsock.WSAGetOverlappedResult( _currentSocket.SafeHandle, _ptrNativeOverlapped, out numBytes, false, out socketFlags); socketError = SocketPal.GetLastSocketError(); } catch { // _currentSocket.CleanedUp check above does not always work since this code is subject to race conditions. socketError = SocketError.OperationAborted; } } } FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags); } #if DEBUG GlobalLog.Leave("CompletionPortCallback"); } #endif } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Tokens { using System; using System.Collections.Generic; using System.Globalization; using System.IdentityModel; using System.IdentityModel.Selectors; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using System.Xml; using HexBinary = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary; using KeyIdentifierClauseEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.KeyIdentifierClauseEntry; using StrEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.StrEntry; using TokenEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.TokenEntry; class WSSecurityJan2004 : SecurityTokenSerializer.SerializerEntries { KeyInfoSerializer securityTokenSerializer; public WSSecurityJan2004(KeyInfoSerializer securityTokenSerializer) { this.securityTokenSerializer = securityTokenSerializer; } public KeyInfoSerializer SecurityTokenSerializer { get { return this.securityTokenSerializer; } } public override void PopulateKeyIdentifierClauseEntries(IList<KeyIdentifierClauseEntry> clauseEntries) { List<StrEntry> strEntries = new List<StrEntry>(); this.securityTokenSerializer.PopulateStrEntries(strEntries); SecurityTokenReferenceJan2004ClauseEntry strClause = new SecurityTokenReferenceJan2004ClauseEntry(this.securityTokenSerializer.EmitBspRequiredAttributes, strEntries); clauseEntries.Add(strClause); } protected void PopulateJan2004StrEntries(IList<StrEntry> strEntries) { strEntries.Add(new LocalReferenceStrEntry(this.securityTokenSerializer.EmitBspRequiredAttributes, this.securityTokenSerializer)); strEntries.Add(new KerberosHashStrEntry(this.securityTokenSerializer.EmitBspRequiredAttributes)); strEntries.Add(new X509SkiStrEntry(this.securityTokenSerializer.EmitBspRequiredAttributes)); strEntries.Add(new X509IssuerSerialStrEntry()); strEntries.Add(new RelDirectStrEntry()); strEntries.Add(new SamlJan2004KeyIdentifierStrEntry()); strEntries.Add(new Saml2Jan2004KeyIdentifierStrEntry()); } public override void PopulateStrEntries(IList<StrEntry> strEntries) { PopulateJan2004StrEntries(strEntries); } protected void PopulateJan2004TokenEntries(IList<TokenEntry> tokenEntryList) { tokenEntryList.Add(new GenericXmlTokenEntry()); tokenEntryList.Add(new UserNamePasswordTokenEntry()); tokenEntryList.Add(new KerberosTokenEntry()); tokenEntryList.Add(new X509TokenEntry()); } public override void PopulateTokenEntries(IList<TokenEntry> tokenEntryList) { PopulateJan2004TokenEntries(tokenEntryList); tokenEntryList.Add(new SamlTokenEntry()); tokenEntryList.Add(new WrappedKeyTokenEntry()); } internal abstract class BinaryTokenEntry : TokenEntry { internal static readonly XmlDictionaryString ElementName = XD.SecurityJan2004Dictionary.BinarySecurityToken; internal static readonly XmlDictionaryString EncodingTypeAttribute = XD.SecurityJan2004Dictionary.EncodingType; internal const string EncodingTypeAttributeString = SecurityJan2004Strings.EncodingType; internal const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; internal const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary; internal static readonly XmlDictionaryString ValueTypeAttribute = XD.SecurityJan2004Dictionary.ValueType; string[] valueTypeUris = null; protected BinaryTokenEntry(string valueTypeUri) { this.valueTypeUris = new string[1]; this.valueTypeUris[0] = valueTypeUri; } protected BinaryTokenEntry(string[] valueTypeUris) { if (valueTypeUris == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris"); this.valueTypeUris = new string[valueTypeUris.GetLength(0)]; for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i) this.valueTypeUris[i] = valueTypeUris[i]; } protected override XmlDictionaryString LocalName { get { return ElementName; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } public override string TokenTypeUri { get { return this.valueTypeUris[0]; } } protected override string ValueTypeUri { get { return this.valueTypeUris[0]; } } public override bool SupportsTokenTypeUri(string tokenTypeUri) { for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i) { if (this.valueTypeUris[i] == tokenTypeUri) return true; } return false; } } class GenericXmlTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return null; } } protected override XmlDictionaryString NamespaceUri { get { return null; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(GenericXmlSecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } class KerberosTokenEntry : BinaryTokenEntry { public KerberosTokenEntry() : base(new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 }) { } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(KerberosReceiverSecurityToken), typeof(KerberosRequestorSecurityToken) }; } } protected class SamlTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SamlAssertion; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.SamlUri; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(SamlSecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } class UserNamePasswordTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.UserNameTokenElement; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(UserNameSecurityToken) }; } public override string TokenTypeUri { get { return SecurityJan2004Strings.UPTokenType; } } protected override string ValueTypeUri { get { return null; } } } protected class WrappedKeyTokenEntry : TokenEntry { protected override XmlDictionaryString LocalName { get { return EncryptedKey.ElementName; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlEncryptionDictionary.Namespace; } } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(WrappedKeySecurityToken) }; } public override string TokenTypeUri { get { return null; } } protected override string ValueTypeUri { get { return null; } } } protected class X509TokenEntry : BinaryTokenEntry { internal const string ValueTypeAbsoluteUri = SecurityJan2004Strings.X509TokenType; public X509TokenEntry() : base(ValueTypeAbsoluteUri) { } protected override Type[] GetTokenTypesCore() { return new Type[] { typeof(X509SecurityToken), typeof(X509WindowsSecurityToken) }; } } protected class SecurityTokenReferenceJan2004ClauseEntry : KeyIdentifierClauseEntry { const int DefaultDerivedKeyLength = 32; bool emitBspRequiredAttributes; IList<StrEntry> strEntries; public SecurityTokenReferenceJan2004ClauseEntry(bool emitBspRequiredAttributes, IList<StrEntry> strEntries) { this.emitBspRequiredAttributes = emitBspRequiredAttributes; this.strEntries = strEntries; } protected bool EmitBspRequiredAttributes { get { return this.emitBspRequiredAttributes; } } protected IList<StrEntry> StrEntries { get { return this.strEntries; } } protected override XmlDictionaryString LocalName { get { return XD.SecurityJan2004Dictionary.SecurityTokenReference; } } protected override XmlDictionaryString NamespaceUri { get { return XD.SecurityJan2004Dictionary.Namespace; } } protected virtual string ReadTokenType(XmlDictionaryReader reader) { return null; } public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) { byte[] nonce = null; int length = 0; if (reader.IsStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri)) { string nonceString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Nonce, XD.SecureConversationFeb2005Dictionary.Namespace); if (nonceString != null) { nonce = Convert.FromBase64String(nonceString); } string lengthString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Length, XD.SecureConversationFeb2005Dictionary.Namespace); if (lengthString != null) { length = Convert.ToInt32(lengthString, CultureInfo.InvariantCulture); } else { length = DefaultDerivedKeyLength; } } string tokenType = ReadTokenType(reader); string strId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); reader.ReadStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri); SecurityKeyIdentifierClause clause = null; for (int i = 0; i < this.strEntries.Count; ++i) { if (this.strEntries[i].CanReadClause(reader, tokenType)) { clause = this.strEntries[i].ReadClause(reader, nonce, length, tokenType); break; } } if (clause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CannotReadKeyIdentifierClause, reader.LocalName, reader.NamespaceURI))); } if (!string.IsNullOrEmpty(strId)) { clause.Id = strId; } reader.ReadEndElement(); return clause; } public override bool SupportsCore(SecurityKeyIdentifierClause keyIdentifierClause) { for (int i = 0; i < this.strEntries.Count; ++i) { if (this.strEntries[i].SupportsCore(keyIdentifierClause)) { return true; } } return false; } public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause) { for (int i = 0; i < this.strEntries.Count; ++i) { if (this.strEntries[i].SupportsCore(keyIdentifierClause)) { writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.SecurityTokenReference, XD.SecurityJan2004Dictionary.Namespace); this.strEntries[i].WriteContent(writer, keyIdentifierClause); writer.WriteEndElement(); return; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StandardsManagerCannotWriteObject, keyIdentifierClause.GetType()))); } } protected abstract class KeyIdentifierStrEntry : StrEntry { bool emitBspRequiredAttributes; protected const string EncodingTypeValueBase64Binary = SecurityJan2004Strings.EncodingTypeValueBase64Binary; protected const string EncodingTypeValueHexBinary = SecurityJan2004Strings.EncodingTypeValueHexBinary; protected const string EncodingTypeValueText = SecurityJan2004Strings.EncodingTypeValueText; protected abstract Type ClauseType { get; } protected virtual string DefaultEncodingType { get { return EncodingTypeValueBase64Binary; } } public abstract Type TokenType { get; } protected abstract string ValueTypeUri { get; } protected bool EmitBspRequiredAttributes { get { return this.emitBspRequiredAttributes; } } protected KeyIdentifierStrEntry(bool emitBspRequiredAttributes) { this.emitBspRequiredAttributes = emitBspRequiredAttributes; } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return (ValueTypeUri == valueType); } return false; } protected abstract SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength); public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return this.TokenType; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { string encodingType = reader.GetAttribute(XD.SecurityJan2004Dictionary.EncodingType, null); if (encodingType == null) { encodingType = DefaultEncodingType; } reader.ReadStartElement(); byte[] bytes; if (encodingType == EncodingTypeValueBase64Binary) { bytes = reader.ReadContentAsBase64(); } else if (encodingType == EncodingTypeValueHexBinary) { bytes = HexBinary.Parse(reader.ReadContentAsString()).Value; } else if (encodingType == EncodingTypeValueText) { bytes = new UTF8Encoding().GetBytes(reader.ReadContentAsString()); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SR.GetString(SR.UnknownEncodingInKeyIdentifier))); } reader.ReadEndElement(); return CreateClause(bytes, derivationNonce, derivationLength); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { return ClauseType.IsAssignableFrom(clause.GetType()); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace); writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, ValueTypeUri); if (this.emitBspRequiredAttributes) { // Emit the encodingType attribute. writer.WriteAttributeString(XD.SecurityJan2004Dictionary.EncodingType, null, DefaultEncodingType); } string encoding = DefaultEncodingType; BinaryKeyIdentifierClause binaryClause = clause as BinaryKeyIdentifierClause; byte[] keyIdentifier = binaryClause.GetBuffer(); if (encoding == EncodingTypeValueBase64Binary) { writer.WriteBase64(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueHexBinary) { writer.WriteBinHex(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueText) { writer.WriteString(new UTF8Encoding().GetString(keyIdentifier, 0, keyIdentifier.Length)); } writer.WriteEndElement(); } } protected class KerberosHashStrEntry : KeyIdentifierStrEntry { protected override Type ClauseType { get { return typeof(KerberosTicketHashKeyIdentifierClause); } } public override Type TokenType { get { return typeof(KerberosRequestorSecurityToken); } } protected override string ValueTypeUri { get { return SecurityJan2004Strings.KerberosHashValueType; } } public KerberosHashStrEntry(bool emitBspRequiredAttributes) : base(emitBspRequiredAttributes) { } protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength) { return new KerberosTicketHashKeyIdentifierClause(bytes, derivationNonce, derivationLength); } public override string GetTokenTypeUri() { return XD.SecurityJan2004Dictionary.KerberosTokenTypeGSS.Value; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace); writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, ValueTypeUri); KerberosTicketHashKeyIdentifierClause binaryClause = clause as KerberosTicketHashKeyIdentifierClause; if (this.EmitBspRequiredAttributes) { // Emit the encodingType attribute. writer.WriteAttributeString(XD.SecurityJan2004Dictionary.EncodingType, null, DefaultEncodingType); } string encoding = DefaultEncodingType; byte[] keyIdentifier = binaryClause.GetBuffer(); if (encoding == EncodingTypeValueBase64Binary) { writer.WriteBase64(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueHexBinary) { writer.WriteBinHex(keyIdentifier, 0, keyIdentifier.Length); } else if (encoding == EncodingTypeValueText) { writer.WriteString(new UTF8Encoding().GetString(keyIdentifier, 0, keyIdentifier.Length)); } writer.WriteEndElement(); } } protected class X509SkiStrEntry : KeyIdentifierStrEntry { protected override Type ClauseType { get { return typeof(X509SubjectKeyIdentifierClause); } } public override Type TokenType { get { return typeof(X509SecurityToken); } } protected override string ValueTypeUri { get { return SecurityJan2004Strings.X509SKIValueType; } } public X509SkiStrEntry(bool emitBspRequiredAttributes) : base(emitBspRequiredAttributes) { } protected override SecurityKeyIdentifierClause CreateClause(byte[] bytes, byte[] derivationNonce, int derivationLength) { return new X509SubjectKeyIdentifierClause(bytes); } public override string GetTokenTypeUri() { return SecurityJan2004Strings.X509TokenType; } } protected class LocalReferenceStrEntry : StrEntry { bool emitBspRequiredAttributes; KeyInfoSerializer tokenSerializer; public LocalReferenceStrEntry(bool emitBspRequiredAttributes, KeyInfoSerializer tokenSerializer) { this.emitBspRequiredAttributes = emitBspRequiredAttributes; this.tokenSerializer = tokenSerializer; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { LocalIdKeyIdentifierClause localClause = clause as LocalIdKeyIdentifierClause; return localClause.OwnerType; } public string GetLocalTokenTypeUri(SecurityKeyIdentifierClause clause) { Type tokenType = GetTokenType(clause); return this.tokenSerializer.GetTokenTypeUri(tokenType); } public override string GetTokenTypeUri() { return null; } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace)) { string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); if (uri != null && uri.Length > 0 && uri[0] == '#') { return true; } } return false; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { string uri = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); string tokenTypeUri = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); Type[] tokenTypes = null; if (tokenTypeUri != null) { tokenTypes = this.tokenSerializer.GetTokenTypes(tokenTypeUri); } SecurityKeyIdentifierClause clause = new LocalIdKeyIdentifierClause(uri.Substring(1), derivationNonce, derivationLength, tokenTypes); if (reader.IsEmptyElement) { reader.Read(); } else { reader.ReadStartElement(); reader.ReadEndElement(); } return clause; } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { return clause is LocalIdKeyIdentifierClause; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { LocalIdKeyIdentifierClause localIdClause = clause as LocalIdKeyIdentifierClause; writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace); if (this.emitBspRequiredAttributes) { string tokenTypeUri = GetLocalTokenTypeUri(localIdClause); if (tokenTypeUri != null) { writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, tokenTypeUri); } } writer.WriteAttributeString(XD.SecurityJan2004Dictionary.URI, null, "#" + localIdClause.LocalId); writer.WriteEndElement(); } } protected class SamlJan2004KeyIdentifierStrEntry : StrEntry { protected virtual bool IsMatchingValueType(string valueType) { return (valueType == SecurityJan2004Strings.SamlAssertionIdValueType); } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri)) { return true; } else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return IsMatchingValueType(valueType); } return false; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return typeof(SamlSecurityToken); } public override string GetTokenTypeUri() { return XD.SecurityXXX2005Dictionary.SamlTokenType.Value; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) { bool readAuthorityBinding = false; bool readKeyIdentifier = false; string id = null; string valueType = null; string binding = null; string location = null; string authorityKind = null; while (reader.IsStartElement()) { if (reader.IsStartElement(XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri)) { if (readAuthorityBinding) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MultipleSamlAuthorityBindingsInReference))); } readAuthorityBinding = true; binding = reader.GetAttribute(XD.SamlDictionary.Binding, null); if (string.IsNullOrEmpty(binding)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.Binding.Value, XD.SamlDictionary.AuthorityBinding.Value))); } location = reader.GetAttribute(XD.SamlDictionary.Location, null); if (string.IsNullOrEmpty(location)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.Location.Value, XD.SamlDictionary.AuthorityBinding.Value))); } authorityKind = reader.GetAttribute(XD.SamlDictionary.AuthorityKind, null); if (string.IsNullOrEmpty(authorityKind)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.RequiredAttributeMissing, XD.SamlDictionary.AuthorityKind.Value, XD.SamlDictionary.AuthorityBinding.Value))); } if (reader.IsEmptyElement) { reader.Read(); } else { reader.ReadStartElement(); reader.ReadEndElement(); } } else if (reader.IsStartElement(XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace)) { if (readKeyIdentifier) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MultipleKeyIdentifiersInReference))); } readKeyIdentifier = true; valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); id = reader.ReadElementContentAsString(); } else { break; } } if (!readKeyIdentifier) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.DidNotFindKeyIdentifierInReference))); } return new SamlAssertionKeyIdentifierClause(id, derivationNone, derivationLength, valueType, tokenType, binding, location, authorityKind); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { if (typeof(SamlAssertionKeyIdentifierClause).IsAssignableFrom(clause.GetType())) { SamlAssertionKeyIdentifierClause samlclause = clause as SamlAssertionKeyIdentifierClause; if ((samlclause.TokenTypeUri == null) || (samlclause.TokenTypeUri == this.GetTokenTypeUri())) { return true; } } return false; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { SamlAssertionKeyIdentifierClause samlClause = clause as SamlAssertionKeyIdentifierClause; if (!string.IsNullOrEmpty(samlClause.Binding) || !string.IsNullOrEmpty(samlClause.Location) || !string.IsNullOrEmpty(samlClause.AuthorityKind)) { writer.WriteStartElement(XD.SamlDictionary.PreferredPrefix.Value, XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri); if (!string.IsNullOrEmpty(samlClause.Binding)) { writer.WriteAttributeString(XD.SamlDictionary.Binding, null, samlClause.Binding); } if (!string.IsNullOrEmpty(samlClause.Location)) { writer.WriteAttributeString(XD.SamlDictionary.Location, null, samlClause.Location); } if (!string.IsNullOrEmpty(samlClause.AuthorityKind)) { writer.WriteAttributeString(XD.SamlDictionary.AuthorityKind, null, samlClause.AuthorityKind); } writer.WriteEndElement(); } writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace); string valueType = string.IsNullOrEmpty(samlClause.ValueType) ? XD.SecurityJan2004Dictionary.SamlAssertionIdValueType.Value : samlClause.ValueType; writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, valueType); writer.WriteString(samlClause.AssertionId); writer.WriteEndElement(); } } class Saml2Jan2004KeyIdentifierStrEntry : SamlJan2004KeyIdentifierStrEntry { // handles SAML2.0 protected override bool IsMatchingValueType(string valueType) { return (valueType == XD.SecurityXXX2005Dictionary.Saml11AssertionValueType.Value); } public override string GetTokenTypeUri() { return XD.SecurityXXX2005Dictionary.Saml20TokenType.Value; } } protected class RelDirectStrEntry : StrEntry { public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { if (reader.IsStartElement(XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace)) { string valueType = reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null); return (valueType == SecurityJan2004Strings.RelAssertionValueType); } return false; } public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return null; } public override string GetTokenTypeUri() { return XD.SecurityJan2004Dictionary.RelAssertionValueType.Value; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNone, int derivationLength, string tokenType) { string assertionId = reader.GetAttribute(XD.SecurityJan2004Dictionary.URI, null); if (reader.IsEmptyElement) { reader.Read(); } else { reader.ReadStartElement(); reader.ReadEndElement(); } return new RelAssertionDirectKeyIdentifierClause(assertionId, derivationNone, derivationLength); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { return typeof(RelAssertionDirectKeyIdentifierClause).IsAssignableFrom(clause.GetType()); } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { RelAssertionDirectKeyIdentifierClause relClause = clause as RelAssertionDirectKeyIdentifierClause; writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.Reference, XD.SecurityJan2004Dictionary.Namespace); writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, SecurityJan2004Strings.RelAssertionValueType); writer.WriteAttributeString(XD.SecurityJan2004Dictionary.URI, null, relClause.AssertionId); writer.WriteEndElement(); } } protected class X509IssuerSerialStrEntry : StrEntry { public override Type GetTokenType(SecurityKeyIdentifierClause clause) { return typeof(X509SecurityToken); } public override bool CanReadClause(XmlDictionaryReader reader, string tokenType) { return reader.IsStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); } public override string GetTokenTypeUri() { return SecurityJan2004Strings.X509TokenType; } public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType) { reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace); reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace); string issuerName = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadStartElement(XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace); string serialNumber = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadEndElement(); reader.ReadEndElement(); return new X509IssuerSerialKeyIdentifierClause(issuerName, serialNumber); } public override bool SupportsCore(SecurityKeyIdentifierClause clause) { return clause is X509IssuerSerialKeyIdentifierClause; } public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause) { X509IssuerSerialKeyIdentifierClause issuerClause = clause as X509IssuerSerialKeyIdentifierClause; writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace); writer.WriteElementString(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace, issuerClause.IssuerName); writer.WriteElementString(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace, issuerClause.IssuerSerialNumber); writer.WriteEndElement(); writer.WriteEndElement(); } } public class IdManager : SignatureTargetIdManager { internal static readonly XmlDictionaryString ElementName = XD.XmlEncryptionDictionary.EncryptedData; static readonly IdManager instance = new IdManager(); IdManager() { } public override string DefaultIdNamespacePrefix { get { return UtilityStrings.Prefix; } } public override string DefaultIdNamespaceUri { get { return UtilityStrings.Namespace; } } internal static IdManager Instance { get { return instance; } } public override string ExtractId(XmlDictionaryReader reader) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); if (reader.IsStartElement(ElementName, XD.XmlEncryptionDictionary.Namespace)) { return reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null); } else { return reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); } } public override void WriteIdAttribute(XmlDictionaryWriter writer, string id) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id); } } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Media; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Services; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors { /// <summary> /// Represents an image cropper property editor. /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.ImageCropper, "Image Cropper", "imagecropper", ValueType = ValueTypes.Json, HideLabel = false, Group = Constants.PropertyEditors.Groups.Media, Icon = "icon-crop")] public class ImageCropperPropertyEditor : DataEditor, IMediaUrlGenerator, INotificationHandler<ContentCopiedNotification>, INotificationHandler<ContentDeletedNotification>, INotificationHandler<MediaDeletedNotification>, INotificationHandler<MediaSavingNotification>, INotificationHandler<MemberDeletedNotification> { private readonly MediaFileManager _mediaFileManager; private readonly ContentSettings _contentSettings; private readonly IDataTypeService _dataTypeService; private readonly IIOHelper _ioHelper; private readonly UploadAutoFillProperties _autoFillProperties; private readonly ILogger<ImageCropperPropertyEditor> _logger; private readonly IContentService _contentService; /// <summary> /// Initializes a new instance of the <see cref="ImageCropperPropertyEditor"/> class. /// </summary> public ImageCropperPropertyEditor( IDataValueEditorFactory dataValueEditorFactory, ILoggerFactory loggerFactory, MediaFileManager mediaFileManager, IOptions<ContentSettings> contentSettings, IDataTypeService dataTypeService, IIOHelper ioHelper, UploadAutoFillProperties uploadAutoFillProperties, IContentService contentService) : base(dataValueEditorFactory) { _mediaFileManager = mediaFileManager ?? throw new ArgumentNullException(nameof(mediaFileManager)); _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _dataTypeService = dataTypeService ?? throw new ArgumentNullException(nameof(dataTypeService)); _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); _autoFillProperties = uploadAutoFillProperties ?? throw new ArgumentNullException(nameof(uploadAutoFillProperties)); _contentService = contentService; _logger = loggerFactory.CreateLogger<ImageCropperPropertyEditor>(); } public bool TryGetMediaPath(string propertyEditorAlias, object value, out string mediaPath) { if (propertyEditorAlias == Alias && GetFileSrcFromPropertyValue(value, out _, false) is var mediaPathValue && !string.IsNullOrWhiteSpace(mediaPathValue)) { mediaPath = mediaPathValue; return true; } mediaPath = null; return false; } /// <summary> /// Creates the corresponding property value editor. /// </summary> /// <returns>The corresponding property value editor.</returns> protected override IDataValueEditor CreateValueEditor() => DataValueEditorFactory.Create<ImageCropperPropertyValueEditor>(Attribute); /// <summary> /// Creates the corresponding preValue editor. /// </summary> /// <returns>The corresponding preValue editor.</returns> protected override IConfigurationEditor CreateConfigurationEditor() => new ImageCropperConfigurationEditor(_ioHelper); /// <summary> /// Gets a value indicating whether a property is an image cropper field. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the specified property is an image cropper field; otherwise, <c>false</c>. /// </returns> private static bool IsCropperField(IProperty property) => property.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.Aliases.ImageCropper; /// <summary> /// Parses the property value into a json object. /// </summary> /// <param name="value">The property value.</param> /// <param name="writeLog">A value indicating whether to log the error.</param> /// <returns>The json object corresponding to the property value.</returns> /// <remarks>In case of an error, optionally logs the error and returns null.</remarks> private JObject GetJObject(string value, bool writeLog) { if (string.IsNullOrWhiteSpace(value)) return null; try { return JsonConvert.DeserializeObject<JObject>(value); } catch (Exception ex) { if (writeLog) _logger.LogError(ex, "Could not parse image cropper value '{Json}'", value); return null; } } /// <summary> /// The paths to all image cropper property files contained within a collection of content entities /// </summary> /// <param name="entities"></param> private IEnumerable<string> ContainedFilePaths(IEnumerable<IContentBase> entities) => entities .SelectMany(x => x.Properties) .Where(IsCropperField) .SelectMany(GetFilePathsFromPropertyValues) .Distinct(); /// <summary> /// Look through all property values stored against the property and resolve any file paths stored /// </summary> /// <param name="prop"></param> /// <returns></returns> private IEnumerable<string> GetFilePathsFromPropertyValues(IProperty prop) { //parses out the src from a json string foreach (var propertyValue in prop.Values) { //check if the published value contains data and return it var src = GetFileSrcFromPropertyValue(propertyValue.PublishedValue, out var _); if (src != null) yield return _mediaFileManager.FileSystem.GetRelativePath(src); //check if the edited value contains data and return it src = GetFileSrcFromPropertyValue(propertyValue.EditedValue, out var _); if (src != null) yield return _mediaFileManager.FileSystem.GetRelativePath(src); } } /// <summary> /// Returns the "src" property from the json structure if the value is formatted correctly /// </summary> /// <param name="propVal"></param> /// <param name="deserializedValue">The deserialized <see cref="JObject"/> value</param> /// <param name="relative">Should the path returned be the application relative path</param> /// <returns></returns> private string GetFileSrcFromPropertyValue(object propVal, out JObject deserializedValue, bool relative = true) { deserializedValue = null; if (propVal == null || !(propVal is string str)) return null; if (!str.DetectIsJson()) { // Assume the value is a plain string with the file path deserializedValue = new JObject() { { "src", str } }; } else { deserializedValue = GetJObject(str, true); } if (deserializedValue?["src"] == null) return null; var src = deserializedValue["src"].Value<string>(); return relative ? _mediaFileManager.FileSystem.GetRelativePath(src) : src; } /// <summary> /// After a content has been copied, also copy uploaded files. /// </summary> public void Handle(ContentCopiedNotification notification) { // get the image cropper field properties var properties = notification.Original.Properties.Where(IsCropperField); // copy files var isUpdated = false; foreach (var property in properties) { //copy each of the property values (variants, segments) to the destination by using the edited value foreach (var propertyValue in property.Values) { var propVal = property.GetValue(propertyValue.Culture, propertyValue.Segment); var src = GetFileSrcFromPropertyValue(propVal, out var jo); if (src == null) { continue; } var sourcePath = _mediaFileManager.FileSystem.GetRelativePath(src); var copyPath = _mediaFileManager.CopyFile(notification.Copy, property.PropertyType, sourcePath); jo["src"] = _mediaFileManager.FileSystem.GetUrl(copyPath); notification.Copy.SetValue(property.Alias, jo.ToString(Formatting.None), propertyValue.Culture, propertyValue.Segment); isUpdated = true; } } // if updated, re-save the copy with the updated value if (isUpdated) { _contentService.Save(notification.Copy); } } public void Handle(ContentDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); public void Handle(MediaDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); public void Handle(MemberDeletedNotification notification) => DeleteContainedFiles(notification.DeletedEntities); private void DeleteContainedFiles(IEnumerable<IContentBase> deletedEntities) { var filePathsToDelete = ContainedFilePaths(deletedEntities); _mediaFileManager.DeleteMediaFiles(filePathsToDelete); } public void Handle(MediaSavingNotification notification) { foreach (var entity in notification.SavedEntities) { AutoFillProperties(entity); } } /// <summary> /// Auto-fill properties (or clear). /// </summary> private void AutoFillProperties(IContentBase model) { var properties = model.Properties.Where(IsCropperField); foreach (var property in properties) { var autoFillConfig = _contentSettings.GetConfig(property.Alias); if (autoFillConfig == null) continue; foreach (var pvalue in property.Values) { var svalue = property.GetValue(pvalue.Culture, pvalue.Segment) as string; if (string.IsNullOrWhiteSpace(svalue)) { _autoFillProperties.Reset(model, autoFillConfig, pvalue.Culture, pvalue.Segment); } else { var jo = GetJObject(svalue, false); string src; if (jo == null) { // so we have a non-empty string value that cannot be parsed into a json object // see http://issues.umbraco.org/issue/U4-4756 // it can happen when an image is uploaded via the folder browser, in which case // the property value will be the file source eg '/media/23454/hello.jpg' and we // are fixing that anomaly here - does not make any sense at all but... bah... src = svalue; property.SetValue(JsonConvert.SerializeObject(new { src = svalue }, Formatting.None), pvalue.Culture, pvalue.Segment); } else { src = jo["src"]?.Value<string>(); } if (src == null) _autoFillProperties.Reset(model, autoFillConfig, pvalue.Culture, pvalue.Segment); else _autoFillProperties.Populate(model, autoFillConfig, _mediaFileManager.FileSystem.GetRelativePath(src), pvalue.Culture, pvalue.Segment); } } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Agent.AssetTransaction { /// <summary> /// Manage asset transactions for a single agent. /// </summary> public class AgentAssetTransactions { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Fields private bool m_dumpAssetsToFile; public AssetTransactionModule Manager; public UUID UserID; public Dictionary<UUID, AssetXferUploader> XferUploaders = new Dictionary<UUID, AssetXferUploader>(); // Methods public AgentAssetTransactions(UUID agentID, AssetTransactionModule manager, bool dumpAssetsToFile) { UserID = agentID; Manager = manager; m_dumpAssetsToFile = dumpAssetsToFile; } public AssetXferUploader RequestXferUploader(UUID transactionID) { if (!XferUploaders.ContainsKey(transactionID)) { AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile); lock (XferUploaders) { XferUploaders.Add(transactionID, uploader); } return uploader; } return null; } public void HandleXfer(ulong xferID, uint packetID, byte[] data) { lock (XferUploaders) { foreach (AssetXferUploader uploader in XferUploaders.Values) { if (uploader.XferID == xferID) { uploader.HandleXferPacket(xferID, packetID, data); break; } } } } public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { if (XferUploaders.ContainsKey(transactionID)) { XferUploaders[transactionID].RequestCreateInventoryItem(remoteClient, transactionID, folderID, callbackID, description, name, invType, type, wearableType, nextOwnerMask); } } /// <summary> /// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed. /// </summary> /// <param name="transactionID"></param> /// <returns>The asset if the upload has completed, null if it has not.</returns> public AssetBase GetTransactionAsset(UUID transactionID) { if (XferUploaders.ContainsKey(transactionID)) { AssetXferUploader uploader = XferUploaders[transactionID]; AssetBase asset = uploader.GetAssetData(); lock (XferUploaders) { XferUploaders.Remove(transactionID); } return asset; } return null; } //private void CreateItemFromUpload(AssetBase asset, IClientAPI ourClient, UUID inventoryFolderID, uint nextPerms, uint wearableType) //{ // Manager.MyScene.CommsManager.AssetCache.AddAsset(asset); // CachedUserInfo userInfo = Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails( // ourClient.AgentId); // if (userInfo != null) // { // InventoryItemBase item = new InventoryItemBase(); // item.Owner = ourClient.AgentId; // item.Creator = ourClient.AgentId; // item.ID = UUID.Random(); // item.AssetID = asset.FullID; // item.Description = asset.Description; // item.Name = asset.Name; // item.AssetType = asset.Type; // item.InvType = asset.Type; // item.Folder = inventoryFolderID; // item.BasePermissions = 0x7fffffff; // item.CurrentPermissions = 0x7fffffff; // item.EveryOnePermissions = 0; // item.NextPermissions = nextPerms; // item.Flags = wearableType; // item.CreationDate = Util.UnixTimeSinceEpoch(); // userInfo.AddItem(item); // ourClient.SendInventoryItemCreateUpdate(item); // } // else // { // m_log.ErrorFormat( // "[ASSET TRANSACTIONS]: Could not find user {0} for inventory item creation", // ourClient.AgentId); // } //} public void RequestUpdateTaskInventoryItem( IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item) { if (XferUploaders.ContainsKey(transactionID)) { AssetBase asset = XferUploaders[transactionID].GetAssetData(); if (asset != null) { m_log.DebugFormat( "[ASSET TRANSACTIONS]: Updating task item {0} in {1} with asset in transaction {2}", item.Name, part.Name, transactionID); asset.Name = item.Name; asset.Description = item.Description; asset.Type = (sbyte)item.Type; item.AssetID = asset.FullID; Manager.MyScene.AssetService.Store(asset); if (part.Inventory.UpdateInventoryItem(item)) part.GetProperties(remoteClient); } } } public void RequestUpdateInventoryItem(IClientAPI remoteClient, UUID transactionID, InventoryItemBase item) { if (XferUploaders.ContainsKey(transactionID)) { UUID assetID = UUID.Combine(transactionID, remoteClient.SecureSessionId); AssetBase asset = Manager.MyScene.AssetService.Get(assetID.ToString()); if (asset == null) { asset = GetTransactionAsset(transactionID); } if (asset != null && asset.FullID == assetID) { // Assets never get updated, new ones get created asset.FullID = UUID.Random(); asset.Name = item.Name; asset.Description = item.Description; asset.Type = (sbyte)item.AssetType; item.AssetID = asset.FullID; Manager.MyScene.AssetService.Store(asset); } IInventoryService invService = Manager.MyScene.InventoryService; invService.UpdateItem(item); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Xtr3D.Net.ExtremeMotion.Data; /// <summary> /// MxN grid,time based click /// </summary> public class Concept0Controller : MonoBehaviour { private const float CLICK_TIME_IN_SEC = 1; private const int INVALID_VALUE = -1; private const int BUTTONS_IN_ROW = 3; private const int BUTTONS_IN_COL = 2; private const int NUM_OF_BUTTONS = BUTTONS_IN_ROW * BUTTONS_IN_COL; private const float BUTTON_VALIDATION_TIME = 0.1f; private const float TIME_BASED_ANIMATION_START_DELAY = 1f; private const float SKELETON_MAX_X_POS = 1.15f; private const float SKELETON_MIN_X_POS = 0.31f; private const float REGION_START_X = 0.30f; private const float REGION_START_Y = 0.8f; private const float REGION_WIDTH = 0.30f; private const float REGION_HEIGHT = 0.45f; private const float SCENE_BUTTON_HYSTE_X = 0.05f; private const float SCENE_BUTTON_HYSTE_Y = 0.05f; // buttons params private const float BUTTON_WIDTH = 367; private const float BUTTON_HEIGHT = 211; private const float BUTTON_START_X_POS = -370; private const float BUTTON_START_Y_POS = 240; private const float BUTTON_X_ROW_SPACE = 20; private const float BUTTON_Y_ROW_SPACE = 140; public CalibrationManager m_calibrationManager; private GenericRegionsManager m_regionManager; public SkeletonManager m_skeletonManager; public TimeBaseAnimation m_timeBaseAnimation; public SceneHeadline m_myHeadline; private float m_myTimer = 0; // game timer private int m_currentSelectedRegionID = INVALID_VALUE; private int m_lastSelectedRegionID = INVALID_VALUE; private float m_buttonSelectedStartedTime = INVALID_VALUE; private float m_buttonValidationStartedTime = INVALID_VALUE; private float m_lastRegionValidationID = INVALID_VALUE; private float m_timeBasedClickDelay = INVALID_VALUE; private int m_currentSelectedButtonID = INVALID_VALUE; private int m_lastSelectedButtonID = INVALID_VALUE; private GridItem[] m_gridItems; // maps region id's to their current active button private Dictionary<int, int> m_regionIdToButtonId = new Dictionary<int, int>(); private static TrackingState m_lastEngineState = TrackingState.NotTracked; void Awake() { //Creating region manager m_regionManager = new GenericRegionsManager(); } void Start () { CreateButtons(); CreateRegions(); m_myHeadline.SetText("Grid Selection"); } void Update () { //updating scene timer m_myTimer += Time.deltaTime; UpdateCalibrationState(); // We want to allow navigate throw menu only if T pose geture is not performed UpdateActiveButton(); } /// <summary> /// Updates the state of the calibration screen. /// </summary> private void UpdateCalibrationState () { if(!m_lastEngineState.Equals(m_skeletonManager.GetTrackingState())) { m_lastEngineState = m_skeletonManager.GetTrackingState(); switch (m_lastEngineState) { case TrackingState.Calibrating: m_calibrationManager.ShowCalibration(true); break; case TrackingState.Tracked: m_calibrationManager.ShowCalibration(false); break; default: break; } } } /// <summary> /// Creates the buttons and placing them in scene. /// </summary> private void CreateButtons() { m_gridItems = new GridItem[NUM_OF_BUTTONS]; GameObject gridItemPrefab = (GameObject) Resources.Load("Prefabs/GridItem"); // loading grid item prefab from resources //Building the buttons matrix for(int i = 0; i < BUTTONS_IN_ROW;i++) { for(int j = 0; j < BUTTONS_IN_COL;j++) { GameObject myItemObject = (GameObject) Instantiate(gridItemPrefab,Vector3.zero,Quaternion.identity); m_gridItems[j*BUTTONS_IN_ROW+i] = myItemObject.GetComponent<GridItem>(); m_gridItems[j*BUTTONS_IN_ROW+i].transform.parent = this.transform; m_gridItems[j*BUTTONS_IN_ROW+i].Init(new Vector3(BUTTON_START_X_POS + (i*(BUTTON_WIDTH + BUTTON_X_ROW_SPACE)),BUTTON_START_Y_POS - (j * (BUTTON_HEIGHT + BUTTON_Y_ROW_SPACE)),0)); ((GridItem)m_gridItems[j*BUTTONS_IN_ROW+i]).SetImage(j*BUTTONS_IN_ROW+i); m_gridItems[j*BUTTONS_IN_ROW+i].SetImageSize(BUTTON_WIDTH,BUTTON_HEIGHT); } } } /// <summary> /// Creates the regions. /// </summary> private void CreateRegions () { for(int i = 0; i < BUTTONS_IN_ROW;i++) { for(int j = 0; j < BUTTONS_IN_COL;j++) { int regionID = m_regionManager.AddRegion(REGION_START_X + (i * REGION_WIDTH),REGION_START_Y - (j * REGION_HEIGHT),REGION_WIDTH,REGION_HEIGHT,SCENE_BUTTON_HYSTE_X,SCENE_BUTTON_HYSTE_Y); m_regionIdToButtonId.Add(regionID,j*BUTTONS_IN_ROW+i); } } } /// <summary> /// Updates the active buttons. /// </summary> private void UpdateActiveButton () { if(m_lastEngineState.Equals(TrackingState.Tracked)) // if user is tracked { // limits palm x pos by SKELETON_MAX_X_POS Vector2 palmPosition = m_skeletonManager.GetRightPalmPosition(); Vector2 palmFixedPosition = new Vector2(Mathf.Clamp(palmPosition.x,SKELETON_MIN_X_POS,SKELETON_MAX_X_POS), palmPosition.y); //saving current active region according to cursor position int currentRegion = m_regionManager.GetActiveRegion(palmFixedPosition); if(IsButtonSelectionValid(currentRegion)) // checking if active region is selected for BUTTON_VALIDATION_TIME { m_currentSelectedRegionID = currentRegion; //checking if a new region is selected if(m_currentSelectedRegionID != m_lastSelectedRegionID) { m_currentSelectedButtonID = m_regionIdToButtonId[m_currentSelectedRegionID]; m_gridItems[m_currentSelectedButtonID].HighLightState(true); DeselectLastRegion(); //update new selected button m_lastSelectedRegionID = m_currentSelectedRegionID; m_lastSelectedButtonID = m_currentSelectedButtonID; // if we have a new button we want starting a new time based click InitClickState(); } UpdateTimeBaseClick(); } } else // user is not tracked { InitClickState(); } } /// <summary> /// Checks if the current button is selected for BUTTON_VALIDATION_TIME /// </summary> /// <returns> /// <c>true</c> if BUTTON_VALIDATION_TIME passed ; otherwise, <c>false</c>. /// </returns> private bool IsButtonSelectionValid (int activeRegionId) { bool valid = false; if(activeRegionId != INVALID_VALUE) { if(activeRegionId != m_lastRegionValidationID) { // we have a new region to check validation m_buttonValidationStartedTime = INVALID_VALUE; m_lastRegionValidationID = activeRegionId; } else if(m_buttonValidationStartedTime == INVALID_VALUE) { m_buttonValidationStartedTime = m_myTimer; } else { if(m_myTimer - m_buttonValidationStartedTime > BUTTON_VALIDATION_TIME) { m_buttonValidationStartedTime = INVALID_VALUE; valid = true; } } } else{ InitRegionsState(); //we are on the empty region! } return valid; } private bool IsTimeBasedAnimationDelayFinished () { bool delayFinished = false; if(m_timeBasedClickDelay == INVALID_VALUE) { m_timeBasedClickDelay = m_myTimer; } else { if(m_myTimer - m_timeBasedClickDelay > TIME_BASED_ANIMATION_START_DELAY) { delayFinished = true; } } return delayFinished; } /// <summary> /// Play time base animation and updates click time. /// </summary> private void UpdateTimeBaseClick () { if(IsTimeBasedAnimationDelayFinished()) { if(m_buttonSelectedStartedTime == INVALID_VALUE) // checks if time based click didn't start yet { UpdateClickAnimationPosition(); m_buttonSelectedStartedTime = m_myTimer; m_timeBaseAnimation.PlayAnimation(); // starts time based click animation } else // time based click already started { //checking if time from m_buttonSelectedStartedTime is larger than click time threshold if(m_myTimer - m_buttonSelectedStartedTime > CLICK_TIME_IN_SEC) { // if button not already on click state if(!m_gridItems[m_currentSelectedButtonID].IsClicked) { //button clicked m_gridItems[m_currentSelectedButtonID].ClickedState(); m_timeBaseAnimation.HideAnimation(); } } } } } void UpdateClickAnimationPosition () { m_timeBaseAnimation.transform.localPosition = m_gridItems[m_regionIdToButtonId[m_currentSelectedRegionID]].transform.localPosition; } /// <summary> /// Inits the state of the regions. /// </summary> private void InitRegionsState() { DeselectLastRegion(); m_currentSelectedRegionID = INVALID_VALUE; m_currentSelectedButtonID = INVALID_VALUE; m_lastSelectedRegionID = INVALID_VALUE; m_lastSelectedButtonID = INVALID_VALUE; m_lastRegionValidationID = INVALID_VALUE; m_timeBaseAnimation.HideAnimation(); } /// <summary> /// Initilizes the state. /// </summary> private void InitClickState() { m_timeBasedClickDelay = INVALID_VALUE; m_buttonSelectedStartedTime = INVALID_VALUE; m_timeBaseAnimation.HideAnimation(); } /// <summary> /// Deslects the last button. /// </summary> private void DeselectLastRegion () { //deselect last highlighted button if we have one if(m_lastSelectedRegionID != INVALID_VALUE) { m_gridItems[m_lastSelectedButtonID].HighLightState(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Dynamic; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { [PythonType("instancemethod"), DontMapGetMemberNamesToDir] public sealed partial class Method : PythonTypeSlot, IWeakReferenceable, IPythonMembersList, IDynamicMetaObjectProvider, ICodeFormattable, Binding.IFastInvokable { private readonly object _func; private readonly object _inst; private readonly object _declaringClass; private WeakRefTracker _weakref; public Method(object function, object instance, object @class) { _func = function; _inst = instance; _declaringClass = @class; } public Method(object function, object instance) { if (instance == null) { throw PythonOps.TypeError("unbound methods must have a class provided"); } _func = function; _inst = instance; } internal string Name { get { return (string)PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__"); } } public string __doc__ { get { return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__doc__") as string; } } public object im_func { get { return _func; } } public object __func__ { get { return _func; } } public object im_self { get { return _inst; } } public object __self__ { get { return _inst; } } public object im_class { get { // we could have an OldClass (or any other object) here if the user called the ctor directly return PythonOps.ToPythonType(_declaringClass as PythonType) ?? _declaringClass; } } [SpecialName] public object Call(CodeContext/*!*/ context, params object[] args) { return context.LanguageContext.CallSplat(this, args); } [SpecialName] public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) { return context.LanguageContext.CallWithKeywords(this, args, kwArgs); } private Exception BadSelf(object got) { OldClass dt = im_class as OldClass; string firstArg; if (got == null) { firstArg = "nothing"; } else { firstArg = PythonOps.GetPythonTypeName(got) + " instance"; } PythonType pt = im_class as PythonType; return PythonOps.TypeError("unbound method {0}() must be called with {1} instance as first argument (got {2} instead)", Name, (dt != null) ? dt.Name : (pt != null) ? pt.Name : im_class, firstArg); } /// <summary> /// Validates that the current self object is usable for this method. /// </summary> internal object CheckSelf(CodeContext context, object self) { if (!PythonOps.IsInstance(context, self, im_class)) { throw BadSelf(self); } return self; } #region Object Overrides private string DeclaringClassAsString() { if (im_class == null) return "?"; if (im_class is PythonType dt) return dt.Name; if (im_class is OldClass oc) return oc.Name; return im_class.ToString(); } public override bool Equals(object obj) { if (!(obj is Method other)) return false; return (object.ReferenceEquals(_inst, other._inst) || PythonOps.EqualRetBool(_inst, other._inst)) && PythonOps.EqualRetBool(_func, other._func); } public override int GetHashCode() { if (_inst == null) return PythonOps.Hash(DefaultContext.Default, _func); return PythonOps.Hash(DefaultContext.Default, _inst) ^ PythonOps.Hash(DefaultContext.Default, _func); } #endregion #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _weakref; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _weakref = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { ((IWeakReferenceable)this).SetWeakRef(value); } #endregion #region Custom member access [SpecialName] public object GetCustomMember(CodeContext context, string name) { switch (name) { // Get the module name from the function and pass that out. Note that CPython's method has // no __module__ attribute and this value can be gotten via a call to method.__getattribute__ // there as well. case "__module__": return PythonOps.GetBoundAttr(context, _func, "__module__"); case "__name__": return PythonOps.GetBoundAttr(DefaultContext.Default, _func, "__name__"); default: object value; string symbol = name; if (TypeCache.Method.TryGetBoundMember(context, this, symbol, out value) || // look on method PythonOps.TryGetBoundAttr(context, _func, symbol, out value)) { // Forward to the func return value; } return OperationFailed.Value; } } [SpecialName] public void SetMemberAfter(CodeContext context, string name, object value) { TypeCache.Method.SetMember(context, this, name, value); } [SpecialName] public void DeleteMember(CodeContext context, string name) { TypeCache.Method.DeleteMember(context, this, name); } IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { List ret = TypeCache.Method.GetMemberNames(context); ret.AddNoLockNoDups("__module__"); if (_func is PythonFunction pf) { PythonDictionary dict = pf.func_dict; // Check the func foreach (KeyValuePair<object, object> kvp in dict) { ret.AddNoLockNoDups(kvp.Key); } } return ret; } #endregion #region PythonTypeSlot Overrides internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (this.im_self == null) { if (owner == null || owner == im_class || PythonOps.IsSubClass(context, owner, im_class)) { value = new Method(_func, instance, owner); return true; } } value = this; return true; } internal override bool GetAlwaysSucceeds { get { return true; } } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { object name; if (!PythonOps.TryGetBoundAttr(context, _func, "__name__", out name)) { name = "?"; } if (_inst != null) { return string.Format("<bound method {0}.{1} of {2}>", DeclaringClassAsString(), name, PythonOps.Repr(context, _inst)); } else { return string.Format("<unbound method {0}.{1}>", DeclaringClassAsString(), name); } } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaMethod(parameter, BindingRestrictions.Empty, this); } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; using System.Threading; using System.Xml; #if !NO_CONFIGURATION using System.Runtime.Serialization.Configuration; #endif using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; using System.Security.Permissions; [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] #if USE_REFEMIT public struct KeyValue<K, V> #else internal struct KeyValue<K, V> #endif { K key; V value; internal KeyValue(K key, V value) { this.key = key; this.value = value; } [DataMember(IsRequired = true)] public K Key { get { return key; } set { key = value; } } [DataMember(IsRequired = true)] public V Value { get { return value; } set { this.value = value; } } } internal enum CollectionKind : byte { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array, } #if USE_REFEMIT public sealed class CollectionDataContract : DataContract #else internal sealed class CollectionDataContract : DataContract #endif { [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the XML element name for collection items." + "Statically cached and used from IL generated code.")] [SecurityCritical] XmlDictionaryString collectionItemName; [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the XML namespace for collection items." + "Statically cached and used from IL generated code.")] [SecurityCritical] XmlDictionaryString childElementNamespace; [Fx.Tag.SecurityNote(Critical = "Internal DataContract representing the contract for collection items." + "Statically cached and used from IL generated code.")] [SecurityCritical] DataContract itemContract; [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization. " + "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")] [SecurityCritical] CollectionDataContractCriticalHelper helper; [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind)) { InitCollectionDataContract(this); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal CollectionDataContract(Type type, DataContract itemContract) : base(new CollectionDataContractCriticalHelper(type, itemContract)) { InitCollectionDataContract(this); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical fields; called from all constructors.")] [SecurityCritical] void InitCollectionDataContract(DataContract sharedTypeContract) { this.helper = base.Helper as CollectionDataContractCriticalHelper; this.collectionItemName = helper.CollectionItemName; if (helper.Kind == CollectionKind.Dictionary || helper.Kind == CollectionKind.GenericDictionary) { this.itemContract = helper.ItemContract; } this.helper.SharedTypeContract = sharedTypeContract; } void InitSharedTypeContract() { } static Type[] KnownInterfaces { [Fx.Tag.SecurityNote(Critical = "Fetches the critical knownInterfaces property.", Safe = "knownInterfaces only needs to be protected for write.")] [SecuritySafeCritical] get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { [Fx.Tag.SecurityNote(Critical = "Fetches the critical kind property.", Safe = "kind only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.Kind; } } internal Type ItemType { [Fx.Tag.SecurityNote(Critical = "Fetches the critical itemType property.", Safe = "itemType only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ItemType; } } public DataContract ItemContract { [Fx.Tag.SecurityNote(Critical = "Fetches the critical itemContract property.", Safe = "itemContract only needs to be protected for write.")] [SecuritySafeCritical] get { return itemContract ?? helper.ItemContract; } [Fx.Tag.SecurityNote(Critical = "Sets the critical itemContract property.")] [SecurityCritical] set { itemContract = value; helper.ItemContract = value; } } internal DataContract SharedTypeContract { [Fx.Tag.SecurityNote(Critical = "Fetches the critical sharedTypeContract property.", Safe = "sharedTypeContract only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.SharedTypeContract; } } internal string ItemName { [Fx.Tag.SecurityNote(Critical = "Fetches the critical itemName property.", Safe = "itemName only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ItemName; } [Fx.Tag.SecurityNote(Critical = "Sets the critical itemName property.")] [SecurityCritical] set { helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { [Fx.Tag.SecurityNote(Critical = "Fetches the critical collectionItemName property.", Safe = "collectionItemName only needs to be protected for write.")] [SecuritySafeCritical] get { return this.collectionItemName; } } internal string KeyName { [Fx.Tag.SecurityNote(Critical = "Fetches the critical keyName property.", Safe = "keyName only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.KeyName; } [Fx.Tag.SecurityNote(Critical = "Sets the critical keyName property.")] [SecurityCritical] set { helper.KeyName = value; } } internal string ValueName { [Fx.Tag.SecurityNote(Critical = "Fetches the critical valueName property.", Safe = "valueName only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ValueName; } [Fx.Tag.SecurityNote(Critical = "Sets the critical valueName property.")] [SecurityCritical] set { helper.ValueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString ChildElementNamespace { [Fx.Tag.SecurityNote(Critical = "Fetches the critical childElementNamespace property.", Safe = "childElementNamespace only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (this.childElementNamespace == null) { lock (this) { if (this.childElementNamespace == null) { if (helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Thread.MemoryBarrier(); helper.ChildElementNamespace = tempChildElementNamespace; } this.childElementNamespace = helper.ChildElementNamespace; } } } return childElementNamespace; } } internal bool IsItemTypeNullable { [Fx.Tag.SecurityNote(Critical = "Fetches the critical isItemTypeNullable property.", Safe = "isItemTypeNullable only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsItemTypeNullable; } [Fx.Tag.SecurityNote(Critical = "Sets the critical isItemTypeNullable property.")] [SecurityCritical] set { helper.IsItemTypeNullable = value; } } internal bool IsConstructorCheckRequired { [Fx.Tag.SecurityNote(Critical = "Fetches the critical isConstructorCheckRequired property.", Safe = "isConstructorCheckRequired only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsConstructorCheckRequired; } [Fx.Tag.SecurityNote(Critical = "Sets the critical isConstructorCheckRequired property.")] [SecurityCritical] set { helper.IsConstructorCheckRequired = value; } } internal MethodInfo GetEnumeratorMethod { [Fx.Tag.SecurityNote(Critical = "Fetches the critical getEnumeratorMethod property.", Safe = "getEnumeratorMethod only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.GetEnumeratorMethod; } } internal MethodInfo AddMethod { [Fx.Tag.SecurityNote(Critical = "Fetches the critical addMethod property.", Safe = "addMethod only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.AddMethod; } } internal ConstructorInfo Constructor { [Fx.Tag.SecurityNote(Critical = "Fetches the critical constructor property.", Safe = "constructor only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.Constructor; } } internal override DataContractDictionary KnownDataContracts { [Fx.Tag.SecurityNote(Critical = "Fetches the critical knownDataContracts property.", Safe = "knownDataContracts only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.KnownDataContracts; } [Fx.Tag.SecurityNote(Critical = "Sets the critical knownDataContracts property.")] [SecurityCritical] set { helper.KnownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { [Fx.Tag.SecurityNote(Critical = "Fetches the critical invalidCollectionInSharedContractMessage property.", Safe = "invalidCollectionInSharedContractMessage only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.InvalidCollectionInSharedContractMessage; } } internal string SerializationExceptionMessage { [Fx.Tag.SecurityNote(Critical = "Fetches the critical serializationExceptionMessage property.", Safe = "serializationExceptionMessage only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.SerializationExceptionMessage; } } internal string DeserializationExceptionMessage { [Fx.Tag.SecurityNote(Critical = "Fetches the critical deserializationExceptionMessage property.", Safe = "deserializationExceptionMessage only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract { get { return this.DeserializationExceptionMessage != null; } } bool ItemNameSetExplicit { [Fx.Tag.SecurityNote(Critical = "Fetches the critical itemNameSetExplicit property.", Safe = "itemNameSetExplicit only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ItemNameSetExplicit; } } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { [Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatWriterDelegate property.", Safe = "xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (helper.XmlFormatWriterDelegate == null) { lock (this) { if (helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this); Thread.MemoryBarrier(); helper.XmlFormatWriterDelegate = tempDelegate; } } } return helper.XmlFormatWriterDelegate; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { [Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatReaderDelegate property.", Safe = "xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (helper.XmlFormatReaderDelegate == null) { lock (this) { if (helper.XmlFormatReaderDelegate == null) { if (this.IsReadOnlyContract) { ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null /*type*/); } XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this); Thread.MemoryBarrier(); helper.XmlFormatReaderDelegate = tempDelegate; } } } return helper.XmlFormatReaderDelegate; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { [Fx.Tag.SecurityNote(Critical = "Fetches the critical xmlFormatGetOnlyCollectionReaderDelegate property.", Safe = "xmlFormatGetOnlyCollectionReaderDelegate only needs to be protected for write; initialized in getter if null.")] [SecuritySafeCritical] get { if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (this.UnderlyingType.IsInterface && (this.Kind == CollectionKind.Enumerable || this.Kind == CollectionKind.Collection || this.Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } if (this.IsReadOnlyContract) { ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null /*type*/); } Fx.Assert(this.AddMethod != null || this.Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property"); XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); Thread.MemoryBarrier(); helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate; } } } return helper.XmlFormatGetOnlyCollectionReaderDelegate; } } [Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing collections. Since the data is cached statically, we lock down access to it.")] #if !NO_SECURITY_ATTRIBUTES [SecurityCritical(SecurityCriticalScope.Everything)] #endif class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { static Type[] _knownInterfaces; Type itemType; bool isItemTypeNullable; CollectionKind kind; readonly MethodInfo getEnumeratorMethod, addMethod; readonly ConstructorInfo constructor; readonly string serializationExceptionMessage, deserializationExceptionMessage; DataContract itemContract; DataContract sharedTypeContract; DataContractDictionary knownDataContracts; bool isKnownTypeAttributeChecked; string itemName; bool itemNameSetExplicit; XmlDictionaryString collectionItemName; string keyName; string valueName; XmlDictionaryString childElementNamespace; string invalidCollectionInSharedContractMessage; XmlFormatCollectionReaderDelegate xmlFormatReaderDelegate; XmlFormatGetOnlyCollectionReaderDelegate xmlFormatGetOnlyCollectionReaderDelegate; XmlFormatCollectionWriterDelegate xmlFormatWriterDelegate; bool isConstructorCheckRequired = false; internal static Type[] KnownInterfaces { get { if (_knownInterfaces == null) { // Listed in priority order _knownInterfaces = new Type[] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return _knownInterfaces; } } void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute) { this.kind = kind; if (itemType != null) { this.itemType = itemType; this.isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType)))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3); this.Name = dictionary.Add(this.StableName.Name); this.Namespace = dictionary.Add(this.StableName.Namespace); this.itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; this.collectionItemName = dictionary.Add(this.itemName); if (isDictionary) { this.keyName = keyName ?? Globals.KeyLocalName; this.valueName = valueName ?? Globals.ValueLocalName; } } if (collectionContractAttribute != null) { this.IsReference = collectionContractAttribute.IsReference; } } internal CollectionDataContractCriticalHelper(CollectionKind kind) : base() { Init(kind, null, null); } // array internal CollectionDataContractCriticalHelper(Type type) : base(type) { if (type == Globals.TypeOfArray) type = Globals.TypeOfObjectArray; if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SupportForMultidimensionalArraysNotPresent))); this.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } // array internal CollectionDataContractCriticalHelper(Type type, DataContract itemContract) : base(type) { if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SupportForMultidimensionalArraysNotPresent))); this.StableName = CreateQualifiedName(Globals.ArrayPrefix + itemContract.StableName.Name, itemContract.StableName.Namespace); this.itemContract = itemContract; Init(CollectionKind.Array, type.GetElementType(), null); } // read-only collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); this.getEnumeratorMethod = getEnumeratorMethod; this.serializationExceptionMessage = serializationExceptionMessage; this.deserializationExceptionMessage = deserializationExceptionMessage; } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : this(type, kind, itemType, getEnumeratorMethod, (string)null, (string)null) { if (addMethod == null && !type.IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); this.addMethod = addMethod; this.constructor = constructor; } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { this.isConstructorCheckRequired = isConstructorCheckRequired; } internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null /*itemType*/, null); this.invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } internal CollectionKind Kind { get { return kind; } } internal Type ItemType { get { return itemType; } } internal DataContract ItemContract { get { if (itemContract == null && UnderlyingType != null) { if (IsDictionary) { if (String.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException( SR.GetString(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); } else { itemContract = DataContract.GetDataContract(ItemType); } } return itemContract; } set { itemContract = value; } } internal DataContract SharedTypeContract { get { return sharedTypeContract; } set { sharedTypeContract = value; } } internal string ItemName { get { return itemName; } set { itemName = value; } } internal bool IsConstructorCheckRequired { get { return isConstructorCheckRequired; } set { isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName { get { return collectionItemName; } } internal string KeyName { get { return keyName; } set { keyName = value; } } internal string ValueName { get { return valueName; } set { valueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public string SerializationExceptionMessage { get { return serializationExceptionMessage; } } public string DeserializationExceptionMessage { get { return deserializationExceptionMessage; } } public XmlDictionaryString ChildElementNamespace { get { return childElementNamespace; } set { childElementNamespace = value; } } internal bool IsItemTypeNullable { get { return isItemTypeNullable; } set { isItemTypeNullable = value; } } internal MethodInfo GetEnumeratorMethod { get { return getEnumeratorMethod; } } internal MethodInfo AddMethod { get { return addMethod; } } internal ConstructorInfo Constructor { get { return constructor; } } internal override DataContractDictionary KnownDataContracts { get { if (!isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!isKnownTypeAttributeChecked) { knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Thread.MemoryBarrier(); isKnownTypeAttributeChecked = true; } } } return knownDataContracts; } set { knownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { get { return invalidCollectionInSharedContractMessage; } } internal bool ItemNameSetExplicit { get { return itemNameSetExplicit; } } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get { return xmlFormatWriterDelegate; } set { xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get { return xmlFormatReaderDelegate; } set { xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { get { return xmlFormatGetOnlyCollectionReaderDelegate; } set { xmlFormatGetOnlyCollectionReaderDelegate = value; } } } DataContract GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return this; } // ClassDataContract.IsNonAttributedTypeValidForSerialization does not need to be called here. It should // never pass because it returns false for types that implement any of CollectionDataContract.KnownInterfaces if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.IsGenericType) type = type.GetGenericTypeDefinition(); return ((IList<Type>)KnownInterfaces).Contains(type); } internal static bool IsCollection(Type type) { Type itemType; return IsCollection(type, out itemType); } internal static bool IsCollection(Type type, out Type itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } internal static bool IsCollection(Type type, bool constructorRequired, bool skipIfReadOnlyContract) { Type itemType; return IsCollectionHelper(type, out itemType, constructorRequired, skipIfReadOnlyContract); } static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType(); return true; } DataContract dataContract; return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired, skipIfReadOnlyContract); } internal static bool TryCreate(Type type, out DataContract dataContract) { Type itemType; return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/); } internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); } } internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType) { InterfaceMapping mapping = type.GetInterfaceMap(interfaceType); for (int i = 0; i < mapping.TargetMethods.Length; i++) { if (mapping.InterfaceMethods[i].Name == name) return mapping.InterfaceMethods[i]; } return null; } static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.Globalization, FxCop.Rule.DoNotPassLiteralsAsLocalizedParameters, Justification = "Private code.")] static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } MethodInfo addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); bool isReadOnlyContract = false; string serializationExceptionMessage = null, deserializationExceptionMessage = null; Type baseType = type.BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; // Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead bool createContractWithException = isBaseTypeCollection && !type.IsSerializable; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeCannotHaveDataContract, null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (type.IsInterface) { Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { addMethod = null; if (type.IsGenericType) { Type[] genericArgs = type.GetGenericArguments(); if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName); } else { itemType = genericArgs[0]; if (interfaceTypeToCheck == Globals.TypeOfICollectionGeneric || interfaceTypeToCheck == Globals.TypeOfIListGeneric) { addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName); } getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName); } } else { if (interfaceTypeToCheck == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue<object, object>); addMethod = type.GetMethod(Globals.AddMethodName); } else { itemType = Globals.TypeOfObject; if (interfaceTypeToCheck == Globals.TypeOfIList) { addMethod = Globals.TypeOfIList.GetMethod(Globals.AddMethodName); } } getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName); } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); return true; } } } ConstructorInfo defaultCtor = null; if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (defaultCtor == null && constructorRequired) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, SR.CollectionTypeDoesNotHaveDefaultCtor, null, out serializationExceptionMessage, out deserializationExceptionMessage); } } } Type knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { CollectionKind currentKind = (CollectionKind)(i + 1); if (kind == CollectionKind.None || currentKind < kind) { kind = currentKind; knownInterfaceType = interfaceType; multipleDefinitions = false; } else if ((kind & currentKind) == currentKind) multipleDefinitions = true; break; } } } if (kind == CollectionKind.None) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) knownInterfaceType = Globals.TypeOfIEnumerable; itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject; GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); if (addMethod == null) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in. if (type.IsSerializable || skipIfReadOnlyContract) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException && !skipIfReadOnlyContract, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), out serializationExceptionMessage, out deserializationExceptionMessage); } } if (tryCreate) { dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } else { if (multipleDefinitions) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } Type[] addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition || (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter); itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.Dictionary: addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); itemType = addMethodTypeArray[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; addMethodTypeArray = new Type[] { itemType }; break; } if (tryCreate) { GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } return !(isReadOnlyContract && skipIfReadOnlyContract); } internal static bool IsCollectionDataContract(Type type) { return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract) { if (hasCollectionDataContract) { if (tryCreate) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.GetString(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param))); return true; } if (createContractWithException) { if (tryCreate) dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.GetString(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param)); return true; } return false; } static void GetReadOnlyCollectionExceptionMessages(Type type, bool hasCollectionDataContract, string message, string param, out string serializationExceptionMessage, out string deserializationExceptionMessage) { serializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString(hasCollectionDataContract ? SR.InvalidCollectionDataContract : SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param); deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString(SR.ReadOnlyCollectionDeserialization, DataContract.GetClrTypeFullName(type)), param); } static string GetInvalidCollectionMessage(string message, string nestedMessage, string param) { return (param == null) ? SR.GetString(message, nestedMessage) : SR.GetString(message, nestedMessage, param); } static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod) { InterfaceMapping mapping = type.GetInterfaceMap(interfaceType); for (int i = 0; i < mapping.TargetMethods.Length; i++) { if (mapping.InterfaceMethods[i].Name == Globals.AddMethodName) addMethod = mapping.InterfaceMethods[i]; else if (mapping.InterfaceMethods[i].Name == Globals.GetEnumeratorMethodName) getEnumeratorMethod = mapping.InterfaceMethods[i]; } } static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod) { addMethod = getEnumeratorMethod = null; if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, null, addMethodTypeArray, null); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); foreach (Type parentInterfaceType in parentInterfaceTypes) { if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { // GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, addMethodTypeArray, null); } if (getEnumeratorMethod == null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type ienumerableInterface = interfaceType.GetInterface("System.Collections.Generic.IEnumerable*"); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); } } } static bool IsKnownInterface(Type type) { Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; foreach (Type knownInterfaceType in KnownInterfaces) { if (typeToCheck == knownInterfaceType) { return true; } } return false; } [Fx.Tag.SecurityNote(Critical = "Sets critical properties on CollectionDataContract .", Safe = "Called during schema import/code generation.")] [SecuritySafeCritical] internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts) { DataContract boundContract; if (boundContracts.TryGetValue(this, out boundContract)) return boundContract; CollectionDataContract boundCollectionContract = new CollectionDataContract(Kind); boundContracts.Add(this, boundCollectionContract); boundCollectionContract.ItemContract = this.ItemContract.BindGenericParameters(paramContracts, boundContracts); boundCollectionContract.IsItemTypeNullable = !boundCollectionContract.ItemContract.IsValueType; boundCollectionContract.ItemName = ItemNameSetExplicit ? this.ItemName : boundCollectionContract.ItemContract.StableName.Name; boundCollectionContract.KeyName = this.KeyName; boundCollectionContract.ValueName = this.ValueName; boundCollectionContract.StableName = CreateQualifiedName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(this.StableName.Name), new GenericNameProvider(DataContract.GetClrTypeFullName(this.UnderlyingType), paramContracts)), IsCollectionDataContract(UnderlyingType) ? this.StableName.Namespace : DataContract.GetCollectionNamespace(boundCollectionContract.ItemContract.StableName.Namespace)); return boundCollectionContract; } internal override DataContract GetValidContract(SerializationMode mode) { if (mode == SerializationMode.SharedType) { if (SharedTypeContract == null) DataContract.ThrowTypeNotSerializable(UnderlyingType); return SharedTypeContract; } ThrowIfInvalid(); return this; } void ThrowIfInvalid() { if (InvalidCollectionInSharedContractMessage != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); } internal override DataContract GetValidContract() { if (this.IsConstructorCheckRequired) { CheckConstructor(); } return this; } [Fx.Tag.SecurityNote(Critical = "Sets the critical IsConstructorCheckRequired property on CollectionDataContract.", Safe = "Does not leak anything.")] [SecuritySafeCritical] void CheckConstructor() { if (this.Constructor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } else { this.IsConstructorCheckRequired = false; } } internal override bool IsValidContract(SerializationMode mode) { if (mode == SerializationMode.SharedType) return (SharedTypeContract != null); return (InvalidCollectionInSharedContractMessage == null); } #if !NO_DYNAMIC_CODEGEN [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Calculates whether this collection requires MemberAccessPermission for deserialization." + " Since this information is used to determine whether to give the generated code access" + " permissions to private members, any changes to the logic should be reviewed.")] internal bool RequiresMemberAccessForRead(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(Constructor)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.AddMethod)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.AddMethod.Name), securityException)); } return true; } return false; } [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Calculates whether this collection requires MemberAccessPermission for serialization." + " Since this information is used to determine whether to give the generated code access" + " permissions to private members, any changes to the logic should be reviewed.")] internal bool RequiresMemberAccessForWrite(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } return false; } #endif internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) return true; if (base.Equals(other, checkedContracts)) { CollectionDataContract dataContract = other as CollectionDataContract; if (dataContract != null) { bool thisItemTypeIsNullable = (ItemContract == null) ? false : !ItemContract.IsValueType; bool otherItemTypeIsNullable = (dataContract.ItemContract == null) ? false : !dataContract.ItemContract.IsValueType; return ItemName == dataContract.ItemName && (IsItemTypeNullable || thisItemTypeIsNullable) == (dataContract.IsItemTypeNullable || otherItemTypeIsNullable) && ItemContract.Equals(dataContract.ItemContract, checkedContracts); } } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return o; } public class DictionaryEnumerator : IEnumerator<KeyValue<object, object>> { IDictionaryEnumerator enumerator; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { this.enumerator = enumerator; } public void Dispose() { } public bool MoveNext() { return enumerator.MoveNext(); } public KeyValue<object, object> Current { get { return new KeyValue<object, object>(enumerator.Key, enumerator.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { enumerator.Reset(); } } public class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>> { IEnumerator<KeyValuePair<K, V>> enumerator; public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator) { this.enumerator = enumerator; } public void Dispose() { } public bool MoveNext() { return enumerator.MoveNext(); } public KeyValue<K, V> Current { get { KeyValuePair<K, V> current = enumerator.Current; return new KeyValue<K, V>(current.Key, current.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { enumerator.Reset(); } } } }
using System; using System.Collections.Generic; namespace ClosedXML.Excel { public enum XLPageOrientation { Default, Portrait, Landscape } public enum XLPaperSize { LetterPaper = 1, LetterSmallPaper = 2, TabloidPaper = 3, LedgerPaper = 4, LegalPaper = 5, StatementPaper = 6, ExecutivePaper = 7, A3Paper = 8, A4Paper = 9, A4SmallPaper = 10, A5Paper = 11, B4Paper = 12, B5Paper = 13, FolioPaper = 14, QuartoPaper = 15, StandardPaper = 16, StandardPaper1 = 17, NotePaper = 18, No9Envelope = 19, No10Envelope = 20, No11Envelope = 21, No12Envelope = 22, No14Envelope = 23, CPaper = 24, DPaper = 25, EPaper = 26, DlEnvelope = 27, C5Envelope = 28, C3Envelope = 29, C4Envelope = 30, C6Envelope = 31, C65Envelope = 32, B4Envelope = 33, B5Envelope = 34, B6Envelope = 35, ItalyEnvelope = 36, MonarchEnvelope = 37, No634Envelope = 38, UsStandardFanfold = 39, GermanStandardFanfold = 40, GermanLegalFanfold = 41, IsoB4 = 42, JapaneseDoublePostcard = 43, StandardPaper2 = 44, StandardPaper3 = 45, StandardPaper4 = 46, InviteEnvelope = 47, LetterExtraPaper = 50, LegalExtraPaper = 51, TabloidExtraPaper = 52, A4ExtraPaper = 53, LetterTransversePaper = 54, A4TransversePaper = 55, LetterExtraTransversePaper = 56, SuperaSuperaA4Paper = 57, SuperbSuperbA3Paper = 58, LetterPlusPaper = 59, A4PlusPaper = 60, A5TransversePaper = 61, JisB5TransversePaper = 62, A3ExtraPaper = 63, A5ExtraPaper = 64, IsoB5ExtraPaper = 65, A2Paper = 66, A3TransversePaper = 67, A3ExtraTransversePaper = 68 } public enum XLPageOrderValues { DownThenOver, OverThenDown } public enum XLShowCommentsValues { None, AtEnd, AsDisplayed } public enum XLPrintErrorValues { Blank, Dash, Displayed, NA } public interface IXLPageSetup { /// <summary> /// Gets an object to manage the print areas of the worksheet. /// </summary> IXLPrintAreas PrintAreas { get; } /// <summary> /// Gets the first row that will repeat on the top of the printed pages. /// <para>Use SetRowsToRepeatAtTop() to set the rows that will be repeated on the top of the printed pages.</para> /// </summary> Int32 FirstRowToRepeatAtTop { get; } /// <summary> /// Gets the last row that will repeat on the top of the printed pages. /// <para>Use SetRowsToRepeatAtTop() to set the rows that will be repeated on the top of the printed pages.</para> /// </summary> Int32 LastRowToRepeatAtTop { get; } /// <summary> /// Sets the rows to repeat on the top of the printed pages. /// </summary> /// <param name="range">The range of rows to repeat on the top of the printed pages.</param> void SetRowsToRepeatAtTop(String range); /// <summary> /// Sets the rows to repeat on the top of the printed pages. /// </summary> /// <param name="firstRowToRepeatAtTop">The first row to repeat at top.</param> /// <param name="lastRowToRepeatAtTop">The last row to repeat at top.</param> void SetRowsToRepeatAtTop(Int32 firstRowToRepeatAtTop, Int32 lastRowToRepeatAtTop); /// <summary>Gets the first column to repeat on the left of the printed pages.</summary> /// <value>The first column to repeat on the left of the printed pages.</value> Int32 FirstColumnToRepeatAtLeft { get; } /// <summary>Gets the last column to repeat on the left of the printed pages.</summary> /// <value>The last column to repeat on the left of the printed pages.</value> Int32 LastColumnToRepeatAtLeft { get; } /// <summary> /// Sets the rows to repeat on the left of the printed pages. /// </summary> /// <param name="firstColumnToRepeatAtLeft">The first column to repeat at left.</param> /// <param name="lastColumnToRepeatAtLeft">The last column to repeat at left.</param> void SetColumnsToRepeatAtLeft(Int32 firstColumnToRepeatAtLeft, Int32 lastColumnToRepeatAtLeft); /// <summary> /// Sets the rows to repeat on the left of the printed pages. /// </summary> /// <param name="range">The range of rows to repeat on the left of the printed pages.</param> void SetColumnsToRepeatAtLeft(String range); /// <summary>Gets or sets the page orientation for printing.</summary> /// <value>The page orientation.</value> XLPageOrientation PageOrientation { get; set; } /// <summary> /// Gets or sets the number of pages wide (horizontal) the worksheet will be printed on. /// <para>If you don't specify the PagesTall, Excel will adjust that value</para> /// <para>based on the contents of the worksheet and the PagesWide number.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> Int32 PagesWide { get; set; } /// <summary> /// Gets or sets the number of pages tall (vertical) the worksheet will be printed on. /// <para>If you don't specify the PagesWide, Excel will adjust that value</para> /// <para>based on the contents of the worksheet and the PagesTall number.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> Int32 PagesTall { get; set; } /// <summary> /// Gets or sets the scale at which the worksheet will be printed. /// <para>The worksheet will be printed on as many pages as necessary to print at the given scale.</para> /// <para>Setting this value will override the PagesWide and PagesTall values.</para> /// </summary> Int32 Scale { get; set; } /// <summary> /// Gets or sets the horizontal dpi for printing the worksheet. /// </summary> Int32 HorizontalDpi { get; set; } /// <summary> /// Gets or sets the vertical dpi for printing the worksheet. /// </summary> Int32 VerticalDpi { get; set; } /// <summary> /// Gets or sets the page number that will begin the printout. /// <para>For example, the first page of your printout could be numbered page 5.</para> /// </summary> Int64 FirstPageNumber { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be centered on the page horizontally. /// </summary> /// <value> /// <c>true</c> if the worksheet will be centered on the page horizontally; otherwise, <c>false</c>. /// </value> Boolean CenterHorizontally { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be centered on the page vertically. /// </summary> /// <value> /// <c>true</c> if the worksheet will be centered on the page vartically; otherwise, <c>false</c>. /// </value> Boolean CenterVertically { get; set; } /// <summary> /// Sets the scale at which the worksheet will be printed. This is equivalent to setting the Scale property. /// <para>The worksheet will be printed on as many pages as necessary to print at the given scale.</para> /// <para>Setting this value will override the PagesWide and PagesTall values.</para> /// </summary> /// <param name="percentageOfNormalSize">The scale at which the worksheet will be printed.</param> void AdjustTo(Int32 percentageOfNormalSize); /// <summary> /// Gets or sets the number of pages the worksheet will be printed on. /// <para>This is equivalent to setting both PagesWide and PagesTall properties.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> /// <param name="pagesWide">The pages wide.</param> /// <param name="pagesTall">The pages tall.</param> void FitToPages(Int32 pagesWide, Int32 pagesTall); /// <summary> /// Gets or sets the size of the paper to print the worksheet. /// </summary> XLPaperSize PaperSize { get; set; } /// <summary> /// Gets an object to work with the page margins. /// </summary> IXLMargins Margins { get; } /// <summary> /// Gets an object to work with the page headers. /// </summary> IXLHeaderFooter Header { get; } /// <summary> /// Gets an object to work with the page footers. /// </summary> IXLHeaderFooter Footer { get; } /// <summary> /// Gets or sets a value indicating whether Excel will automatically adjust the font size to the scale of the worksheet. /// </summary> /// <value> /// <c>true</c> if Excel will automatically adjust the font size to the scale of the worksheet; otherwise, <c>false</c>. /// </value> Boolean ScaleHFWithDocument { get; set; } /// <summary> /// Gets or sets a value indicating whether the header and footer margins are aligned with the left and right margins of the worksheet. /// </summary> /// <value> /// <c>true</c> if the header and footer margins are aligned with the left and right margins of the worksheet; otherwise, <c>false</c>. /// </value> Boolean AlignHFWithMargins { get; set; } /// <summary> /// Gets or sets a value indicating whether the gridlines will be printed. /// </summary> /// <value> /// <c>true</c> if the gridlines will be printed; otherwise, <c>false</c>. /// </value> Boolean ShowGridlines { get; set; } /// <summary> /// Gets or sets a value indicating whether to show row numbers and column letters/numbers. /// </summary> /// <value> /// <c>true</c> to show row numbers and column letters/numbers; otherwise, <c>false</c>. /// </value> Boolean ShowRowAndColumnHeadings { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be printed in black and white. /// </summary> /// <value> /// <c>true</c> if the worksheet will be printed in black and white; otherwise, <c>false</c>. /// </value> Boolean BlackAndWhite { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be printed in draft quality. /// </summary> /// <value> /// <c>true</c> if the worksheet will be printed in draft quality; otherwise, <c>false</c>. /// </value> Boolean DraftQuality { get; set; } /// <summary> /// Gets or sets the page order for printing. /// </summary> XLPageOrderValues PageOrder { get; set; } /// <summary> /// Gets or sets how the comments will be printed. /// </summary> XLShowCommentsValues ShowComments { get; set; } /// <summary> /// Gets a list with the row breaks (for printing). /// </summary> List<Int32> RowBreaks { get; } /// <summary> /// Gets a list with the column breaks (for printing). /// </summary> List<Int32> ColumnBreaks { get; } /// <summary> /// Adds a horizontal page break after the given row. /// </summary> /// <param name="row">The row to insert the break.</param> void AddHorizontalPageBreak(Int32 row); /// <summary> /// Adds a vertical page break after the given column. /// </summary> /// <param name="column">The column to insert the break.</param> void AddVerticalPageBreak(Int32 column); /// <summary> /// Gets or sets how error values will be printed. /// </summary> XLPrintErrorValues PrintErrorValue { get; set; } IXLPageSetup SetPageOrientation(XLPageOrientation value); IXLPageSetup SetPagesWide(Int32 value); IXLPageSetup SetPagesTall(Int32 value); IXLPageSetup SetScale(Int32 value); IXLPageSetup SetHorizontalDpi(Int32 value); IXLPageSetup SetVerticalDpi(Int32 value); IXLPageSetup SetFirstPageNumber(Int64 value); IXLPageSetup SetCenterHorizontally(); IXLPageSetup SetCenterHorizontally(Boolean value); IXLPageSetup SetCenterVertically(); IXLPageSetup SetCenterVertically(Boolean value); IXLPageSetup SetPaperSize(XLPaperSize value); IXLPageSetup SetScaleHFWithDocument(); IXLPageSetup SetScaleHFWithDocument(Boolean value); IXLPageSetup SetAlignHFWithMargins(); IXLPageSetup SetAlignHFWithMargins(Boolean value); IXLPageSetup SetShowGridlines(); IXLPageSetup SetShowGridlines(Boolean value); IXLPageSetup SetShowRowAndColumnHeadings(); IXLPageSetup SetShowRowAndColumnHeadings(Boolean value); IXLPageSetup SetBlackAndWhite(); IXLPageSetup SetBlackAndWhite(Boolean value); IXLPageSetup SetDraftQuality(); IXLPageSetup SetDraftQuality(Boolean value); IXLPageSetup SetPageOrder(XLPageOrderValues value); IXLPageSetup SetShowComments(XLShowCommentsValues value); IXLPageSetup SetPrintErrorValue(XLPrintErrorValues value); Boolean DifferentFirstPageOnHF { get; set; } IXLPageSetup SetDifferentFirstPageOnHF(); IXLPageSetup SetDifferentFirstPageOnHF(Boolean value); Boolean DifferentOddEvenPagesOnHF { get; set; } IXLPageSetup SetDifferentOddEvenPagesOnHF(); IXLPageSetup SetDifferentOddEvenPagesOnHF(Boolean value); } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Security.Principal; using EventStore.Common.Log; using EventStore.Core.Bus; using EventStore.Core.Helpers; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Messages.ParallelQueryProcessingMessages; using EventStore.Projections.Core.Utils; namespace EventStore.Projections.Core.Services.Processing { //TODO: replace Console.WriteLine with logging //TODO: separate check-pointing from projection handling public class CoreProjection : IDisposable, ICoreProjection, ICoreProjectionForProcessingPhase, IHandle<CoreProjectionManagementMessage.GetState>, IHandle<CoreProjectionManagementMessage.GetResult>, IHandle<ProjectionManagementMessage.SlaveProjectionsStarted> { [Flags] private enum State : uint { Initial = 0x80000000, StartSlaveProjectionsRequested = 0x1, LoadStateRequested = 0x2, StateLoaded = 0x4, Subscribed = 0x8, Running = 0x10, Stopping = 0x40, Stopped = 0x80, FaultedStopping = 0x100, Faulted = 0x200, CompletingPhase = 0x400, PhaseCompleted = 0x800, } private readonly string _name; private readonly ProjectionVersion _version; private readonly IPublisher _publisher; private readonly ProjectionProcessingStrategy _projectionProcessingStrategy; internal readonly Guid _projectionCorrelationId; private readonly IPublisher _inputQueue; private readonly IPrincipal _runAs; private readonly ILogger _logger; private State _state; private string _faultedReason; private readonly PartitionStateCache _partitionStateCache; private ICoreProjectionCheckpointManager _checkpointManager; private readonly ICoreProjectionCheckpointReader _checkpointReader; private readonly bool _isSlaveProjection; private bool _tickPending; private bool _startOnLoad; private bool _completed; private CheckpointSuggestedWorkItem _checkpointSuggestedWorkItem; private IProjectionProcessingPhase _projectionProcessingPhase; private readonly bool _stopOnEof; private readonly IProjectionProcessingPhase[] _projectionProcessingPhases; private readonly CoreProjectionCheckpointWriter _coreProjectionCheckpointWriter; private readonly bool _requiresRootPartition; private readonly Action<ProjectionStatistics> _enrichStatistics; private SlaveProjectionCommunicationChannels _slaveProjections; //NOTE: this is only for slave projections (TBD) public CoreProjection( ProjectionProcessingStrategy projectionProcessingStrategy, ProjectionVersion version, Guid projectionCorrelationId, IPublisher inputQueue, IPrincipal runAs, IPublisher publisher, IODispatcher ioDispatcher, ReaderSubscriptionDispatcher subscriptionDispatcher, ILogger logger, ProjectionNamesBuilder namingBuilder, CoreProjectionCheckpointWriter coreProjectionCheckpointWriter, PartitionStateCache partitionStateCache, string effectiveProjectionName, ITimeProvider timeProvider, bool isSlaveProjection) { if (publisher == null) throw new ArgumentNullException("publisher"); if (ioDispatcher == null) throw new ArgumentNullException("ioDispatcher"); if (subscriptionDispatcher == null) throw new ArgumentNullException("subscriptionDispatcher"); _projectionProcessingStrategy = projectionProcessingStrategy; _projectionCorrelationId = projectionCorrelationId; _inputQueue = inputQueue; _runAs = runAs; _name = effectiveProjectionName; _version = version; _stopOnEof = projectionProcessingStrategy.GetStopOnEof(); _logger = logger; _publisher = publisher; _partitionStateCache = partitionStateCache; _requiresRootPartition = projectionProcessingStrategy.GetRequiresRootPartition(); _isSlaveProjection = isSlaveProjection; var useCheckpoints = projectionProcessingStrategy.GetUseCheckpoints(); _coreProjectionCheckpointWriter = coreProjectionCheckpointWriter; _projectionProcessingPhases = projectionProcessingStrategy.CreateProcessingPhases( publisher, projectionCorrelationId, partitionStateCache, UpdateStatistics, this, namingBuilder, timeProvider, ioDispatcher, coreProjectionCheckpointWriter); //NOTE: currently assuming the first checkpoint manager to be able to load any state _checkpointReader = new CoreProjectionCheckpointReader( publisher, _projectionCorrelationId, ioDispatcher, namingBuilder.MakeCheckpointStreamName(), _version, useCheckpoints); _enrichStatistics = projectionProcessingStrategy.EnrichStatistics; GoToState(State.Initial); } private void BeginPhase(IProjectionProcessingPhase processingPhase, CheckpointTag startFrom) { _projectionProcessingPhase = processingPhase; _projectionProcessingPhase.SetProjectionState(PhaseState.Starting); _checkpointManager = processingPhase.CheckpointManager; _projectionProcessingPhase.InitializeFromCheckpoint(startFrom); _checkpointManager.Start(startFrom); } internal void UpdateStatistics() { var info = new ProjectionStatistics(); GetStatistics(info); _publisher.Publish( new CoreProjectionManagementMessage.StatisticsReport(_projectionCorrelationId, info)); } public void Start() { EnsureState(State.Initial); _startOnLoad = true; var slaveProjectionDefinitions = _projectionProcessingStrategy.GetSlaveProjections(); if (slaveProjectionDefinitions != null) { GoToState(State.StartSlaveProjectionsRequested); } else { GoToState(State.LoadStateRequested); } } public void LoadStopped() { _startOnLoad = false; EnsureState(State.Initial); GoToState(State.LoadStateRequested); } public void Stop() { EnsureState( State.LoadStateRequested | State.StateLoaded | State.Subscribed | State.Running | State.PhaseCompleted | State.CompletingPhase); try { if (_state == State.LoadStateRequested || _state == State.PhaseCompleted) GoToState(State.Stopped); else GoToState(State.Stopping); } catch (Exception ex) { SetFaulted(ex); } } public void Kill() { SetFaulted("Killed"); } private void GetStatistics(ProjectionStatistics info) { _checkpointManager.GetStatistics(info); if (float.IsNaN(info.Progress) || float.IsNegativeInfinity(info.Progress) || float.IsPositiveInfinity(info.Progress)) { info.Progress = -2.0f; } info.Status = _state.EnumValueName() + info.Status; info.Name = _name; info.EffectiveName = _name; info.ProjectionId = _version.ProjectionId; info.Epoch = _version.Epoch; info.Version = _version.Version; info.StateReason = ""; info.BufferedEvents = 0; info.PartitionsCached = _partitionStateCache.CachedItemCount; _enrichStatistics(info); if (_projectionProcessingPhase != null) _projectionProcessingPhase.GetStatistics(info); } public void CompletePhase() { if (_state != State.Running) return; if (!_stopOnEof) throw new InvalidOperationException("!_projectionConfig.StopOnEof"); _completed = true; _checkpointManager.Progress(100.0f); GoToState(State.CompletingPhase); } public void Handle(CoreProjectionManagementMessage.GetState message) { if (_state == State.LoadStateRequested || _state == State.StateLoaded) { message.Envelope.ReplyWith( new CoreProjectionManagementMessage.StateReport( message.CorrelationId, _projectionCorrelationId, message.Partition, state: null, position: null, exception: new Exception("Not yet available"))); return; } EnsureState( State.Running | State.Stopping | State.Stopped | State.FaultedStopping | State.Faulted | State.CompletingPhase | State.PhaseCompleted); _projectionProcessingPhase.Handle(message); } public void Handle(CoreProjectionManagementMessage.GetResult message) { if (_state == State.LoadStateRequested || _state == State.StateLoaded) { message.Envelope.ReplyWith( new CoreProjectionManagementMessage.ResultReport( message.CorrelationId, _projectionCorrelationId, message.Partition, result: null, position: null, exception: new Exception("Not yet available"))); return; } EnsureState( State.Running | State.Stopping | State.Stopped | State.FaultedStopping | State.Faulted | State.CompletingPhase | State.PhaseCompleted); _projectionProcessingPhase.Handle(message); } public void Handle(CoreProjectionProcessingMessage.CheckpointCompleted message) { CheckpointCompleted(message.CheckpointTag); } public void Handle(CoreProjectionProcessingMessage.CheckpointLoaded message) { EnsureState(State.LoadStateRequested); try { var checkpointTag = message.CheckpointTag; var phase = checkpointTag == null ? 0 : checkpointTag.Phase; var projectionProcessingPhase = _projectionProcessingPhases[phase]; if (checkpointTag == null) checkpointTag = projectionProcessingPhase.MakeZeroCheckpointTag(); checkpointTag = projectionProcessingPhase.AdjustTag(checkpointTag); //TODO: initialize projection state here (test it) //TODO: write test to ensure projection state is correctly loaded from a checkpoint and posted back when enough empty records processed //TODO: handle errors _coreProjectionCheckpointWriter.StartFrom(checkpointTag, message.CheckpointEventNumber); if (_requiresRootPartition) _partitionStateCache.CacheAndLockPartitionState("", PartitionState.Deserialize(message.CheckpointData, checkpointTag), null); BeginPhase(projectionProcessingPhase, checkpointTag); GoToState(State.StateLoaded); if (_startOnLoad) { if (_slaveProjections != null) _projectionProcessingPhase.AssignSlaves(_slaveProjections); _projectionProcessingPhase.Subscribe(checkpointTag, fromCheckpoint: true); } else GoToState(State.Stopped); } catch (Exception ex) { SetFaulted(ex); } } public void Handle(CoreProjectionProcessingMessage.PrerecordedEventsLoaded message) { EnsureState(State.StateLoaded); try { _projectionProcessingPhase.Handle(message); } catch (Exception ex) { SetFaulted(ex); } } public void Handle(CoreProjectionProcessingMessage.RestartRequested message) { _logger.Info( "Projection '{0}'({1}) restart has been requested due to: '{2}'", _name, _projectionCorrelationId, message.Reason); if (_state != State.Running) { SetFaulted( string.Format( "A concurrency violation detected, but the projection is not running. Current state is: {0}. The reason for the restart is: '{1}' ", _state, message.Reason)); return; } // EnsureUnsubscribed(); StopSlaveProjections(); GoToState(State.Initial); Start(); } public void Handle(CoreProjectionProcessingMessage.Failed message) { SetFaulted(message.Reason); } public void EnsureUnsubscribed() { if (_projectionProcessingPhase != null) _projectionProcessingPhase.EnsureUnsubscribed(); } private void StopSlaveProjections() { //TODO: encapsulate into StopSlaveProjections message? var slaveProjections = _slaveProjections; if (slaveProjections != null) { _slaveProjections = null; foreach (var group in slaveProjections.Channels) { foreach (var channel in group.Value) { _publisher.Publish( new ProjectionManagementMessage.Delete( new NoopEnvelope(), channel.ManagedProjectionName, ProjectionManagementMessage.RunAs.System, true, true)); } } } } private void GoToState(State state) { var wasStopped = _state == State.Stopped || _state == State.Faulted || _state == State.PhaseCompleted; var wasStopping = _state == State.Stopping || _state == State.FaultedStopping || _state == State.CompletingPhase; var wasStarting = _state == State.LoadStateRequested || _state == State.StateLoaded || _state == State.Subscribed; var wasStarted = _state == State.Subscribed || _state == State.Running || _state == State.Stopping || _state == State.FaultedStopping || _state == State.CompletingPhase; var wasRunning = _state == State.Running; var wasFaulted = _state == State.Faulted || _state == State.FaultedStopping; _state = state; // set state before transition to allow further state change switch (state) { case State.Stopped: case State.Faulted: case State.PhaseCompleted: if (wasStarted && !wasStopped) _checkpointManager.Stopped(); break; case State.Stopping: case State.FaultedStopping: case State.CompletingPhase: if (wasStarted && !wasStopping) _checkpointManager.Stopping(); break; } if (_projectionProcessingPhase != null) // null while loading state switch (state) { case State.LoadStateRequested: case State.StateLoaded: case State.Subscribed: if (!wasStarting) _projectionProcessingPhase.SetProjectionState(PhaseState.Starting); break; case State.Running: if (!wasRunning) _projectionProcessingPhase.SetProjectionState(PhaseState.Running); break; case State.Faulted: case State.FaultedStopping: if (wasRunning) _projectionProcessingPhase.SetProjectionState(PhaseState.Stopped); break; case State.Stopped: case State.Stopping: case State.CompletingPhase: case State.PhaseCompleted: if (wasRunning) _projectionProcessingPhase.SetProjectionState(PhaseState.Stopped); break; default: _projectionProcessingPhase.SetProjectionState(PhaseState.Unknown); break; } switch (state) { case State.Initial: EnterInitial(); break; case State.StartSlaveProjectionsRequested: EnterStartSlaveProjectionsRequested(); break; case State.LoadStateRequested: EnterLoadStateRequested(); break; case State.StateLoaded: EnterStateLoaded(); break; case State.Subscribed: EnterSubscribed(); break; case State.Running: EnterRunning(); break; case State.Stopping: EnterStopping(); break; case State.Stopped: EnterStopped(); break; case State.FaultedStopping: EnterFaultedStopping(); break; case State.Faulted: EnterFaulted(); break; case State.CompletingPhase: EnterCompletingPhase(); break; case State.PhaseCompleted: EnterPhaseCompleted(); break; default: throw new Exception(); } UpdateStatistics(); } private void EnterInitial() { _completed = false; _partitionStateCache.Initialize(); _projectionProcessingPhase = null; _checkpointManager = _projectionProcessingPhases[0].CheckpointManager; _checkpointManager.Initialize(); _checkpointReader.Initialize(); _tickPending = false; if (_requiresRootPartition) _partitionStateCache.CacheAndLockPartitionState("", new PartitionState("", null, CheckpointTag.Empty), null); // NOTE: this is to workaround exception in GetState requests submitted by client } private void EnterStartSlaveProjectionsRequested() { _publisher.Publish(new ProjectionManagementMessage.StartSlaveProjections( new PublishEnvelope(_inputQueue), new ProjectionManagementMessage.RunAs(_runAs), _name, _projectionProcessingStrategy.GetSlaveProjections(), _inputQueue, _projectionCorrelationId)); } private void EnterLoadStateRequested() { _checkpointReader.BeginLoadState(); } private void EnterStateLoaded() { } private void EnterSubscribed() { if (_startOnLoad) { GoToState(State.Running); } else GoToState(State.Stopped); } private void EnterRunning() { try { _publisher.Publish( new CoreProjectionManagementMessage.Started(_projectionCorrelationId)); _projectionProcessingPhase.ProcessEvent(); } catch (Exception ex) { SetFaulted(ex); } } private void EnterStopping() { EnsureUnsubscribed(); } private void EnterStopped() { EnsureUnsubscribed(); StopSlaveProjections(); _publisher.Publish(new CoreProjectionManagementMessage.Stopped(_projectionCorrelationId, _completed)); } private void EnterFaultedStopping() { EnsureUnsubscribed(); } private void EnterFaulted() { EnsureUnsubscribed(); StopSlaveProjections(); _publisher.Publish( new CoreProjectionManagementMessage.Faulted(_projectionCorrelationId, _faultedReason)); } private void EnterCompletingPhase() { } private void EnterPhaseCompleted() { var completedPhaseIndex = _checkpointManager.LastProcessedEventPosition.Phase; if (completedPhaseIndex == _projectionProcessingPhases.Length - 1) { Stop(); } else { var nextPhase = _projectionProcessingPhases[completedPhaseIndex + 1]; var nextPhaseZeroPosition = nextPhase.MakeZeroCheckpointTag(); BeginPhase(nextPhase, nextPhaseZeroPosition); if (_slaveProjections != null) _projectionProcessingPhase.AssignSlaves(_slaveProjections); _projectionProcessingPhase.Subscribe(nextPhaseZeroPosition, fromCheckpoint: false); } } private void EnsureState(State expectedStates) { if ((_state & expectedStates) == 0) { throw new Exception( string.Format("Current state is {0}. Expected states are: {1}", _state, expectedStates)); } } private void Tick() { // ignore any ticks received when not pending. this may happen when restart requested if (!_tickPending) return; // process messages in almost all states as we now ignore work items when processing EnsureState( State.Running | State.Stopping | State.Stopped | State.FaultedStopping | State.Faulted | State.CompletingPhase | State.PhaseCompleted); try { _tickPending = false; _projectionProcessingPhase.ProcessEvent(); } catch (Exception ex) { SetFaulted(ex); } } public void Dispose() { EnsureUnsubscribed(); StopSlaveProjections(); if (_projectionProcessingPhase != null) _projectionProcessingPhase.Dispose(); } public void EnsureTickPending() { // ticks are requested when an async operation is completed or when an item is being processed // thus, the tick message is removed from the queue when it does not process any work item (and // it is renewed therefore) if (_tickPending) return; _tickPending = true; _publisher.Publish(new ProjectionCoreServiceMessage.CoreTick(Tick)); } public void SetFaulted(Exception ex) { SetFaulted(ex.Message); } public void SetFaulted(string reason) { if (_state != State.FaultedStopping && _state != State.Faulted) _faultedReason = reason; if (_state != State.Faulted) GoToState(State.Faulted); } public void SetFaulting(string reason) { if (_state != State.FaultedStopping && _state != State.Faulted) { _faultedReason = reason; GoToState(State.FaultedStopping); } } private void CheckpointCompleted(CheckpointTag lastCompletedCheckpointPosition) { CompleteCheckpointSuggestedWorkItem(); // all emitted events caused by events before the checkpoint position have been written // unlock states, so the cache can be clean up as they can now be safely reloaded from the ES _partitionStateCache.Unlock(lastCompletedCheckpointPosition); switch (_state) { case State.Stopping: GoToState(State.Stopped); break; case State.FaultedStopping: GoToState(State.Faulted); break; case State.CompletingPhase: GoToState(State.PhaseCompleted); break; } } public void SetCurrentCheckpointSuggestedWorkItem(CheckpointSuggestedWorkItem checkpointSuggestedWorkItem) { if (_checkpointSuggestedWorkItem != null && checkpointSuggestedWorkItem != null) throw new InvalidOperationException("Checkpoint in progress"); if (_checkpointSuggestedWorkItem == null && checkpointSuggestedWorkItem == null) throw new InvalidOperationException("No checkpoint in progress"); _checkpointSuggestedWorkItem = checkpointSuggestedWorkItem; } private void CompleteCheckpointSuggestedWorkItem() { var workItem = _checkpointSuggestedWorkItem; if (workItem != null) { _checkpointSuggestedWorkItem = null; workItem.CheckpointCompleted(); EnsureTickPending(); } } public CheckpointTag LastProcessedEventPosition { get { return _checkpointManager.LastProcessedEventPosition; } } public void Subscribed() { GoToState(State.Subscribed); } public void Handle(ProjectionManagementMessage.SlaveProjectionsStarted message) { _slaveProjections = message.SlaveProjections; GoToState(State.LoadStateRequested); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Baseline; using LamarCodeGeneration; using Marten.Internal; using Marten.Internal.Linq; using Marten.Internal.Operations; using Marten.Internal.Storage; using Marten.Linq; using Marten.Linq.Fields; using Marten.Schema; using Marten.Schema.Identity; using Marten.Services; using Marten.Storage; using Marten.Util; using Npgsql; using NpgsqlTypes; using Remotion.Linq; namespace Marten.Events { public abstract class EventMapping: IDocumentMapping, IQueryableDocument { protected readonly EventGraph _parent; protected readonly DocumentMapping _inner; protected EventMapping(EventGraph parent, Type eventType) { _parent = parent; DocumentType = eventType; EventTypeName = eventType.IsGenericType ? eventType.ShortNameInCode() : DocumentType.Name.ToTableAlias(); IdMember = DocumentType.GetProperty(nameof(IEvent.Id)); _inner = new DocumentMapping(eventType, parent.Options); } public IDocumentMapping Root => this; public Type DocumentType { get; } public string EventTypeName { get; set; } public string Alias => EventTypeName; public MemberInfo IdMember { get; } public NpgsqlDbType IdType { get; } = NpgsqlDbType.Uuid; public TenancyStyle TenancyStyle { get; } = TenancyStyle.Single; Type IDocumentMapping.IdType => typeof(Guid); public DbObjectName Table => new DbObjectName(_parent.DatabaseSchemaName, "mt_events"); public DuplicatedField[] DuplicatedFields { get; } public DeleteStyle DeleteStyle { get; } public PropertySearching PropertySearching { get; } = PropertySearching.JSON_Locator_Only; public string[] SelectFields() { return new[] { "id", "data" }; } public IField FieldFor(Expression expression) { return FieldFor(FindMembers.Determine(expression)); } public IField FieldFor(IEnumerable<MemberInfo> members) { return _inner.FieldFor(members); } public IField FieldFor(MemberInfo member) { return _inner.FieldFor(member); } public IField FieldFor(string memberName) { throw new NotSupportedException(); } public IWhereFragment FilterDocuments(QueryModel model, IWhereFragment query) { return new CompoundWhereFragment("and", DefaultWhereFragment(), query); } public IWhereFragment DefaultWhereFragment() { return new WhereFragment($"d.type = '{EventTypeName}'"); } public void DeleteAllDocuments(ITenant factory) { factory.RunSql($"delete from mt_events where type = '{Alias}'"); } public IdAssignment<T> ToIdAssignment<T>(ITenant tenant) { throw new NotSupportedException(); } public IQueryableDocument ToQueryableDocument() { return this; } } public class EventMapping<T>: EventMapping, IDocumentStorage<T> where T : class { private readonly string _tableName; private Type _idType; public EventMapping(EventGraph parent) : base(parent, typeof(T)) { var schemaName = parent.DatabaseSchemaName; _tableName = schemaName == StoreOptions.DefaultDatabaseSchemaName ? "mt_events" : $"{schemaName}.mt_events"; _idType = parent.StreamIdentity == StreamIdentity.AsGuid ? typeof(Guid) : typeof(string); } public bool UseOptimisticConcurrency { get; } = false; string ISelectClause.FromObject => _tableName; Type ISelectClause.SelectedType => typeof(T); void ISelectClause.WriteSelectClause(CommandBuilder sql) { sql.Append("select data from "); sql.Append(_tableName); sql.Append(" as d"); } ISelector ISelectClause.BuildSelector(IMartenSession session) { return new EventSelector<T>(session.Serializer); } IQueryHandler<TResult> ISelectClause.BuildHandler<TResult>(IMartenSession session, Statement topStatement, Statement currentStatement) { var selector = new EventSelector<T>(session.Serializer); return LinqHandlerBuilder.BuildHandler<T, TResult>(selector, topStatement); } internal class EventSelector<TEvent>: ISelector<TEvent> { private readonly ISerializer _serializer; public EventSelector(ISerializer serializer) { _serializer = serializer; } public TEvent Resolve(DbDataReader reader) { using var json = reader.GetTextReader(0); return _serializer.FromJson<TEvent>(json); } public Task<TEvent> ResolveAsync(DbDataReader reader, CancellationToken token) { using var json = reader.GetTextReader(0); var doc = _serializer.FromJson<TEvent>(json); return Task.FromResult(doc); } } ISelectClause ISelectClause.UseStatistics(QueryStatistics statistics) { throw new NotSupportedException(); } Type IDocumentStorage.SourceType => typeof(IEvent); IFieldMapping IDocumentStorage.Fields => this; IQueryableDocument IDocumentStorage.QueryableDocument => this; object IDocumentStorage<T>.IdentityFor(T document) { throw new NotSupportedException(); } Type IDocumentStorage.IdType => _idType; Guid? IDocumentStorage<T>.VersionFor(T document, IMartenSession session) { throw new NotSupportedException(); } void IDocumentStorage<T>.Store(IMartenSession session, T document) { throw new NotSupportedException(); } void IDocumentStorage<T>.Store(IMartenSession session, T document, Guid? version) { throw new NotSupportedException(); } void IDocumentStorage<T>.Eject(IMartenSession session, T document) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.Update(T document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.Insert(T document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.Upsert(T document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.Overwrite(T document, IMartenSession session, ITenant tenant) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.DeleteForDocument(T document) { throw new NotSupportedException(); } IStorageOperation IDocumentStorage<T>.DeleteForWhere(IWhereFragment @where) { throw new NotSupportedException(); } void IDocumentStorage<T>.EjectById(IMartenSession session, object id) { // Nothing } void IDocumentStorage<T>.RemoveDirtyTracker(IMartenSession session, object id) { // Nothing } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata.Ecma335 { internal class NamespaceCache { private readonly MetadataReader _metadataReader; private readonly object _namespaceTableAndListLock = new object(); private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable; private NamespaceData _rootNamespace; private ImmutableArray<NamespaceDefinitionHandle> _namespaceList; private uint _virtualNamespaceCounter; internal NamespaceCache(MetadataReader reader) { Debug.Assert(reader != null); _metadataReader = reader; } /// <summary> /// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method /// on this will probably have a very high amount of overhead. /// </summary> internal bool CacheIsRealized { get { return _namespaceTable != null; } } internal string GetFullName(NamespaceDefinitionHandle handle) { Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case. NamespaceData data = GetNamespaceData(handle); return data.FullName; } internal NamespaceData GetRootNamespace() { EnsureNamespaceTableIsPopulated(); Debug.Assert(_rootNamespace != null); return _rootNamespace; } internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) { EnsureNamespaceTableIsPopulated(); NamespaceData result; if (!_namespaceTable.TryGetValue(handle, out result)) { Throw.InvalidHandle(); } return result; } /// <summary> /// This will return a StringHandle for the simple name of a namespace name at the given segment index. /// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number /// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace /// name between dots. /// /// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle': /// /// reader.GetString(GetSimpleName(handle)) == "Test" /// reader.GetString(GetSimpleName(handle, 0)) == "System" /// reader.GetString(GetSimpleName(handle, 1)) == "Collections" /// reader.GetString(GetSimpleName(handle, 2)) == "Generic" /// reader.GetString(GetSimpleName(handle, 3)) == "Test" /// reader.GetString(GetSimpleName(handle, 1000)) == "Test" /// </summary> private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue) { StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName(); Debug.Assert(!handleContainingSegment.IsVirtual); int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1; int currentSegment = 0; while (currentSegment < segmentIndex) { int currentIndex = _metadataReader.StringStream.IndexOfRaw(lastFoundIndex + 1, '.'); if (currentIndex == -1) { break; } lastFoundIndex = currentIndex; ++currentSegment; } Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0); // + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way, // we want the next char. int resultIndex = lastFoundIndex + 1; return StringHandle.FromOffset(resultIndex).WithDotTermination(); } /// <summary> /// Two distinct namespace handles represent the same namespace if their full names are the same. This /// method merges builders corresponding to such namespace handles. /// </summary> private void PopulateNamespaceTable() { lock (_namespaceTableAndListLock) { if (_namespaceTable != null) { return; } var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>(); // Make sure to add entry for root namespace. The root namespace is special in that even // though it might not have types of its own it always has an equivalent representation // as a nil handle and we don't want to handle it below as dot-terminated virtual namespace. // We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so // that we never hand back a handle to the user that doesn't have a typeid as that prevents // round-trip conversion to Handle and back. (We may discover other handle aliases for the // root namespace (any nil/empty string will do), but we need this one to always be there. NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromFullNameOffset(0); namespaceBuilderTable.Add( rootNamespace, new NamespaceDataBuilder( rootNamespace, rootNamespace.GetFullName(), String.Empty)); PopulateTableWithTypeDefinitions(namespaceBuilderTable); PopulateTableWithExportedTypes(namespaceBuilderTable); Dictionary<string, NamespaceDataBuilder> stringTable; MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable); List<NamespaceDataBuilder> virtualNamespaces; ResolveParentChildRelationships(stringTable, out virtualNamespaces); var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>(); foreach (var group in namespaceBuilderTable) { // Freeze() caches the result, so any many-to-one relationships // between keys and values will be preserved and efficiently handled. namespaceTable.Add(group.Key, group.Value.Freeze()); } if (virtualNamespaces != null) { foreach (var virtualNamespace in virtualNamespaces) { namespaceTable.Add(virtualNamespace.Handle, virtualNamespace.Freeze()); } } _namespaceTable = namespaceTable; _rootNamespace = namespaceTable[rootNamespace]; } } /// <summary> /// This will take 'table' and merge all of the NamespaceData instances that point to the same /// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it /// back to the caller should the caller want to use it. /// </summary> private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable) { var namespaces = new Dictionary<string, NamespaceDataBuilder>(); List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null; foreach (var group in table) { NamespaceDataBuilder data = group.Value; NamespaceDataBuilder existingRecord; if (namespaces.TryGetValue(data.FullName, out existingRecord)) { // Children should not exist until the next step. Debug.Assert(data.Namespaces.Count == 0); data.MergeInto(existingRecord); if (remaps == null) { remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>(); } remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord)); } else { namespaces.Add(data.FullName, data); } } // Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it. if (remaps != null) { foreach (var tuple in remaps) { table[tuple.Key] = tuple.Value; } } stringTable = namespaces; } /// <summary> /// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle, /// as well as the name provided. /// </summary> private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) { Debug.Assert(realChild.HasFullName); int numberOfSegments = 0; foreach (char c in fullName) { if (c == '.') { numberOfSegments++; } } StringHandle simpleName = GetSimpleName(realChild, numberOfSegments); var namespaceHandle = NamespaceDefinitionHandle.FromVirtualIndex(++_virtualNamespaceCounter); return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); } /// <summary> /// Quick convenience method that handles linking together child + parent /// </summary> private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) { Debug.Assert(child != null && parent != null); Debug.Assert(!child.Handle.IsNil); child.Parent = parent.Handle; parent.Namespaces.Add(child.Handle); } /// <summary> /// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a /// virtual one. This will automatically link any virtual namespaces it creates up to its parents. /// </summary> private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces, NamespaceDataBuilder realChild, ref List<NamespaceDataBuilder> virtualNamespaces) { Debug.Assert(realChild.Handle.HasFullName); string childName = realChild.FullName; var child = realChild; // The condition for this loop is very complex -- essentially, we keep going // until we: // A. Encounter the root namespace as 'child' // B. Find a preexisting namespace as 'parent' while (true) { int lastIndex = childName.LastIndexOf('.'); string parentName; if (lastIndex == -1) { if (childName.Length == 0) { return; } else { parentName = String.Empty; } } else { parentName = childName.Substring(0, lastIndex); } NamespaceDataBuilder parentData; if (existingNamespaces.TryGetValue(parentName, out parentData)) { LinkChildDataToParentData(child, parentData); return; } if (virtualNamespaces != null) { foreach (var data in virtualNamespaces) { if (data.FullName == parentName) { LinkChildDataToParentData(child, data); return; } } } else { virtualNamespaces = new List<NamespaceDataBuilder>(); } var virtualParent = SynthesizeNamespaceData(parentName, realChild.Handle); LinkChildDataToParentData(child, virtualParent); virtualNamespaces.Add(virtualParent); childName = virtualParent.FullName; child = virtualParent; } } /// <summary> /// This will link all parents/children in the given namespaces dictionary up to each other. /// /// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders /// of their own, but do have child namespaces. These are returned via the virtualNamespaces out /// parameter. /// </summary> private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> virtualNamespaces) { virtualNamespaces = null; foreach (var namespaceData in namespaces.Values) { LinkChildToParentNamespace(namespaces, namespaceData, ref virtualNamespaces); } } /// <summary> /// Loops through all type definitions in metadata, adding them to the given table /// </summary> private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var typeHandle in _metadataReader.TypeDefinitions) { TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle); if (type.Attributes.IsNested()) { continue; } NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeHandle); NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.TypeDefinitions.Add(typeHandle); } else { StringHandle name = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName); newData.TypeDefinitions.Add(typeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Loops through all type forwarders in metadata, adding them to the given table /// </summary> private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (exportedType.Implementation.Kind == HandleKind.ExportedType) { continue; // skip nested exported types. } NamespaceDefinitionHandle namespaceHandle = exportedType.NamespaceDefinition; NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.ExportedTypes.Add(exportedTypeHandle); } else { Debug.Assert(namespaceHandle.HasFullName); StringHandle simpleName = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); newData.ExportedTypes.Add(exportedTypeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Populates namespaceList with distinct namespaces. No ordering is guaranteed. /// </summary> private void PopulateNamespaceList() { lock (_namespaceTableAndListLock) { if (_namespaceList != null) { return; } Debug.Assert(_namespaceTable != null); var namespaceNameSet = new HashSet<string>(); var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); foreach (var group in _namespaceTable) { var data = group.Value; if (namespaceNameSet.Add(data.FullName)) { namespaceListBuilder.Add(group.Key); } } _namespaceList = namespaceListBuilder.ToImmutable(); } } /// <summary> /// If the namespace table doesn't exist, populates it! /// </summary> private void EnsureNamespaceTableIsPopulated() { // PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily. if (_namespaceTable == null) { PopulateNamespaceTable(); } Debug.Assert(_namespaceTable != null); } /// <summary> /// If the namespace list doesn't exist, populates it! /// </summary> private void EnsureNamespaceListIsPopulated() { if (_namespaceList == null) { PopulateNamespaceList(); } Debug.Assert(_namespaceList != null); } /// <summary> /// An intermediate class used to build NamespaceData instances. This was created because we wanted to /// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the /// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace /// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles /// and NamespaceData. So, the pointer semantics must be preserved. /// /// This class assumes that the builders will not be modified in any way after the first call to /// Freeze(). /// </summary> private class NamespaceDataBuilder { public readonly NamespaceDefinitionHandle Handle; public readonly StringHandle Name; public readonly string FullName; public NamespaceDefinitionHandle Parent; public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces; public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions; public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes; private NamespaceData _frozen; public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) { Handle = handle; Name = name; FullName = fullName; Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>(); } /// <summary> /// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling /// this method, it is an error to use any methods or fields except Freeze() on the target /// NamespaceDataBuilder. /// </summary> public NamespaceData Freeze() { // It is not an error to call this function multiple times. We cache the result // because it's immutable. if (_frozen == null) { var namespaces = Namespaces.ToImmutable(); Namespaces = null; var typeDefinitions = TypeDefinitions.ToImmutable(); TypeDefinitions = null; var exportedTypes = ExportedTypes.ToImmutable(); ExportedTypes = null; _frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes); } return _frozen; } public void MergeInto(NamespaceDataBuilder other) { Parent = default(NamespaceDefinitionHandle); other.Namespaces.AddRange(this.Namespaces); other.TypeDefinitions.AddRange(this.TypeDefinitions); other.ExportedTypes.AddRange(this.ExportedTypes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System { // These sources are taken from corclr repo (src\mscorlib\src\System\Buffer.cs with x64 path removed) // The reason for this duplication is that System.Runtime.dll 4.0.10 did not expose Buffer.MemoryCopy, // but we need to make this component work with System.Runtime.dll 4.0.10 // The methods AreOverlapping and SlowCopyBackwards are not from Buffer.cs. Buffer.cs does an internal CLR call for these. static class BufferInternal { // This method has different signature for x64 and other platforms and is done for performance reasons. [System.Security.SecurityCritical] private unsafe static void Memmove(byte* dest, byte* src, uint len) { if (AreOverlapping(dest, src, len)) { SlowCopyBackwards(dest, src, len); return; } // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short*)dest = *(short*)src; return; case 3: *(short*)dest = *(short*)src; *(dest + 2) = *(src + 2); return; case 4: *(int*)dest = *(int*)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); return; case 9: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(dest + 8) = *(src + 8); return; case 10: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); return; default: break; } if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *dest = *src; src++; dest++; len--; if (((int)dest & 2) == 0) goto Aligned; } *(short*)dest = *(short*)src; src += 2; dest += 2; len -= 2; Aligned:; } uint count = len / 16; while (count > 0) { ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; ((int*)dest)[2] = ((int*)src)[2]; ((int*)dest)[3] = ((int*)src)[3]; dest += 16; src += 16; count--; } if ((len & 8) != 0) { ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) *dest = *src; return; } private static unsafe void SlowCopyBackwards(byte* dest, byte* src, uint len) { Debug.Assert(len <= int.MaxValue); if (len == 0) return; for(int i=((int)len)-1; i>=0; i--) { dest[i] = src[i]; } } private static unsafe bool AreOverlapping(byte* dest, byte* src, uint len) { byte* srcEnd = src + len; byte* destEnd = dest + len; if (srcEnd >= dest && srcEnd <= destEnd) { return true; } return false; } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void MemoryCopy(void* source, void* destination, int destinationSizeInBytes, int sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { throw new ArgumentOutOfRangeException(nameof(sourceBytesToCopy)); } Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeX509ChainHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { internal SafeX509ChainHandle() : base(default(bool)) { } public override bool IsInvalid { get { throw null; } } protected override void Dispose(bool disposing) { } protected override bool ReleaseHandle() { throw null; } } } namespace System.Security.Cryptography.X509Certificates { public sealed partial class CertificateRequest { public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(System.Security.Cryptography.X509Certificates.X500DistinguishedName subjectName, System.Security.Cryptography.X509Certificates.PublicKey publicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(string subjectName, System.Security.Cryptography.ECDsa key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public CertificateRequest(string subjectName, System.Security.Cryptography.RSA key, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public System.Collections.ObjectModel.Collection<System.Security.Cryptography.X509Certificates.X509Extension> CertificateExtensions { get { throw null; } } public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X500DistinguishedName issuerName, System.Security.Cryptography.X509Certificates.X509SignatureGenerator generator, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSelfSigned(System.DateTimeOffset notBefore, System.DateTimeOffset notAfter) { throw null; } public byte[] CreateSigningRequest() { throw null; } public byte[] CreateSigningRequest(System.Security.Cryptography.X509Certificates.X509SignatureGenerator signatureGenerator) { throw null; } } public static partial class DSACertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.DSA privateKey) { throw null; } public static System.Security.Cryptography.DSA GetDSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public static partial class ECDsaCertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.ECDsa privateKey) { throw null; } public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } [System.FlagsAttribute] public enum OpenFlags { IncludeArchived = 8, MaxAllowed = 2, OpenExistingOnly = 4, ReadOnly = 0, ReadWrite = 1, } public sealed partial class PublicKey { public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { } public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { throw null; } } public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm Key { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } } public static partial class RSACertificateExtensions { public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSA privateKey) { throw null; } public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } } public enum StoreLocation { CurrentUser = 1, LocalMachine = 2, } public enum StoreName { AddressBook = 1, AuthRoot = 2, CertificateAuthority = 3, Disallowed = 4, My = 5, Root = 6, TrustedPeople = 7, TrustedPublisher = 8, } public sealed partial class SubjectAlternativeNameBuilder { public SubjectAlternativeNameBuilder() { } public void AddDnsName(string dnsName) { } public void AddEmailAddress(string emailAddress) { } public void AddIpAddress(System.Net.IPAddress ipAddress) { } public void AddUri(System.Uri uri) { } public void AddUserPrincipalName(string upn) { } public System.Security.Cryptography.X509Certificates.X509Extension Build(bool critical=false) { throw null; } } public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { } public X500DistinguishedName(string distinguishedName) { } public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { } public string Name { get { throw null; } } public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { throw null; } public override string Format(bool multiLine) { throw null; } } [System.FlagsAttribute] public enum X500DistinguishedNameFlags { DoNotUsePlusSign = 32, DoNotUseQuotes = 64, ForceUTF8Encoding = 16384, None = 0, Reversed = 1, UseCommas = 128, UseNewLines = 256, UseSemicolons = 16, UseT61Encoding = 8192, UseUTF8Encoding = 4096, } public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509BasicConstraintsExtension() { } public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { } public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { } public bool CertificateAuthority { get { throw null; } } public bool HasPathLengthConstraint { get { throw null; } } public int PathLengthConstraint { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Certificate : System.IDisposable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { public X509Certificate() { } public X509Certificate(byte[] data) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(byte[] rawData, string password) { } public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(System.IntPtr handle) { } public X509Certificate(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { } public X509Certificate(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate(string fileName, string password) { } public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public System.IntPtr Handle { get { throw null; } } public string Issuer { get { throw null; } } public string Subject { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromCertFile(string filename) { throw null; } public static System.Security.Cryptography.X509Certificates.X509Certificate CreateFromSignedFile(string filename) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override bool Equals(object obj) { throw null; } public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, System.Security.SecureString password) { throw null; } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } protected static string FormatDate(System.DateTime date) { throw null; } public virtual byte[] GetCertHash() { throw null; } public virtual string GetCertHashString() { throw null; } public virtual string GetEffectiveDateString() { throw null; } public virtual string GetExpirationDateString() { throw null; } public virtual string GetFormat() { throw null; } public override int GetHashCode() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { throw null; } public virtual string GetKeyAlgorithm() { throw null; } public virtual byte[] GetKeyAlgorithmParameters() { throw null; } public virtual string GetKeyAlgorithmParametersString() { throw null; } [System.ObsoleteAttribute("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { throw null; } public virtual byte[] GetPublicKey() { throw null; } public virtual string GetPublicKeyString() { throw null; } public virtual byte[] GetRawCertData() { throw null; } public virtual string GetRawCertDataString() { throw null; } public virtual byte[] GetSerialNumber() { throw null; } public virtual string GetSerialNumberString() { throw null; } public virtual void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public virtual void Reset() { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } public virtual string ToString(bool fVerbose) { throw null; } } public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate { public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(System.IntPtr handle) { } protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { } public X509Certificate2(string fileName) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public bool Archived { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { throw null; } } public string FriendlyName { get { throw null; } set { } } public bool HasPrivateKey { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { throw null; } } public System.DateTime NotAfter { get { throw null; } } public System.DateTime NotBefore { get { throw null; } } public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } public byte[] RawData { get { throw null; } } public string SerialNumber { get { throw null; } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { throw null; } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { throw null; } } public string Thumbprint { get { throw null; } } public int Version { get { throw null; } } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { throw null; } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { throw null; } public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { throw null; } public override void Import(byte[] rawData) { } [System.CLSCompliantAttribute(false)] public override void Import(byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName) { } [System.CLSCompliantAttribute(false)] public override void Import(string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public override void Reset() { } public override string ToString() { throw null; } public override string ToString(bool verbose) { throw null; } public bool Verify() { throw null; } } public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { throw null; } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { throw null; } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { throw null; } public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { throw null; } public void Import(byte[] rawData) { } public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Import(string fileName) { } public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator { internal X509Certificate2Enumerator() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public partial class X509CertificateCollection : System.Collections.CollectionBase { public X509CertificateCollection() { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { } public new System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { throw null; } public override int GetHashCode() { throw null; } public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { throw null; } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { } public partial class X509CertificateEnumerator : System.Collections.IEnumerator { public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { } public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class X509Chain : System.IDisposable { public X509Chain() { } public X509Chain(bool useMachineContext) { } public X509Chain(System.IntPtr chainContext) { } public static X509Chain Create() { throw null; } public System.IntPtr ChainContext { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { throw null; } } public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { throw null; } } public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void Reset() { } } public partial class X509ChainElement { internal X509ChainElement() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { throw null; } } public string Information { get { throw null; } } } public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal X509ChainElementCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator { internal X509ChainElementEnumerator() { } public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public sealed partial class X509ChainPolicy { public X509ChainPolicy() { } public System.Security.Cryptography.OidCollection ApplicationPolicy { get { throw null; } } public System.Security.Cryptography.OidCollection CertificatePolicy { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { throw null; } set { } } public System.TimeSpan UrlRetrievalTimeout { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { throw null; } set { } } public System.DateTime VerificationTime { get { throw null; } set { } } public void Reset() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509ChainStatus { public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { throw null; } set { } } public string StatusInformation { get { throw null; } set { } } } [System.FlagsAttribute] public enum X509ChainStatusFlags { CtlNotSignatureValid = 262144, CtlNotTimeValid = 131072, CtlNotValidForUsage = 524288, Cyclic = 128, ExplicitDistrust = 67108864, HasExcludedNameConstraint = 32768, HasNotDefinedNameConstraint = 8192, HasNotPermittedNameConstraint = 16384, HasNotSupportedCriticalExtension = 134217728, HasNotSupportedNameConstraint = 4096, HasWeakSignature = 1048576, InvalidBasicConstraints = 1024, InvalidExtension = 256, InvalidNameConstraints = 2048, InvalidPolicyConstraints = 512, NoError = 0, NoIssuanceChainPolicy = 33554432, NotSignatureValid = 8, NotTimeNested = 2, NotTimeValid = 1, NotValidForUsage = 16, OfflineRevocation = 16777216, PartialChain = 65536, RevocationStatusUnknown = 64, Revoked = 4, UntrustedRoot = 32, } public enum X509ContentType { Authenticode = 6, Cert = 1, Pfx = 3, Pkcs12 = 3, Pkcs7 = 5, SerializedCert = 2, SerializedStore = 4, Unknown = 0, } public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509EnhancedKeyUsageExtension() { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { } public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Extension : System.Security.Cryptography.AsnEncodedData { protected X509Extension() { } public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { } public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { } public X509Extension(string oid, byte[] rawData, bool critical) { } public bool Critical { get { throw null; } set { } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable { public X509ExtensionCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { throw null; } } public object SyncRoot { get { throw null; } } public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { throw null; } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator { internal X509ExtensionEnumerator() { } public System.Security.Cryptography.X509Certificates.X509Extension Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } public enum X509FindType { FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByIssuerDistinguishedName = 4, FindByIssuerName = 3, FindByKeyUsage = 13, FindBySerialNumber = 5, FindBySubjectDistinguishedName = 2, FindBySubjectKeyIdentifier = 14, FindBySubjectName = 1, FindByTemplateName = 9, FindByThumbprint = 0, FindByTimeExpired = 8, FindByTimeNotYetValid = 7, FindByTimeValid = 6, } public enum X509IncludeOption { EndCertOnly = 2, ExcludeRoot = 1, None = 0, WholeChain = 3, } [System.FlagsAttribute] public enum X509KeyStorageFlags { DefaultKeySet = 0, EphemeralKeySet = 32, Exportable = 4, MachineKeySet = 2, PersistKeySet = 16, UserKeySet = 1, UserProtected = 8, } public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509KeyUsageExtension() { } public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { } public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { } public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } [System.FlagsAttribute] public enum X509KeyUsageFlags { CrlSign = 2, DataEncipherment = 16, DecipherOnly = 32768, DigitalSignature = 128, EncipherOnly = 1, KeyAgreement = 8, KeyCertSign = 4, KeyEncipherment = 32, None = 0, NonRepudiation = 64, } public enum X509NameType { DnsFromAlternativeName = 4, DnsName = 3, EmailName = 1, SimpleName = 0, UpnName = 2, UrlName = 5, } public enum X509RevocationFlag { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } public enum X509RevocationMode { NoCheck = 0, Offline = 2, Online = 1, } public abstract partial class X509SignatureGenerator { protected X509SignatureGenerator() { } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { throw null; } } protected abstract System.Security.Cryptography.X509Certificates.PublicKey BuildPublicKey(); public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForECDsa(System.Security.Cryptography.ECDsa key) { throw null; } public static System.Security.Cryptography.X509Certificates.X509SignatureGenerator CreateForRSA(System.Security.Cryptography.RSA key, System.Security.Cryptography.RSASignaturePadding signaturePadding) { throw null; } public abstract byte[] GetSignatureAlgorithmIdentifier(System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public abstract byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); } public sealed partial class X509Store : System.IDisposable { public X509Store() { } public X509Store(System.IntPtr storeHandle) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName) { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(string storeName) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } } public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { throw null; } } public string Name { get { throw null; } } public System.IntPtr StoreHandle { get { throw null; } } public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public void Close() { } public void Dispose() { } public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509SubjectKeyIdentifierExtension() { } public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { } public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { } public string SubjectKeyIdentifier { get { throw null; } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public enum X509SubjectKeyIdentifierHashAlgorithm { CapiSha1 = 2, Sha1 = 0, ShortSha1 = 1, } [System.FlagsAttribute] public enum X509VerificationFlags { AllFlags = 4095, AllowUnknownCertificateAuthority = 16, IgnoreCertificateAuthorityRevocationUnknown = 1024, IgnoreCtlNotTimeValid = 2, IgnoreCtlSignerRevocationUnknown = 512, IgnoreEndRevocationUnknown = 256, IgnoreInvalidBasicConstraints = 8, IgnoreInvalidName = 64, IgnoreInvalidPolicy = 128, IgnoreNotTimeNested = 4, IgnoreNotTimeValid = 1, IgnoreRootRevocationUnknown = 2048, IgnoreWrongUsage = 32, NoFlag = 0, } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using TokenStream = Lucene.Net.Analysis.TokenStream; using ConcurrentMergeScheduler = Lucene.Net.Index.ConcurrentMergeScheduler; using Insanity = Lucene.Net.Util.FieldCacheSanityChecker.Insanity; using FieldCache = Lucene.Net.Search.FieldCache; using CacheEntry = Lucene.Net.Search.CacheEntry; namespace Lucene.Net.Util { /// <summary> Base class for all Lucene unit tests. /// <p/> /// Currently the /// only added functionality over JUnit's TestCase is /// asserting that no unhandled exceptions occurred in /// threads launched by ConcurrentMergeScheduler and asserting sane /// FieldCache usage athe moment of tearDown. /// <p/> /// If you /// override either <code>setUp()</code> or /// <code>tearDown()</code> in your unit test, make sure you /// call <code>super.setUp()</code> and /// <code>super.tearDown()</code> /// <p/> /// </summary> /// <seealso cref="assertSaneFieldCaches"> /// </seealso> [Serializable] public abstract class LuceneTestCase { public static System.IO.FileInfo TEMP_DIR; static LuceneTestCase() { String s = System.Environment.GetEnvironmentVariable("TEMP"); if (s == null) throw new Exception("To run tests, you need to define system property 'temp'"); TEMP_DIR = new System.IO.FileInfo(s); } [NonSerialized] private bool savedAPISetting = false; bool allowDocsOutOfOrder = true; public LuceneTestCase():base() { } public LuceneTestCase(System.String name) { } [SetUp] public virtual void SetUp() { //{{Lucene.Net-2.9.1}} allowDocsOutOfOrder = Lucene.Net.Search.BooleanQuery.GetAllowDocsOutOfOrder(); ConcurrentMergeScheduler.SetTestMode(); savedAPISetting = TokenStream.GetOnlyUseNewAPI(); TokenStream.SetOnlyUseNewAPI(false); } /// <summary> Forcible purges all cache entries from the FieldCache. /// <p/> /// This method will be called by tearDown to clean up FieldCache.DEFAULT. /// If a (poorly written) test has some expectation that the FieldCache /// will persist across test methods (ie: a static IndexReader) this /// method can be overridden to do nothing. /// <p/> /// </summary> /// <seealso cref="FieldCache.PurgeAllCaches()"> /// </seealso> protected internal virtual void PurgeFieldCache(FieldCache fc) { fc.PurgeAllCaches(); } protected internal virtual System.String GetTestLabel() { return Lucene.Net.TestCase.GetFullName(); } [TearDown] public virtual void TearDown() { try { // this isn't as useful as calling directly from the scope where the // index readers are used, because they could be gc'ed just before // tearDown is called. // But it's better then nothing. AssertSaneFieldCaches(GetTestLabel()); if (ConcurrentMergeScheduler.AnyUnhandledExceptions()) { // Clear the failure so that we don't just keep // failing subsequent test cases ConcurrentMergeScheduler.ClearUnhandledExceptions(); Assert.Fail("ConcurrentMergeScheduler hit unhandled exceptions"); } } finally { PurgeFieldCache(Lucene.Net.Search.FieldCache_Fields.DEFAULT); } TokenStream.SetOnlyUseNewAPI(savedAPISetting); //base.TearDown(); // {{Aroush-2.9}} this.seed_init = false; //{{Lucene.Net-2.9.1}} Lucene.Net.Search.BooleanQuery.SetAllowDocsOutOfOrder(allowDocsOutOfOrder); } /// <summary> Asserts that FieldCacheSanityChecker does not detect any /// problems with FieldCache.DEFAULT. /// <p/> /// If any problems are found, they are logged to System.err /// (allong with the msg) when the Assertion is thrown. /// <p/> /// This method is called by tearDown after every test method, /// however IndexReaders scoped inside test methods may be garbage /// collected prior to this method being called, causing errors to /// be overlooked. Tests are encouraged to keep their IndexReaders /// scoped at the class level, or to explicitly call this method /// directly in the same scope as the IndexReader. /// <p/> /// </summary> /// <seealso cref="FieldCacheSanityChecker"> /// </seealso> protected internal virtual void AssertSaneFieldCaches(System.String msg) { CacheEntry[] entries = Lucene.Net.Search.FieldCache_Fields.DEFAULT.GetCacheEntries(); Insanity[] insanity = null; try { try { insanity = FieldCacheSanityChecker.CheckSanity(entries); } catch (System.SystemException e) { System.IO.StreamWriter temp_writer; temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardError(), System.Console.Error.Encoding); temp_writer.AutoFlush = true; DumpArray(msg + ": FieldCache", entries, temp_writer); throw e; } Assert.AreEqual(0, insanity.Length, msg + ": Insane FieldCache usage(s) found"); insanity = null; } finally { // report this in the event of any exception/failure // if no failure, then insanity will be null anyway if (null != insanity) { System.IO.StreamWriter temp_writer2; temp_writer2 = new System.IO.StreamWriter(System.Console.OpenStandardError(), System.Console.Error.Encoding); temp_writer2.AutoFlush = true; DumpArray(msg + ": Insane FieldCache usage(s)", insanity, temp_writer2); } } } /// <summary> Convinience method for logging an iterator.</summary> /// <param name="label">String logged before/after the items in the iterator /// </param> /// <param name="iter">Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator. /// </param> /// <param name="stream">Stream to log messages to. /// </param> public static void DumpIterator(System.String label, System.Collections.IEnumerator iter, System.IO.StreamWriter stream) { stream.WriteLine("*** BEGIN " + label + " ***"); if (null == iter) { stream.WriteLine(" ... NULL ..."); } else { while (iter.MoveNext()) { stream.WriteLine(iter.Current.ToString()); } } stream.WriteLine("*** END " + label + " ***"); } /// <summary> Convinience method for logging an array. Wraps the array in an iterator and delegates</summary> /// <seealso cref="dumpIterator(String,Iterator,PrintStream)"> /// </seealso> public static void DumpArray(System.String label, System.Object[] objs, System.IO.StreamWriter stream) { System.Collections.IEnumerator iter = (null == objs)?null:new System.Collections.ArrayList(objs).GetEnumerator(); DumpIterator(label, iter, stream); } /// <summary> Returns a {@link Random} instance for generating random numbers during the test. /// The random seed is logged during test execution and printed to System.out on any failure /// for reproducing the test using {@link #NewRandom(long)} with the recorded seed /// . /// </summary> public virtual System.Random NewRandom() { if (seed_init != false) { throw new System.SystemException("please call LuceneTestCase.newRandom only once per test"); } return NewRandom(seedRnd.Next(System.Int32.MinValue, System.Int32.MaxValue)); } /// <summary> Returns a {@link Random} instance for generating random numbers during the test. /// If an error occurs in the test that is not reproducible, you can use this method to /// initialize the number generator with the seed that was printed out during the failing test. /// </summary> public virtual System.Random NewRandom(int seed) { if (this.seed_init != false) { throw new System.SystemException("please call LuceneTestCase.newRandom only once per test"); } this.seed_init = true; this.seed = seed; return new System.Random(seed); } // @Override public virtual void RunBare() { try { seed_init = false; //base.RunBare(); // {{Aroush-2.9}} System.Diagnostics.Debug.Fail("Port issue:", "base.RunBare()"); // {{Aroush-2.9}} } catch (System.Exception e) { if (seed_init != false) { System.Console.Out.WriteLine("NOTE: random seed of testcase '" + GetType() + "' was: " + seed); } throw e; } } // recorded seed [NonSerialized] protected internal int seed = 0; protected internal bool seed_init = false; // static members [NonSerialized] private static readonly System.Random seedRnd = new System.Random(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for ProjectItem</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Xunit; namespace Microsoft.Build.UnitTests.OM.Definition { /// <summary> /// Tests for ProjectItem /// </summary> public class ProjectItem_Tests { /// <summary> /// Project getter /// </summary> [Fact] public void ProjectGetter() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; Assert.Equal(true, Object.ReferenceEquals(project, item.Project)); } /// <summary> /// No metadata, simple case /// </summary> [Fact] public void NoMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'/> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.NotNull(item.Xml); Assert.Equal("i", item.ItemType); Assert.Equal("i1", item.EvaluatedInclude); Assert.Equal("i1", item.UnevaluatedInclude); Assert.Equal(false, item.Metadata.GetEnumerator().MoveNext()); } /// <summary> /// Read off metadata /// </summary> [Fact] public void ReadMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); var itemMetadata = Helpers.MakeList(item.Metadata); Assert.Equal(2, itemMetadata.Count); Assert.Equal("m1", itemMetadata[0].Name); Assert.Equal("m2", itemMetadata[1].Name); Assert.Equal("v1", itemMetadata[0].EvaluatedValue); Assert.Equal("v2", itemMetadata[1].EvaluatedValue); Assert.Equal(itemMetadata[0], item.GetMetadata("m1")); Assert.Equal(itemMetadata[1], item.GetMetadata("m2")); } /// <summary> /// Get metadata inherited from item definitions /// </summary> [Fact] public void GetMetadataObjectsFromDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1b</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); ProjectMetadata m0 = item.GetMetadata("m0"); ProjectMetadata m1 = item.GetMetadata("m1"); ProjectItemDefinition definition = project.ItemDefinitions["i"]; ProjectMetadata idm0 = definition.GetMetadata("m0"); ProjectMetadata idm1 = definition.GetMetadata("m1"); Assert.Equal(true, Object.ReferenceEquals(m0, idm0)); Assert.Equal(false, Object.ReferenceEquals(m1, idm1)); } /// <summary> /// Get metadata values inherited from item definitions /// </summary> [Fact] public void GetMetadataValuesFromDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1b</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.Equal("v0", item.GetMetadataValue("m0")); Assert.Equal("v1b", item.GetMetadataValue("m1")); Assert.Equal("v2", item.GetMetadataValue("m2")); } /// <summary> /// Getting nonexistent metadata should return null /// </summary> [Fact] public void GetNonexistentMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='i0'/>"); Assert.Equal(null, item.GetMetadata("m0")); } /// <summary> /// Getting value of nonexistent metadata should return String.Empty /// </summary> [Fact] public void GetNonexistentMetadataValue() { ProjectItem item = GetOneItemFromFragment(@"<i Include='i0'/>"); Assert.Equal(String.Empty, item.GetMetadataValue("m0")); } /// <summary> /// Attempting to set metadata with an invalid XML name should fail /// </summary> [Fact] public void SetInvalidXmlNameMetadata() { Assert.Throws<ArgumentException>(() => { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("##invalid##", "x"); } ); } /// <summary> /// Attempting to set built-in metadata should fail /// </summary> [Fact] public void SetInvalidBuiltInMetadata() { Assert.Throws<ArgumentException>(() => { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("FullPath", "x"); } ); } /// <summary> /// Attempting to set reserved metadata should fail /// </summary> [Fact] public void SetInvalidReservedMetadata() { Assert.Throws<InvalidOperationException>(() => { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("Choose", "x"); } ); } /// <summary> /// Metadata enumerator should only return custom metadata /// </summary> [Fact] public void MetadataEnumeratorExcludesBuiltInMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); Assert.Equal(false, item.Metadata.GetEnumerator().MoveNext()); } /// <summary> /// Read off built-in metadata /// </summary> [Fact] public void BuiltInMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); // c:\foo\bar.baz %(FullPath) = full path of item // c:\ %(RootDir) = root directory of item // bar %(Filename) = item filename without extension // .baz %(Extension) = item filename extension // c:\foo\ %(RelativeDir) = item directory as given in item-spec // foo\ %(Directory) = full path of item directory relative to root // [] %(RecursiveDir) = portion of item path that matched a recursive wildcard // c:\foo\bar.baz %(Identity) = item-spec as given // [] %(ModifiedTime) = last write time of item // [] %(CreatedTime) = creation time of item // [] %(AccessedTime) = last access time of item Assert.Equal(@"c:\foo\bar.baz", item.GetMetadataValue("FullPath")); Assert.Equal(@"c:\", item.GetMetadataValue("RootDir")); Assert.Equal(@"bar", item.GetMetadataValue("Filename")); Assert.Equal(@".baz", item.GetMetadataValue("Extension")); Assert.Equal(@"c:\foo\", item.GetMetadataValue("RelativeDir")); Assert.Equal(@"foo\", item.GetMetadataValue("Directory")); Assert.Equal(String.Empty, item.GetMetadataValue("RecursiveDir")); Assert.Equal(@"c:\foo\bar.baz", item.GetMetadataValue("Identity")); } /// <summary> /// Check file-timestamp related metadata /// </summary> [Fact] public void BuiltInMetadataTimes() { string path = null; string fileTimeFormat = "yyyy'-'MM'-'dd HH':'mm':'ss'.'fffffff"; try { path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); File.WriteAllText(path, String.Empty); FileInfo info = new FileInfo(path); ProjectItem item = GetOneItemFromFragment(@"<i Include='" + path + "'/>"); Assert.Equal(info.LastWriteTime.ToString(fileTimeFormat), item.GetMetadataValue("ModifiedTime")); Assert.Equal(info.CreationTime.ToString(fileTimeFormat), item.GetMetadataValue("CreatedTime")); Assert.Equal(info.LastAccessTime.ToString(fileTimeFormat), item.GetMetadataValue("AccessedTime")); } finally { File.Delete(path); } } /// <summary> /// Test RecursiveDir metadata /// </summary> [Fact] public void RecursiveDirMetadata() { string directory = null; string subdirectory = null; string file = null; try { directory = Path.Combine(Path.GetTempPath(), "a"); if (File.Exists(directory)) { File.Delete(directory); } subdirectory = Path.Combine(directory, "b"); if (File.Exists(subdirectory)) { File.Delete(subdirectory); } file = Path.Combine(subdirectory, "c"); Directory.CreateDirectory(subdirectory); File.WriteAllText(file, String.Empty); ProjectItem item = GetOneItemFromFragment("<i Include='" + directory + @"\**\*'/>"); Assert.Equal(@"b\", item.GetMetadataValue("RecursiveDir")); Assert.Equal("c", item.GetMetadataValue("Filename")); } finally { File.Delete(file); Directory.Delete(subdirectory); Directory.Delete(directory); } } /// <summary> /// Correctly establish the "RecursiveDir" value when the include /// is semicolon separated. /// (This is what requires that the original include fragment [before wildcard /// expansion] is stored in the item.) /// </summary> [Fact] public void RecursiveDirWithSemicolonSeparatedInclude() { string directory = null; string subdirectory = null; string file = null; try { directory = Path.Combine(Path.GetTempPath(), "a"); if (File.Exists(directory)) { File.Delete(directory); } subdirectory = Path.Combine(directory, "b"); if (File.Exists(subdirectory)) { File.Delete(subdirectory); } file = Path.Combine(subdirectory, "c"); Directory.CreateDirectory(subdirectory); File.WriteAllText(file, String.Empty); IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment("<i Include='i0;" + directory + @"\**\*;i2'/>"); Assert.Equal(3, items.Count); Assert.Equal("i0", items[0].EvaluatedInclude); Assert.Equal(@"b\", items[1].GetMetadataValue("RecursiveDir")); Assert.Equal("i2", items[2].EvaluatedInclude); } finally { File.Delete(file); Directory.Delete(subdirectory); Directory.Delete(directory); } } /// <summary> /// Basic exclude case /// </summary> [Fact] public void Exclude() { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment("<i Include='a;b' Exclude='b;c'/>"); Assert.Equal(1, items.Count); Assert.Equal("a", items[0].EvaluatedInclude); } /// <summary> /// Exclude against an include with item vectors in it /// </summary> [Fact] public void ExcludeWithIncludeVector() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='a;b;c'> </i> </ItemGroup> <ItemGroup> <i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); // Should contain a, b, c, x, z, a, c, u, w Assert.Equal(9, items.Count); ObjectModelHelpers.AssertItems(new[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" }, items); } /// <summary> /// Exclude with item vectors against an include with item vectors in it /// </summary> [Fact] public void ExcludeVectorWithIncludeVector() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='a;b;c'> </i> <j Include='b;y;v' /> </ItemGroup> <ItemGroup> <i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); // Should contain a, b, c, z, a, c, u Assert.Equal(7, items.Count); ObjectModelHelpers.AssertItems(new[] { "a", "b", "c", "z", "a", "c", "u" }, items); } private const string ExcludeWithWildCards = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='{0}' Exclude='{1}'/> </ItemGroup> </Project> "; [Theory] [InlineData( ExcludeWithWildCards, "a.*", "*.1", new[] { "a.1", "a.2", "a.1" }, new[] { "a.2" })] [InlineData( ExcludeWithWildCards, @"**\*.cs", @"a\**", new[] { "1.cs", @"a\2.cs", @"a\b\3.cs", @"a\b\c\4.cs" }, new[] { "1.cs" })] [InlineData( ExcludeWithWildCards, @"**\*", @"**\b\**", new[] { "1.cs", @"a\2.cs", @"a\b\3.cs", @"a\b\c\4.cs" }, new[] { "1.cs", @"a\2.cs", "build.proj" })] [InlineData(ExcludeWithWildCards, @"**\*", @"**\b\**\*.cs", new[] { "1.cs", @"a\2.cs", @"a\b\3.cs", @"a\b\c\4.cs", @"a\b\c\5.txt" }, new[] { "1.cs", @"a\2.cs", @"a\b\c\5.txt", "build.proj" })] [InlineData( ExcludeWithWildCards, @"src\**\proj\**\*.cs", @"src\**\proj\**\none\**\*", new[] { "1.cs", @"src\2.cs", @"src\a\3.cs", @"src\proj\4.cs", @"src\proj\a\5.cs", @"src\a\proj\6.cs", @"src\a\proj\a\7.cs", @"src\proj\none\8.cs", @"src\proj\a\none\9.cs", @"src\proj\a\none\a\10.cs", @"src\a\proj\a\none\11.cs", @"src\a\proj\a\none\a\12.cs" }, new[] { @"src\a\proj\6.cs", @"src\a\proj\a\7.cs", @"src\proj\4.cs", @"src\proj\a\5.cs" })] [InlineData( ExcludeWithWildCards, @"**\*", "foo", new[] { "foo", @"a\foo", @"a\a\foo", @"a\b\foo", }, new string[] { @"a\a\foo", @"a\b\foo", @"a\foo", "build.proj" })] public void ExcludeVectorWithWildCards(string projectContents, string includeString, string excludeString, string[] inputFiles, string[] expectedInclude) { //todo run the test twice with slashes and back-slashes when fixing https://github.com/Microsoft/msbuild/issues/724 string root = ""; try { string[] createdFiles; string projectFile; var formattedProjectContents = string.Format(projectContents, includeString, excludeString); root = Helpers.CreateProjectInTempDirectoryWithFiles(formattedProjectContents, inputFiles, out projectFile, out createdFiles); ObjectModelHelpers.AssertItems(expectedInclude, new Project(projectFile).Items.ToList()); } finally { ObjectModelHelpers.DeleteDirectory(root); Directory.Delete(root); } } /// <summary> /// Expression like @(x) should clone metadata, but metadata should still point at the original XML objects /// </summary> [Fact] public void CopyFromWithItemListExpressionClonesMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>m1</m> </i> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); project.GetItems("i").First().SetMetadataValue("m", "m2"); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item2 = project.GetItems("j").First(); Assert.Equal("m2", item1.GetMetadataValue("m")); Assert.Equal("m1", item2.GetMetadataValue("m")); // Should still point at the same XML items Assert.Equal(true, Object.ReferenceEquals(item1.GetMetadata("m").Xml, item2.GetMetadata("m").Xml)); } /// <summary> /// Expression like @(x) should not clone metadata, even if the item type is different. /// It's obvious that it shouldn't clone it if the item type is the same. /// If it is different, it doesn't clone it for performance; even if the item definition metadata /// changes later (this is design time), the inheritors of that item definition type /// (even those that have subsequently been transformed to a different itemtype) should see /// the changes, by design. /// Just to make sure we don't change that behavior, we test it here. /// </summary> [Fact] public void CopyFromWithItemListExpressionDoesNotCloneDefinitionMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m>m1</m> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'/> <i Include='@(i)'/> <i Include=""@(i->'%(identity)')"" /><!-- this will have two items, so setting metadata will split it --> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item1b = project.GetItems("i").ElementAt(1); ProjectItem item1c = project.GetItems("i").ElementAt(2); ProjectItem item2 = project.GetItems("j").First(); Assert.Equal("m1", item1.GetMetadataValue("m")); Assert.Equal("m1", item1b.GetMetadataValue("m")); Assert.Equal("m1", item1c.GetMetadataValue("m")); Assert.Equal("m1", item2.GetMetadataValue("m")); project.ItemDefinitions["i"].SetMetadataValue("m", "m2"); // All the items will see this change Assert.Equal("m2", item1.GetMetadataValue("m")); Assert.Equal("m2", item1b.GetMetadataValue("m")); Assert.Equal("m2", item1c.GetMetadataValue("m")); Assert.Equal("m2", item2.GetMetadataValue("m")); // And verify we're not still pointing to the definition metadata objects item1.SetMetadataValue("m", "m3"); item1b.SetMetadataValue("m", "m4"); item1c.SetMetadataValue("m", "m5"); item2.SetMetadataValue("m", "m6"); Assert.Equal("m2", project.ItemDefinitions["i"].GetMetadataValue("m")); // Should not have been affected } /// <summary> /// Expression like @(x) should not clone metadata, for perf. See comment on test above. /// </summary> [Fact] public void CopyFromWithItemListExpressionClonesDefinitionMetadata_Variation() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m>m1</m> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'/> <i Include=""@(i->'%(identity)')"" /><!-- this will have one item--> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item1b = project.GetItems("i").ElementAt(1); ProjectItem item2 = project.GetItems("j").First(); Assert.Equal("m1", item1.GetMetadataValue("m")); Assert.Equal("m1", item1b.GetMetadataValue("m")); Assert.Equal("m1", item2.GetMetadataValue("m")); project.ItemDefinitions["i"].SetMetadataValue("m", "m2"); // The items should all see this change Assert.Equal("m2", item1.GetMetadataValue("m")); Assert.Equal("m2", item1b.GetMetadataValue("m")); Assert.Equal("m2", item2.GetMetadataValue("m")); // And verify we're not still pointing to the definition metadata objects item1.SetMetadataValue("m", "m3"); item1b.SetMetadataValue("m", "m4"); item2.SetMetadataValue("m", "m6"); Assert.Equal("m2", project.ItemDefinitions["i"].GetMetadataValue("m")); // Should not have been affected } /// <summary> /// Repeated copying of items with item definitions should cause the following order of precedence: /// 1) direct metadata on the item /// 2) item definition metadata on the very first item in the chain /// 3) item definition on the next item, and so on until /// 4) item definition metadata on the destination item itself /// </summary> [Fact] public void CopyWithItemDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <l>l1</l> <m>m1</m> <n>n1</n> </i> <j> <m>m2</m> <o>o2</o> <p>p2</p> </j> <k> <n>n3</n> </k> <l/> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <l>l0</l> </i> <j Include='@(i)'/> <k Include='@(j)'> <p>p4</p> </k> <l Include='@(k);l1'/> <m Include='@(l)'> <o>o4</o> </m> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal("l0", project.GetItems("i").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("i").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("i").First().GetMetadataValue("n")); Assert.Equal("", project.GetItems("i").First().GetMetadataValue("o")); Assert.Equal("", project.GetItems("i").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("j").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("j").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("j").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("j").First().GetMetadataValue("o")); Assert.Equal("p2", project.GetItems("j").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("k").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("k").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("k").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("k").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("k").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("l").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("l").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("l").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("l").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("l").First().GetMetadataValue("p")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("l")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("m")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("n")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("o")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("m").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("m").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("m").First().GetMetadataValue("n")); Assert.Equal("o4", project.GetItems("m").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("m").First().GetMetadataValue("p")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("l")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("m")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("n")); Assert.Equal("o4", project.GetItems("m").ElementAt(1).GetMetadataValue("o")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("p")); // Should still point at the same XML metadata Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("l").Xml, project.GetItems("m").First().GetMetadata("l").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("m").Xml, project.GetItems("m").First().GetMetadata("m").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("n").Xml, project.GetItems("m").First().GetMetadata("n").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("o").Xml, project.GetItems("k").First().GetMetadata("o").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("k").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); Assert.Equal(true, !Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); } /// <summary> /// Repeated copying of items with item definitions should cause the following order of precedence: /// 1) direct metadata on the item /// 2) item definition metadata on the very first item in the chain /// 3) item definition on the next item, and so on until /// 4) item definition metadata on the destination item itself /// </summary> [Fact] public void CopyWithItemDefinition2() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <l>l1</l> <m>m1</m> <n>n1</n> </i> <j> <m>m2</m> <o>o2</o> <p>p2</p> </j> <k> <n>n3</n> </k> <l/> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <l>l0</l> </i> <j Include='@(i)'/> <k Include='@(j)'> <p>p4</p> </k> <l Include='@(k);l1'/> <m Include='@(l)'> <o>o4</o> </m> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.Equal("l0", project.GetItems("i").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("i").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("i").First().GetMetadataValue("n")); Assert.Equal("", project.GetItems("i").First().GetMetadataValue("o")); Assert.Equal("", project.GetItems("i").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("j").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("j").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("j").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("j").First().GetMetadataValue("o")); Assert.Equal("p2", project.GetItems("j").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("k").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("k").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("k").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("k").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("k").First().GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("l").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("l").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("l").First().GetMetadataValue("n")); Assert.Equal("o2", project.GetItems("l").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("l").First().GetMetadataValue("p")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("l")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("m")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("n")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("o")); Assert.Equal("", project.GetItems("l").ElementAt(1).GetMetadataValue("p")); Assert.Equal("l0", project.GetItems("m").First().GetMetadataValue("l")); Assert.Equal("m1", project.GetItems("m").First().GetMetadataValue("m")); Assert.Equal("n1", project.GetItems("m").First().GetMetadataValue("n")); Assert.Equal("o4", project.GetItems("m").First().GetMetadataValue("o")); Assert.Equal("p4", project.GetItems("m").First().GetMetadataValue("p")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("l")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("m")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("n")); Assert.Equal("o4", project.GetItems("m").ElementAt(1).GetMetadataValue("o")); Assert.Equal("", project.GetItems("m").ElementAt(1).GetMetadataValue("p")); // Should still point at the same XML metadata Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("l").Xml, project.GetItems("m").First().GetMetadata("l").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("m").Xml, project.GetItems("m").First().GetMetadata("m").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("n").Xml, project.GetItems("m").First().GetMetadata("n").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("o").Xml, project.GetItems("k").First().GetMetadata("o").Xml)); Assert.Equal(true, Object.ReferenceEquals(project.GetItems("k").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); Assert.Equal(true, !Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); } /// <summary> /// Metadata on items can refer to metadata above /// </summary> [Fact] public void MetadataReferringToMetadataAbove() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>%(m1);v2;%(m0)</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); var itemMetadata = Helpers.MakeList(item.Metadata); Assert.Equal(2, itemMetadata.Count); Assert.Equal("v1;v2;", item.GetMetadataValue("m2")); } /// <summary> /// Built-in metadata should work, too. /// NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now. /// It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed. /// </summary> [Fact] public void BuiltInMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.Equal("i1", item.GetMetadataValue("m")); } /// <summary> /// Qualified built in metadata should work /// </summary> [Fact] public void BuiltInQualifiedMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(i.Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.Equal("i1", item.GetMetadataValue("m")); } /// <summary> /// Mis-qualified built in metadata should not work /// </summary> [Fact] public void BuiltInMisqualifiedMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(j.Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.Equal(String.Empty, item.GetMetadataValue("m")); } /// <summary> /// Metadata condition should work correctly with built-in metadata /// </summary> [Fact] public void BuiltInMetadataInMetadataCondition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m Condition=""'%(Identity)'=='i1'"">m1</m> <n Condition=""'%(Identity)'=='i2'"">n1</n> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.Equal("m1", item.GetMetadataValue("m")); Assert.Equal(String.Empty, item.GetMetadataValue("n")); } /// <summary> /// Metadata on item condition not allowed (currently) /// </summary> [Fact] public void BuiltInMetadataInItemCondition() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1' Condition=""'%(Identity)'=='i1'/> </ItemGroup> </Project> "; GetOneItem(content); } ); } /// <summary> /// Two items should each get their own values for built-in metadata /// </summary> [Fact] public void BuiltInMetadataTwoItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1.cpp;c:\bar\i2.cpp'> <m>%(Filename).obj</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@"i1.obj", items[0].GetMetadataValue("m")); Assert.Equal(@"i2.obj", items[1].GetMetadataValue("m")); } /// <summary> /// Items from another list, but with different metadata /// </summary> [Fact] public void DifferentMetadataItemsFromOtherList() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'> <m>m1</m> </h> <h Include='h1'/> <i Include='@(h)'> <m>%(m)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@"m1", items[0].GetMetadataValue("m")); Assert.Equal(String.Empty, items[1].GetMetadataValue("m")); } /// <summary> /// Items from another list, but with different metadata /// </summary> [Fact] public void DifferentBuiltInMetadataItemsFromOtherList() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0.x'/> <h Include='h1.y'/> <i Include='@(h)'> <m>%(extension)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@".x", items[0].GetMetadataValue("m")); Assert.Equal(@".y", items[1].GetMetadataValue("m")); } /// <summary> /// Two items coming from a transform /// </summary> [Fact] public void BuiltInMetadataTransformInInclude() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include=""@(h->'%(Identity).baz')""> <m>%(Filename)%(Extension).obj</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@"h0.baz.obj", items[0].GetMetadataValue("m")); Assert.Equal(@"h1.baz.obj", items[1].GetMetadataValue("m")); } /// <summary> /// Transform in the metadata value; no bare metadata involved /// </summary> [Fact] public void BuiltInMetadataTransformInMetadataValue() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include='i0'/> <i Include='i1;i2'> <m>@(i);@(h->'%(Filename)')</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@"i0;h0;h1", items[1].GetMetadataValue("m")); Assert.Equal(@"i0;h0;h1", items[2].GetMetadataValue("m")); } /// <summary> /// Transform in the metadata value; bare metadata involved /// </summary> [Fact] public void BuiltInMetadataTransformInMetadataValueBareMetadataPresent() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include='i0.x'/> <i Include='i1.y;i2'> <m>@(i);@(h->'%(Filename)');%(Extension)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m")); Assert.Equal(@"i0.x;h0;h1;", items[2].GetMetadataValue("m")); } /// <summary> /// Metadata on items can refer to item lists /// </summary> [Fact] public void MetadataValueReferringToItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <i Include='i0'/> <i Include='i1'> <m1>@(h);@(i)</m1> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal("h0;i0", items[1].GetMetadataValue("m1")); } /// <summary> /// Metadata on items' conditions can refer to item lists /// </summary> [Fact] public void MetadataConditionReferringToItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <i Include='i0'/> <i Include='i1'> <m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1> <m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal("v1", items[1].GetMetadataValue("m1")); Assert.Equal(String.Empty, items[1].GetMetadataValue("m2")); } /// <summary> /// Metadata on items' conditions can refer to other metadata /// </summary> [Fact] public void MetadataConditionReferringToMetadataOnSameItem() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m0>0</m0> <m1 Condition=""'%(m0)'=='0'"">1</m1> <m2 Condition=""'%(m0)'=='3'"">2</m2> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal("0", items[0].GetMetadataValue("m0")); Assert.Equal("1", items[0].GetMetadataValue("m1")); Assert.Equal(String.Empty, items[0].GetMetadataValue("m2")); } /// <summary> /// Remove a metadatum /// </summary> [Fact] public void RemoveMetadata() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; item.SetMetadataValue("m", "m1"); project.ReevaluateIfNecessary(); bool found = item.RemoveMetadata("m"); Assert.Equal(true, found); Assert.Equal(true, project.IsDirty); Assert.Equal(String.Empty, item.GetMetadataValue("m")); Assert.Equal(0, Helpers.Count(item.Xml.Metadata)); } /// <summary> /// Attempt to remove a metadatum originating from an item definition. /// Should fail if it was not overridden. /// </summary> [Fact] public void RemoveItemDefinitionMetadataMasked() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItemDefinition("i").AddMetadata("m", "m1"); xml.AddItem("i", "i1").AddMetadata("m", "m2"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); bool found = item.RemoveMetadata("m"); Assert.Equal(true, found); Assert.Equal(0, item.DirectMetadataCount); Assert.Equal(0, Helpers.Count(item.DirectMetadata)); Assert.Equal("m1", item.GetMetadataValue("m")); // Now originating from definition! Assert.Equal(true, project.IsDirty); Assert.Equal(0, item.Xml.Count); } /// <summary> /// Attempt to remove a metadatum originating from an item definition. /// Should fail if it was not overridden. /// </summary> [Fact] public void RemoveItemDefinitionMetadataNotMasked() { Assert.Throws<InvalidOperationException>(() => { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItemDefinition("i").AddMetadata("m", "m1"); xml.AddItem("i", "i1"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.RemoveMetadata("m"); // Should throw } ); } /// <summary> /// Remove a nonexistent metadatum /// </summary> [Fact] public void RemoveNonexistentMetadata() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); bool found = item.RemoveMetadata("m"); Assert.Equal(false, found); Assert.Equal(false, project.IsDirty); } /// <summary> /// Tests removing built-in metadata. /// </summary> [Fact] public void RemoveBuiltInMetadata() { Assert.Throws<ArgumentException>(() => { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItem("i", "i1"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); // This should throw item.RemoveMetadata("FullPath"); } ); } /// <summary> /// Simple rename /// </summary> [Fact] public void Rename() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); // populate built in metadata cache for this item, to verify the cache is cleared out by the rename Assert.Equal("i1", item.GetMetadataValue("FileName")); item.Rename("i2"); Assert.Equal("i2", item.Xml.Include); Assert.Equal("i2", item.EvaluatedInclude); Assert.Equal(true, project.IsDirty); Assert.Equal("i2", item.GetMetadataValue("FileName")); } /// <summary> /// Verifies that renaming a ProjectItem whose xml backing is a wildcard doesn't corrupt /// the MSBuild evaluation data. /// </summary> [Fact] public void RenameItemInProjectWithWildcards() { string projectDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(projectDirectory); try { string sourceFile = Path.Combine(projectDirectory, "a.cs"); string renamedSourceFile = Path.Combine(projectDirectory, "b.cs"); File.Create(sourceFile).Dispose(); var project = new Project(); project.AddItem("File", "*.cs"); project.FullPath = Path.Combine(projectDirectory, "test.proj"); // assign a path so the wildcards can lock onto something. project.ReevaluateIfNecessary(); var projectItem = project.Items.Single(); Assert.Equal(Path.GetFileName(sourceFile), projectItem.EvaluatedInclude); Assert.Same(projectItem, project.GetItemsByEvaluatedInclude(projectItem.EvaluatedInclude).Single()); projectItem.Rename(Path.GetFileName(renamedSourceFile)); File.Move(sourceFile, renamedSourceFile); // repro w/ or w/o this project.ReevaluateIfNecessary(); projectItem = project.Items.Single(); Assert.Equal(Path.GetFileName(renamedSourceFile), projectItem.EvaluatedInclude); Assert.Same(projectItem, project.GetItemsByEvaluatedInclude(projectItem.EvaluatedInclude).Single()); } finally { Directory.Delete(projectDirectory, recursive: true); } } /// <summary> /// Change item type /// </summary> [Fact] public void ChangeItemType() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); item.ItemType = "j"; Assert.Equal("j", item.ItemType); Assert.Equal(true, project.IsDirty); } /// <summary> /// Change item type to invalid value /// </summary> [Fact] public void ChangeItemTypeInvalid() { Assert.Throws<ArgumentException>(() => { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); item.ItemType = "|"; } ); } /// <summary> /// Attempt to rename imported item should fail /// </summary> [Fact] public void RenameImported() { Assert.Throws<InvalidOperationException>(() => { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.AddItem("i", "i1"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.Rename("i2"); } finally { File.Delete(file); } } ); } /// <summary> /// Attempt to set metadata on imported item should fail /// </summary> [Fact] public void SetMetadataImported() { Assert.Throws<InvalidOperationException>(() => { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.AddItem("i", "i1"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.SetMetadataValue("m", "m0"); } finally { File.Delete(file); } } ); } /// <summary> /// Attempt to remove metadata on imported item should fail /// </summary> [Fact] public void RemoveMetadataImported() { Assert.Throws<InvalidOperationException>(() => { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); ProjectItem item = import.AddItem("i", "i1")[0]; item.SetMetadataValue("m", "m0"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); item = Helpers.GetFirst(project.GetItems("i")); item.RemoveMetadata("m"); } finally { File.Delete(file); } } ); } // TODO: Should remove tests go in project item tests, project item instance tests, or both? [Fact] public void Remove() { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment( "<i Include='a;b' />" + "<i Remove='b;c' />" ); Assert.Equal(1, items.Count); Assert.Equal("a", items[0].EvaluatedInclude); } [Fact] public void RemoveGlob() { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment( @"<i Include='a.txt;b.cs;bin\foo.cs' />" + @"<i Remove='bin\**' />" ); Assert.Equal(2, items.Count); Assert.Equal(@"a.txt;b.cs", string.Join(";", items.Select(i => i.EvaluatedInclude))); ; } [Fact] public void RemoveItemReference() { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment( @"<i Include='a;b;c;d' />" + @"<j Include='b;d' />" + @"<i Remove='@(j)' />" ); Assert.Equal(2, items.Count); Assert.Equal(@"a;c", string.Join(";", items.Select(i => i.EvaluatedInclude))); ; } [Fact] public void UpdateMetadataShouldAddOrReplace() { string content = @"<i Include='a;b'> <m1>m1_contents</m1> <m2>m2_contents</m2> <m3>m3_contents</m3> </i> <i Update='a'> <m1>updated</m1> <m2></m2> <m4>added</m4> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); ObjectModelHelpers.AssertItemHasMetadata( new Dictionary<string, string> { {"m1", "updated"}, {"m2", ""}, {"m3", "m3_contents"}, {"m4", "added"} } , items[0]); ObjectModelHelpers.AssertItemHasMetadata( new Dictionary<string, string> { {"m1", "m1_contents"}, {"m2", "m2_contents"}, {"m3", "m3_contents"} } , items[1]); } /// <summary> /// Project evaluation is a design time evaluation. Conditions on items are ignored /// Conditions on metadata on the other hand appear to be respected on the other hand (don't know why, but that's what the code does). /// </summary> [Fact] public void UpdateShouldNotRespectConditionsOnItems() { string content = @"<i Include='a;b;c'> <m1>m1_contents</m1> </i> <i Update='a' Condition='1 == 1'> <m1>from_true</m1> </i> <i Update='b' Condition='1 == 0'> <m1>from_false_item</m1> </i> <i Update='c'> <m1 Condition='1 == 0'>from_false_metadata</m1> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); var expectedInitial = new Dictionary<string, string> { {"m1", "m1_contents"} }; var expectedUpdateFromTrue = new Dictionary<string, string> { {"m1", "from_true"} }; var expectedUpdateFromFalseOnItem = new Dictionary<string, string> { {"m1", "from_false_item"} }; ObjectModelHelpers.AssertItemHasMetadata(expectedUpdateFromTrue, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedUpdateFromFalseOnItem, items[1]); ObjectModelHelpers.AssertItemHasMetadata(expectedInitial, items[2]); } [Fact] public void LastUpdateWins() { string content = @"<i Include='a'> <m1>m1_contents</m1> </i> <i Update='a'> <m1>first</m1> </i> <i Update='a'> <m1>second</m1> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); var expectedUpdate = new Dictionary<string, string> { {"m1", "second"} }; ObjectModelHelpers.AssertItemHasMetadata(expectedUpdate, items[0]); } [Fact] public void UpdateWithNoMetadataShouldNotAffectItems() { string content = @"<i Include='a;b'> <m1>m1_contents</m1> <m2>m2_contents</m2> <m3>m3_contents</m3> </i> <i Update='a'> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); var expectedMetadata = new Dictionary<string, string> { {"m1", "m1_contents"}, {"m2", "m2_contents"}, {"m3", "m3_contents"} }; Assert.Equal(2, items.Count); ObjectModelHelpers.AssertItemHasMetadata(expectedMetadata, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedMetadata, items[1]); } [Fact] public void UpdateOnNonExistingItemShouldDoNothing() { string content = @"<i Include='a;b'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i> <i Update='c'> <m1>updated</m1> <m2></m2> <m3>added</m3> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); Assert.Equal(2, items.Count); var expectedMetadata = new Dictionary<string, string> { {"m1", "m1_contents"}, {"m2", "m2_contents"}, }; ObjectModelHelpers.AssertItemHasMetadata(expectedMetadata, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedMetadata, items[1]); } [Fact] public void UpdateOnEmptyStringShouldThrow() { string content = @"<i Include='a;b'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i> <i Update=''> <m1>updated</m1> <m2></m2> <m3>added</m3> </i>"; var exception = Assert.Throws<InvalidProjectFileException>(() => { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); }); Assert.Equal("The required attribute \"Update\" is empty or missing from the element <i>.", exception.Message); } // Complex metadata: metadata references from the same item; item transforms; correct binding of metadata with same name but different item qualifiers [Fact] public void UpdateShouldSupportComplexMetadata() { string content = @" <i1 Include='x'> <m1>%(Identity)</m1> </i1> <i2 Include='a;b'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i2> <i2 Update='a;b'> <m1>%(Identity)</m1> <m2>%(m1)@(i1 -> '%(m1)')</m2> </i2>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content, true); Assert.Equal(3, items.Count); var expectedMetadataX = new Dictionary<string, string> { {"m1", "x"}, }; var expectedMetadataA = new Dictionary<string, string> { {"m1", "a"}, {"m2", "ax"}, }; var expectedMetadataB = new Dictionary<string, string> { {"m1", "b"}, {"m2", "bx"}, }; ObjectModelHelpers.AssertItemHasMetadata(expectedMetadataX, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedMetadataA, items[1]); ObjectModelHelpers.AssertItemHasMetadata(expectedMetadataB, items[2]); } [Fact] public void UpdateShouldBeAbleToContainGlobs() { string rootDir = null; try { var content = @"<i Include='*.foo'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i> <i Update='*bar*foo'> <m1>updated</m1> <m2></m2> <m3>added</m3> </i>"; var items = GetItemsFromFragmentWithGlobs(out rootDir, content, "a.foo", "b.foo", "bar1.foo", "bar2.foo"); Assert.Equal(4, items.Count); var expectedInitialMetadata = new Dictionary<string, string> { {"m1", "m1_contents"}, {"m2", "m2_contents"}, }; var expectedUpdatedMetadata = new Dictionary<string, string> { {"m1", "updated"}, {"m2", ""}, {"m3", "added"}, }; ObjectModelHelpers.AssertItemHasMetadata(expectedInitialMetadata, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedInitialMetadata, items[1]); ObjectModelHelpers.AssertItemHasMetadata(expectedUpdatedMetadata, items[2]); ObjectModelHelpers.AssertItemHasMetadata(expectedUpdatedMetadata, items[3]); } finally { ObjectModelHelpers.DeleteDirectory(rootDir); } } [Fact] public void UpdateShouldBeAbleToContainItemReferences() { var content = @"<i1 Include='x;y'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i1> <i1 Update='@(i1)'> <m1>m1_updated</m1> <m2>m2_updated</m2> </i1> <i2 Include='a;y'> <m1>m1_i2_contents</m1> <m2>m2_i2_contents</m2> </i2> <i2 Update='@(i1)'> <m1>m1_i2_updated</m1> </i2>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content, true); Assert.Equal(4, items.Count); var expected_i1 = new Dictionary<string, string> { {"m1", "m1_updated"}, {"m2", "m2_updated"}, }; var expected_i2_a = new Dictionary<string, string> { {"m1", "m1_i2_contents"}, {"m2", "m2_i2_contents"} }; var expected_i2_y = new Dictionary<string, string> { {"m1", "m1_i2_updated"}, {"m2", "m2_i2_contents"} }; ObjectModelHelpers.AssertItemHasMetadata(expected_i1, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expected_i1, items[1]); ObjectModelHelpers.AssertItemHasMetadata(expected_i2_a, items[2]); ObjectModelHelpers.AssertItemHasMetadata(expected_i2_y, items[3]); } [Fact] public void UpdateShouldBeAbleToContainProperties() { var content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <P>a</P> </PropertyGroup> <ItemGroup> <i Include='a;b;c'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i> <i Update='$(P);b'> <m1>m1_updated</m1> <m2>m2_updated</m2> </i> </ItemGroup> </Project>" ; IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(3, items.Count); var expectedInitial = new Dictionary<string, string> { {"m1", "m1_contents"}, {"m2", "m2_contents"} }; var expectedUpdated = new Dictionary<string, string> { {"m1", "m1_updated"}, {"m2", "m2_updated"} }; ObjectModelHelpers.AssertItemHasMetadata(expectedUpdated, items[0]); ObjectModelHelpers.AssertItemHasMetadata(expectedUpdated, items[1]); ObjectModelHelpers.AssertItemHasMetadata(expectedInitial, items[2]); } [Fact] public void UpdateShouldUseCaseInsensitiveMatching() { var content = @" <i Include='x'> <m1>m1_contents</m1> <m2>m2_contents</m2> </i> <i Update='X'> <m1>m1_updated</m1> <m2>m2_updated</m2> </i>"; IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(content); var expectedUpdated = new Dictionary<string, string> { {"m1", "m1_updated"}, {"m2", "m2_updated"}, }; ObjectModelHelpers.AssertItemHasMetadata(expectedUpdated, items[0]); } private static List<ProjectItem> GetItemsFromFragmentWithGlobs(out string rootDir, string itemGroupFragment, params string[] globFiles) { var projectFile = ObjectModelHelpers.CreateFileInTempProjectDirectory($"{Guid.NewGuid()}.proj", ObjectModelHelpers.FormatProjectContentsWithItemGroupFragment(itemGroupFragment)); rootDir = Path.GetDirectoryName(projectFile); Helpers.CreateFilesInDirectory(rootDir, globFiles); return Helpers.MakeList(new Project(projectFile).GetItems("i")); } /// <summary> /// Get the item of type "i" using the item Xml fragment provided. /// If there is more than one, fail. /// </summary> private static ProjectItem GetOneItemFromFragment(string fragment) { IList<ProjectItem> items = ObjectModelHelpers.GetItemsFromFragment(fragment); Assert.Equal(1, items.Count); return items[0]; } /// <summary> /// Get the item of type "i" in the project provided. /// If there is more than one, fail. /// </summary> private static ProjectItem GetOneItem(string content) { IList<ProjectItem> items = ObjectModelHelpers.GetItems(content); Assert.Equal(1, items.Count); return items[0]; } } }
// <copyright file="ResidualStopCriterionTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // 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. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Solvers.StopCriterion { /// <summary> /// Residual stop criterion tests. /// </summary> [TestFixture, Category("LASolver")] public sealed class ResidualStopCriterionTest { /// <summary> /// Create with negative maximum throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithNegativeMaximumThrowsArgumentOutOfRangeException() { Assert.That(() => new ResidualStopCriterion<float>(-0.1f), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException() { Assert.That(() => new ResidualStopCriterion<float>(-1), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create. /// </summary> [Test] public void Create() { var criterion = new ResidualStopCriterion<float>(1e-6f, 50); Assert.AreEqual(1e-6f, criterion.Maximum, "Incorrect maximum"); Assert.AreEqual(50, criterion.MinimumIterationsBelowMaximum, "Incorrect iteration count"); } /// <summary> /// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException() { var criterion = new ResidualStopCriterion<float>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( -1, Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(3, 5), Vector<float>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Determine status with non-matching solution vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingSolutionVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<float>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<float>.Build.Dense(4, 4), Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(3, 4)), Throws.ArgumentException); } /// <summary> /// Determine status with non-matching source vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingSourceVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<float>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(4, 4), Vector<float>.Build.Dense(3, 4)), Throws.ArgumentException); } /// <summary> /// Determine status with non-matching residual vector throws <c>ArgumentException</c>. /// </summary> [Test] public void DetermineStatusWithNonMatchingResidualVectorThrowsArgumentException() { var criterion = new ResidualStopCriterion<float>(1e-6f, 50); Assert.That(() => criterion.DetermineStatus( 1, Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(3, 4), Vector<float>.Build.Dense(4, 4)), Throws.ArgumentException); } /// <summary> /// Can determine status with source NaN. /// </summary> [Test] public void DetermineStatusWithSourceNaN() { var criterion = new ResidualStopCriterion<float>(1e-3f, 10); var solution = new DenseVector(new[] { 1.0f, 1.0f, 2.0f }); var source = new DenseVector(new[] { 1.0f, 1.0f, float.NaN }); var residual = new DenseVector(new[] { 1000.0f, 1000.0f, 2001.0f }); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged"); } /// <summary> /// Can determine status with residual NaN. /// </summary> [Test] public void DetermineStatusWithResidualNaN() { var criterion = new ResidualStopCriterion<float>(1e-3f, 10); var solution = new DenseVector(new[] { 1.0f, 1.0f, 2.0f }); var source = new DenseVector(new[] { 1.0f, 1.0f, 2.0f }); var residual = new DenseVector(new[] { 1000.0f, float.NaN, 2001.0f }); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged"); } /// <summary> /// Can determine status with convergence at first iteration. /// </summary> [Test] public void DetermineStatusWithConvergenceAtFirstIteration() { var criterion = new ResidualStopCriterion<float>(1e-6); var solution = new DenseVector(new[] { 1.0f, 1.0f, 1.0f }); var source = new DenseVector(new[] { 1.0f, 1.0f, 1.0f }); var residual = new DenseVector(new[] { 0.0f, 0.0f, 0.0f }); var status = criterion.DetermineStatus(0, solution, source, residual); Assert.AreEqual(IterationStatus.Converged, status, "Should be done"); } /// <summary> /// Can determine status. /// </summary> [Test] public void DetermineStatus() { var criterion = new ResidualStopCriterion<float>(1e-3f, 10); // the solution vector isn't actually being used so ... var solution = new DenseVector(new[] { float.NaN, float.NaN, float.NaN }); // Set the source values var source = new DenseVector(new[] { 1.000f, 1.000f, 2.001f }); // Set the residual values var residual = new DenseVector(new[] { 0.001f, 0.001f, 0.002f }); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Continue, status, "Should still be running"); var status2 = criterion.DetermineStatus(16, solution, source, residual); Assert.AreEqual(IterationStatus.Converged, status2, "Should be done"); } /// <summary> /// Can reset calculation state. /// </summary> [Test] public void ResetCalculationState() { var criterion = new ResidualStopCriterion<float>(1e-3f, 10); var solution = new DenseVector(new[] { 0.001f, 0.001f, 0.002f }); var source = new DenseVector(new[] { 0.001f, 0.001f, 0.002f }); var residual = new DenseVector(new[] { 1.000f, 1.000f, 2.001f }); var status = criterion.DetermineStatus(5, solution, source, residual); Assert.AreEqual(IterationStatus.Continue, status, "Should be running"); criterion.Reset(); Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Should not have started"); } /// <summary> /// Can clone stop criterion. /// </summary> [Test] public void Clone() { var criterion = new ResidualStopCriterion<float>(1e-3f, 10); var clone = criterion.Clone(); Assert.IsInstanceOf(typeof (ResidualStopCriterion<float>), clone, "Wrong criterion type"); var clonedCriterion = clone as ResidualStopCriterion<float>; Assert.IsNotNull(clonedCriterion); // ReSharper disable PossibleNullReferenceException Assert.AreEqual(criterion.Maximum, clonedCriterion.Maximum, "Clone failed"); Assert.AreEqual(criterion.MinimumIterationsBelowMaximum, clonedCriterion.MinimumIterationsBelowMaximum, "Clone failed"); // ReSharper restore PossibleNullReferenceException } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Web; using System.Xml; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Querying; using umbraco.cms.businesslogic.cache; using umbraco.BusinessLogic; using umbraco.DataLayer; using System.Web.Security; using System.Text; using System.Security.Cryptography; using System.Linq; using Umbraco.Core.Security; namespace umbraco.cms.businesslogic.member { /// <summary> /// The Member class represents a member of the public website (not to be confused with umbraco users) /// /// Members are used when creating communities and collaborative applications using umbraco, or if there are a /// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website) /// /// Inherits generic datafields from it's baseclass content. /// </summary> [Obsolete("Use the MemberService and the Umbraco.Core.Models.Member models instead")] public class Member : Content { #region Constants and static members public static readonly string UmbracoMemberProviderName = Constants.Conventions.Member.UmbracoMemberProviderName; public static readonly string UmbracoRoleProviderName = Constants.Conventions.Member.UmbracoRoleProviderName; public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member); // zb-00004 #29956 : refactor cookies names & handling private const string _sQLOptimizedMany = @" select umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate, umbracoNode.nodeUser, umbracoNode.text, cmsMember.Email, cmsMember.LoginName, cmsMember.Password from umbracoNode inner join cmsContent on cmsContent.nodeId = umbracoNode.id inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId where umbracoNode.nodeObjectType = @nodeObjectType AND {0} order by {1}"; #endregion #region Private members private Hashtable _groups = null; protected internal IMember MemberItem; #endregion #region Constructors internal Member(IMember member) : base(member) { SetupNode(member); } /// <summary> /// Initializes a new instance of the Member class. /// </summary> /// <param name="id">Identifier</param> public Member(int id) : base(id) { } /// <summary> /// Initializes a new instance of the Member class. /// </summary> /// <param name="id">Identifier</param> public Member(Guid id) : base(id) { } /// <summary> /// Initializes a new instance of the Member class, with an option to only initialize /// the data used by the tree in the umbraco console. /// </summary> /// <param name="id">Identifier</param> /// <param name="noSetup"></param> public Member(int id, bool noSetup) : base(id, noSetup) { } public Member(Guid id, bool noSetup) : base(id, noSetup) { } #endregion #region Static methods /// <summary> /// A list of all members in the current umbraco install /// /// Note: is ressource intensive, use with care. /// </summary> public static Member[] GetAll { get { return GetAllAsList().ToArray(); } } public static IEnumerable<Member> GetAllAsList() { int totalRecs; return ApplicationContext.Current.Services.MemberService.GetAll(0, int.MaxValue, out totalRecs) .Select(x => new Member(x)) .ToArray(); } /// <summary> /// Retrieves a list of members thats not start with a-z /// </summary> /// <returns>array of members</returns> public static Member[] getAllOtherMembers() { //NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on // changing how the members are shown and not having to worry about letters. var ids = new List<int>(); using (var dr = SqlHelper.ExecuteReader( string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"), SqlHelper.CreateParameter("@nodeObjectType", Member._objectType))) { while (dr.Read()) { ids.Add(dr.GetInt("id")); } } if (ids.Any()) { return ApplicationContext.Current.Services.MemberService.GetAllMembers(ids.ToArray()) .Select(x => new Member(x)) .ToArray(); } return new Member[] { }; } /// <summary> /// Retrieves a list of members by the first letter in their name. /// </summary> /// <param name="letter">The first letter</param> /// <returns></returns> public static Member[] getMemberFromFirstLetter(char letter) { int totalRecs; return ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName( letter.ToString(CultureInfo.InvariantCulture), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith) .Select(x => new Member(x)) .ToArray(); } public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin) { int totalRecs; if (matchByNameInsteadOfLogin) { var found = ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName( usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); return found.Select(x => new Member(x)).ToArray(); } else { var found = ApplicationContext.Current.Services.MemberService.FindByUsername( usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); return found.Select(x => new Member(x)).ToArray(); } } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <returns>The new member</returns> public static Member MakeNew(string Name, MemberType mbt, User u) { return MakeNew(Name, "", "", mbt, u); } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <param name="Email">The email of the user</param> /// <returns>The new member</returns> public static Member MakeNew(string Name, string Email, MemberType mbt, User u) { return MakeNew(Name, "", Email, mbt, u); } /// <summary> /// Creates a new member /// </summary> /// <param name="Name">Membername</param> /// <param name="mbt">Member type</param> /// <param name="u">The umbraco usercontext</param> /// <param name="Email">The email of the user</param> /// <returns>The new member</returns> public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u) { if (mbt == null) throw new ArgumentNullException("mbt"); var loginName = (string.IsNullOrEmpty(LoginName) == false) ? LoginName : Name; var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); //NOTE: This check is ONLY for backwards compatibility, this check shouldn't really be here it is up to the Membership provider // logic to deal with this but it was here before so we can't really change that. // Test for e-mail if (Email != "" && GetMemberFromEmail(Email) != null && provider.RequiresUniqueEmail) throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); if (GetMemberFromLoginName(loginName) != null) throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName)); var model = ApplicationContext.Current.Services.MemberService.CreateMemberWithIdentity( loginName, Email.ToLower(), Name, mbt.MemberTypeItem); //The content object will only have the 'WasCancelled' flag set to 'True' if the 'Saving' event has been cancelled, so we return null. if (((Entity)model).WasCancelled) return null; var legacy = new Member(model); var e = new NewEventArgs(); legacy.OnNew(e); legacy.Save(); return legacy; } /// <summary> /// Retrieve a member given the loginname /// /// Used when authentifying the Member /// </summary> /// <param name="loginName">The unique Loginname</param> /// <returns>The member with the specified loginname - null if no Member with the login exists</returns> public static Member GetMemberFromLoginName(string loginName) { Mandate.ParameterNotNullOrEmpty(loginName, "loginName"); var found = ApplicationContext.Current.Services.MemberService.GetByUsername(loginName); if (found == null) return null; return new Member(found); } /// <summary> /// Retrieve a Member given an email, the first if there multiple members with same email /// /// Used when authentifying the Member /// </summary> /// <param name="email">The email of the member</param> /// <returns>The member with the specified email - null if no Member with the email exists</returns> public static Member GetMemberFromEmail(string email) { if (string.IsNullOrEmpty(email)) return null; var found = ApplicationContext.Current.Services.MemberService.GetByEmail(email); if (found == null) return null; return new Member(found); } /// <summary> /// Retrieve Members given an email /// /// Used when authentifying a Member /// </summary> /// <param name="email">The email of the member(s)</param> /// <returns>The members with the specified email</returns> public static Member[] GetMembersFromEmail(string email) { if (string.IsNullOrEmpty(email)) return null; int totalRecs; var found = ApplicationContext.Current.Services.MemberService.FindByEmail( email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact); return found.Select(x => new Member(x)).ToArray(); } /// <summary> /// Retrieve a Member given the credentials /// /// Used when authentifying the member /// </summary> /// <param name="loginName">Member login</param> /// <param name="password">Member password</param> /// <returns>The member with the credentials - null if none exists</returns> [Obsolete("Use the MembershipProvider methods to validate a member")] public static Member GetMemberFromLoginNameAndPassword(string loginName, string password) { if (IsMember(loginName)) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); // validate user via provider if (provider.ValidateUser(loginName, password)) { return GetMemberFromLoginName(loginName); } else { LogHelper.Debug<Member>("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")", true); return null; } } else { LogHelper.Debug<Member>("No member with loginname: " + loginName + " Exists", true); return null; } } [Obsolete("This method will not work if the password format is encrypted since the encryption that is performed is not static and a new value will be created each time the same string is encrypted")] public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password) { var o = SqlHelper.ExecuteScalar<object>( "select nodeID from cmsMember where LoginName = @loginName and Password = @password", SqlHelper.CreateParameter("loginName", loginName), SqlHelper.CreateParameter("password", password)); if (o == null) return null; int tmpId; if (!int.TryParse(o.ToString(), out tmpId)) return null; return new Member(tmpId); } [Obsolete("Use MembershipProviderExtensions.IsUmbracoMembershipProvider instead")] public static bool InUmbracoMemberMode() { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); return provider.IsUmbracoMembershipProvider(); } public static bool IsUsingUmbracoRoles() { return Roles.Provider.Name == UmbracoRoleProviderName; } /// <summary> /// Helper method - checks if a Member with the LoginName exists /// </summary> /// <param name="loginName">Member login</param> /// <returns>True if the member exists</returns> public static bool IsMember(string loginName) { Mandate.ParameterNotNullOrEmpty(loginName, "loginName"); return ApplicationContext.Current.Services.MemberService.Exists(loginName); } /// <summary> /// Deletes all members of the membertype specified /// /// Used when a membertype is deleted /// /// Use with care /// </summary> /// <param name="dt">The membertype which are being deleted</param> public static void DeleteFromType(MemberType dt) { ApplicationContext.Current.Services.MemberService.DeleteMembersOfType(dt.Id); } #endregion #region Public Properties public override int sortOrder { get { return MemberItem == null ? base.sortOrder : MemberItem.SortOrder; } set { if (MemberItem == null) { base.sortOrder = value; } else { MemberItem.SortOrder = value; } } } public override int Level { get { return MemberItem == null ? base.Level : MemberItem.Level; } set { if (MemberItem == null) { base.Level = value; } else { MemberItem.Level = value; } } } public override int ParentId { get { return MemberItem == null ? base.ParentId : MemberItem.ParentId; } } public override string Path { get { return MemberItem == null ? base.Path : MemberItem.Path; } set { if (MemberItem == null) { base.Path = value; } else { MemberItem.Path = value; } } } [Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)] public override string Text { get { return MemberItem.Name; } set { value = value.Trim(); MemberItem.Name = value; } } /// <summary> /// The members password, used when logging in on the public website /// </summary> [Obsolete("Do not use this property, use GetPassword and ChangePassword instead, if using ChangePassword ensure that the password is encrypted or hashed based on the active membership provider")] public string Password { get { return MemberItem.RawPasswordValue; } set { // We need to use the provider for this in order for hashing, etc. support // To write directly to the db use the ChangePassword method // this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project) var helper = new MemberShipHelper(); var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); MemberItem.RawPasswordValue = helper.EncodePassword(value, provider.PasswordFormat); } } /// <summary> /// The loginname of the member, used when logging in /// </summary> public string LoginName { get { return MemberItem.Username; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("The loginname must be different from an empty string", "LoginName"); if (value.Contains(",")) throw new ArgumentException("The parameter 'LoginName' must not contain commas."); MemberItem.Username = value; } } /// <summary> /// A list of groups the member are member of /// </summary> public Hashtable Groups { get { if (_groups == null) PopulateGroups(); return _groups; } } /// <summary> /// The members email /// </summary> public string Email { get { return MemberItem.Email.IsNullOrWhiteSpace() ? string.Empty : MemberItem.Email.ToLower(); } set { MemberItem.Email = value == null ? "" : value.ToLower(); } } #endregion #region Public Methods [Obsolete("Obsolete", false)] protected override void setupNode() { if (Id == -1) { base.setupNode(); return; } var content = ApplicationContext.Current.Services.MemberService.GetById(Id); if (content == null) throw new ArgumentException(string.Format("No Member exists with id '{0}'", Id)); SetupNode(content); } private void SetupNode(IMember content) { MemberItem = content; //Also need to set the ContentBase item to this one so all the propery values load from it ContentBase = MemberItem; //Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader() base.PopulateCMSNodeFromUmbracoEntity(MemberItem, _objectType); //If the version is empty we update with the latest version from the current IContent. if (Version == Guid.Empty) Version = MemberItem.Version; } /// <summary> /// Used to persist object changes to the database /// </summary> /// <param name="raiseEvents"></param> public void Save(bool raiseEvents) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); //Due to backwards compatibility with this API we need to check for duplicate emails here if required. // This check should not be done here, as this logic is based on the MembershipProvider var requireUniqueEmail = provider.RequiresUniqueEmail; //check if there's anyone with this email in the db that isn't us var membersFromEmail = GetMembersFromEmail(Email); if (requireUniqueEmail && membersFromEmail != null && membersFromEmail.Any(x => x.Id != Id)) { throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); } var e = new SaveEventArgs(); if (raiseEvents) { FireBeforeSave(e); } foreach (var property in GenericProperties) { MemberItem.SetValue(property.PropertyType.Alias, property.Value); } if (e.Cancel == false) { ApplicationContext.Current.Services.MemberService.Save(MemberItem, raiseEvents); //base.VersionDate = MemberItem.UpdateDate; base.Save(); if (raiseEvents) { FireAfterSave(e); } } } /// <summary> /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility /// </summary> public override void Save() { Save(true); } /// <summary> /// Xmlrepresentation of a member /// </summary> /// <param name="xd">The xmldocument context</param> /// <param name="Deep">Recursive - should always be set to false</param> /// <returns>A the xmlrepresentation of the current member</returns> public override XmlNode ToXml(XmlDocument xd, bool Deep) { var x = base.ToXml(xd, Deep); if (x.Attributes != null && x.Attributes["loginName"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "loginName", LoginName)); } if (x.Attributes != null && x.Attributes["email"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "email", Email)); } if (x.Attributes != null && x.Attributes["key"] == null) { x.Attributes.Append(XmlHelper.AddAttribute(xd, "key", UniqueId.ToString())); } return x; } /// <summary> /// Deltes the current member /// </summary> [Obsolete("Obsolete, Use Umbraco.Core.Services.MemberService.Delete()", false)] public override void delete() { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { if (MemberItem != null) { ApplicationContext.Current.Services.MemberService.Delete(MemberItem); } else { var member = ApplicationContext.Current.Services.MemberService.GetById(Id); ApplicationContext.Current.Services.MemberService.Delete(member); } // Delete all content and cmsnode specific data! base.delete(); FireAfterDelete(e); } } /// <summary> /// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider - you must /// call Save() after using this method /// </summary> /// <param name="newPassword"></param> public void ChangePassword(string newPassword) { MemberItem.RawPasswordValue = newPassword; } /// <summary> /// Returns the currently stored password - this may be encrypted or hashed string depending on the active membership provider /// </summary> /// <returns></returns> public string GetPassword() { return MemberItem.RawPasswordValue; } /// <summary> /// Adds the member to group with the specified id /// </summary> /// <param name="GroupId">The id of the group which the member is being added to</param> [MethodImpl(MethodImplOptions.Synchronized)] public void AddGroup(int GroupId) { var e = new AddGroupEventArgs(); e.GroupId = GroupId; FireBeforeAddGroup(e); if (!e.Cancel) { var parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId) }; bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId", parameters) > 0; if (!exists) SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)", parameters); PopulateGroups(); FireAfterAddGroup(e); } } /// <summary> /// Removes the member from the MemberGroup specified /// </summary> /// <param name="GroupId">The MemberGroup from which the Member is removed</param> public void RemoveGroup(int GroupId) { var e = new RemoveGroupEventArgs(); e.GroupId = GroupId; FireBeforeRemoveGroup(e); if (!e.Cancel) { SqlHelper.ExecuteNonQuery( "delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId", SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId)); PopulateGroups(); FireAfterRemoveGroup(e); } } #endregion #region Protected methods protected override XmlNode generateXmlWithoutSaving(XmlDocument xd) { XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", ""); XmlPopulate(xd, ref node, false); node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); return node; } #endregion #region Private methods private void PopulateGroups() { var temp = new Hashtable(); using (var dr = SqlHelper.ExecuteReader( "select memberGroup from cmsMember2MemberGroup where member = @id", SqlHelper.CreateParameter("@id", Id))) { while (dr.Read()) temp.Add(dr.GetInt("memberGroup"), new MemberGroup(dr.GetInt("memberGroup"))); } _groups = temp; } private static string GetCacheKey(int id) { return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id); } [Obsolete("Only use .NET Membership APIs to handle state now", true)] static void ClearMemberState() { // zb-00004 #29956 : refactor cookies names & handling StateHelper.Cookies.Member.Clear(); FormsAuthentication.SignOut(); } #endregion #region MemberHandle functions /// <summary> /// Method is used when logging a member in. /// /// Adds the member to the cache of logged in members /// /// Uses cookiebased recognition /// /// Can be used in the runtime /// </summary> /// <param name="m">The member to log in</param> [Obsolete("Use Membership APIs and FormsAuthentication to handle member login")] public static void AddMemberToCache(Member m) { if (m != null) { var e = new AddToCacheEventArgs(); m.FireBeforeAddToCache(e); if (!e.Cancel) { // Add cookie with member-id, guid and loginname // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members //SetMemberState(m); FormsAuthentication.SetAuthCookie(m.LoginName, true); //cache the member var cachedMember = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Member>( GetCacheKey(m.Id), timeout: TimeSpan.FromMinutes(30), getCacheItem: () => { // Debug information HttpContext.Current.Trace.Write("member", string.Format("Member added to cache: {0}/{1} ({2})", m.Text, m.LoginName, m.Id)); return m; }); m.FireAfterAddToCache(e); } } } // zb-00035 #29931 : remove old cookie code /// <summary> /// Method is used when logging a member in. /// /// Adds the member to the cache of logged in members /// /// Uses cookie or session based recognition /// /// Can be used in the runtime /// </summary> /// <param name="m">The member to log in</param> /// <param name="UseSession">create a persistent cookie</param> /// <param name="TimespanForCookie">Has no effect</param> [Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")] public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie) { if (m != null) { var e = new AddToCacheEventArgs(); m.FireBeforeAddToCache(e); if (!e.Cancel) { // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members //SetMemberState(m, UseSession, TimespanForCookie.TotalDays); FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession); //cache the member var cachedMember = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Member>( GetCacheKey(m.Id), timeout: TimeSpan.FromMinutes(30), getCacheItem: () => { // Debug information HttpContext.Current.Trace.Write("member", string.Format("Member added to cache: {0}/{1} ({2})", m.Text, m.LoginName, m.Id)); return m; }); m.FireAfterAddToCache(e); } } } /// <summary> /// Removes the member from the cache /// /// Can be used in the public website /// </summary> /// <param name="m">Member to remove</param> [Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)] public static void RemoveMemberFromCache(Member m) { RemoveMemberFromCache(m.Id); } /// <summary> /// Removes the member from the cache /// /// Can be used in the public website /// </summary> /// <param name="NodeId">Node Id of the member to remove</param> [Obsolete("Member cache is automatically cleared when members are updated")] public static void RemoveMemberFromCache(int NodeId) { ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(GetCacheKey(NodeId)); } /// <summary> /// Deletes the member cookie from the browser /// /// Can be used in the public website /// </summary> /// <param name="m">Member</param> [Obsolete("Obsolete, use the ClearMemberFromClient(int NodeId) instead", false)] public static void ClearMemberFromClient(Member m) { if (m != null) ClearMemberFromClient(m.Id); else { // If the member doesn't exists as an object, we'll just make sure that cookies are cleared // zb-00035 #29931 : cleanup member state management ClearMemberState(); } FormsAuthentication.SignOut(); } /// <summary> /// Deletes the member cookie from the browser /// /// Can be used in the public website /// </summary> /// <param name="NodeId">The Node id of the member to clear</param> [Obsolete("Use FormsAuthentication.SignOut instead")] public static void ClearMemberFromClient(int NodeId) { // zb-00035 #29931 : cleanup member state management // NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members // ClearMemberState(); FormsAuthentication.SignOut(); RemoveMemberFromCache(NodeId); } /// <summary> /// Retrieve a collection of members in the cache /// /// Can be used from the public website /// </summary> /// <returns>A collection of cached members</returns> public static Hashtable CachedMembers() { var h = new Hashtable(); var items = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItemsByKeySearch<Member>( CacheKeys.MemberBusinessLogicCacheKey); foreach (var i in items) { h.Add(i.Id, i); } return h; } /// <summary> /// Retrieve a member from the cache /// /// Can be used from the public website /// </summary> /// <param name="id">Id of the member</param> /// <returns>If the member is cached it returns the member - else null</returns> public static Member GetMemberFromCache(int id) { Hashtable members = CachedMembers(); if (members.ContainsKey(id)) return (Member)members[id]; else return null; } /// <summary> /// An indication if the current visitor is logged in /// /// Can be used from the public website /// </summary> /// <returns>True if the the current visitor is logged in</returns> [Obsolete("Use the standard ASP.Net procedures for hanlding FormsAuthentication, simply check the HttpContext.User and HttpContext.User.Identity.IsAuthenticated to determine if a member is logged in or not")] public static bool IsLoggedOn() { return HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated; } /// <summary> /// Gets the current visitors memberid /// </summary> /// <returns>The current visitors members id, if the visitor is not logged in it returns 0</returns> public static int CurrentMemberId() { int currentMemberId = 0; // For backwards compatibility between umbraco members and .net membership if (HttpContext.Current.User.Identity.IsAuthenticated) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); var member = provider.GetCurrentUser(); if (member == null) { throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); } int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId); } return currentMemberId; } /// <summary> /// Get the current member /// </summary> /// <returns>Returns the member, if visitor is not logged in: null</returns> public static Member GetCurrentMember() { try { if (HttpContext.Current.User.Identity.IsAuthenticated) { var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); var member = provider.GetCurrentUser(); if (member == null) { throw new InvalidOperationException("No member object found with username " + provider.GetCurrentUserName()); } int currentMemberId = 0; if (int.TryParse(member.ProviderUserKey.ToString(), out currentMemberId)) { var m = new Member(currentMemberId); return m; } } } catch (Exception ex) { LogHelper.Error<Member>("An error occurred in GetCurrentMember", ex); } return null; } #endregion #region Events /// <summary> /// The save event handler /// </summary> public delegate void SaveEventHandler(Member sender, SaveEventArgs e); /// <summary> /// The new event handler /// </summary> public delegate void NewEventHandler(Member sender, NewEventArgs e); /// <summary> /// The delete event handler /// </summary> public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e); /// <summary> /// The add to cache event handler /// </summary> public delegate void AddingToCacheEventHandler(Member sender, AddToCacheEventArgs e); /// <summary> /// The add group event handler /// </summary> public delegate void AddingGroupEventHandler(Member sender, AddGroupEventArgs e); /// <summary> /// The remove group event handler /// </summary> public delegate void RemovingGroupEventHandler(Member sender, RemoveGroupEventArgs e); /// <summary> /// Occurs when [before save]. /// </summary> new public static event SaveEventHandler BeforeSave; /// <summary> /// Raises the <see cref="E:BeforeSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> new protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) { BeforeSave(this, e); } } new public static event SaveEventHandler AfterSave; new protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) { AfterSave(this, e); } } public static event NewEventHandler New; protected virtual void OnNew(NewEventArgs e) { if (New != null) { New(this, e); } } public static event AddingGroupEventHandler BeforeAddGroup; protected virtual void FireBeforeAddGroup(AddGroupEventArgs e) { if (BeforeAddGroup != null) { BeforeAddGroup(this, e); } } public static event AddingGroupEventHandler AfterAddGroup; protected virtual void FireAfterAddGroup(AddGroupEventArgs e) { if (AfterAddGroup != null) { AfterAddGroup(this, e); } } public static event RemovingGroupEventHandler BeforeRemoveGroup; protected virtual void FireBeforeRemoveGroup(RemoveGroupEventArgs e) { if (BeforeRemoveGroup != null) { BeforeRemoveGroup(this, e); } } public static event RemovingGroupEventHandler AfterRemoveGroup; protected virtual void FireAfterRemoveGroup(RemoveGroupEventArgs e) { if (AfterRemoveGroup != null) { AfterRemoveGroup(this, e); } } public static event AddingToCacheEventHandler BeforeAddToCache; protected virtual void FireBeforeAddToCache(AddToCacheEventArgs e) { if (BeforeAddToCache != null) { BeforeAddToCache(this, e); } } public static event AddingToCacheEventHandler AfterAddToCache; protected virtual void FireAfterAddToCache(AddToCacheEventArgs e) { if (AfterAddToCache != null) { AfterAddToCache(this, e); } } new public static event DeleteEventHandler BeforeDelete; new protected virtual void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) { BeforeDelete(this, e); } } new public static event DeleteEventHandler AfterDelete; new protected virtual void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) { AfterDelete(this, e); } } #endregion #region Membership helper class used for encryption methods /// <summary> /// ONLY FOR INTERNAL USE. /// This is needed due to a design flaw where the Umbraco membership provider is located /// in a separate project referencing this project, which means we can't call special methods /// directly on the UmbracoMemberShipMember class. /// This is a helper implementation only to be able to use the encryption functionality /// of the membership provides (which are protected). /// /// ... which means this class should have been marked internal with a Friend reference to the other assembly right?? /// </summary> internal class MemberShipHelper : MembershipProvider { public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public string EncodePassword(string password, MembershipPasswordFormat pwFormat) { string encodedPassword = password; switch (pwFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: HMACSHA1 hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; } return encodedPassword; } public override bool EnablePasswordReset { get { throw new NotImplementedException(); } } public override bool EnablePasswordRetrieval { get { throw new NotImplementedException(); } } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } public override int MaxInvalidPasswordAttempts { get { throw new NotImplementedException(); } } public override int MinRequiredNonAlphanumericCharacters { get { throw new NotImplementedException(); } } public override int MinRequiredPasswordLength { get { throw new NotImplementedException(); } } public override int PasswordAttemptWindow { get { throw new NotImplementedException(); } } public override MembershipPasswordFormat PasswordFormat { get { throw new NotImplementedException(); } } public override string PasswordStrengthRegularExpression { get { throw new NotImplementedException(); } } public override bool RequiresQuestionAndAnswer { get { throw new NotImplementedException(); } } public override bool RequiresUniqueEmail { get { throw new NotImplementedException(); } } public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { throw new NotImplementedException(); } } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonDictionaryContract : JsonContainerContract { /// <summary> /// Gets or sets the dictionary key resolver. /// </summary> /// <value>The dictionary key resolver.</value> public Func<string, string> DictionaryKeyResolver { get; set; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary keys. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary keys.</value> public Type DictionaryKeyType { get; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary values. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary values.</value> public Type DictionaryValueType { get; } internal JsonContract KeyContract { get; set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; } private readonly ConstructorInfo _parameterizedConstructor; private ObjectConstructor<object> _overrideCreator; private ObjectConstructor<object> _parameterizedCreator; internal ObjectConstructor<object> ParameterizedCreator { get { if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } return _parameterizedCreator; } } /// <summary> /// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>. /// </summary> /// <value>The function used to create the object.</value> public ObjectConstructor<object> OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; } /// <summary> /// Gets a value indicating whether the creator has a parameter with the dictionary values. /// </summary> /// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value> public bool HasParameterizedCreator { get; set; } internal bool HasParameterizedCreatorInternal => (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); /// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } else if (underlyingType.IsGenericType()) { // ConcurrentDictionary<,> + IDictionary setter + null value = error // wrap to use generic setter // https://github.com/JamesNK/Newtonsoft.Json/issues/1582 Type typeDefinition = underlyingType.GetGenericTypeDefinition(); if (typeDefinition.FullName == JsonTypeReflector.ConcurrentDictionaryTypeName) { ShouldCreateWrapper = true; } } #if HAVE_READ_ONLY_COLLECTIONS IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if HAVE_READ_ONLY_COLLECTIONS else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); } IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary<object, object>); } } if (keyType != null && valueType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor( CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType), typeof(IDictionary<,>).MakeGenericType(keyType, valueType)); #if HAVE_FSHARP_TYPES if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } if (!typeof(IDictionary).IsAssignableFrom(CreatedType)) { ShouldCreateWrapper = true; } DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _)) { ShouldCreateWrapper = true; } } #endif if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( underlyingType, DictionaryKeyType, DictionaryValueType, out Type immutableCreatedType, out ObjectConstructor<object> immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } } internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedDictionary)_genericWrapperCreator(dictionary); } internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) { Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object)); _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType); } return (IDictionary)_genericTemporaryDictionaryCreator(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Rubber_Ducky { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteEffects sfx; Texture2D duckies; float[] rotations = new float[6]; bool[] events = new bool[5]; int rotateDuck = -1; int moveDuckS = -1, moveDuckB = -1; int duckSX = -1, duckBX = -1; bool motionDucks = false; bool hitB, hitS; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here for (int i = 0; i < rotations.Length; i++) { if (i == 4) rotations[i] = 180; else rotations[i] = 0; } base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here duckies = this.Content.Load<Texture2D>("Duckies"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState kb = Keyboard.GetState(); // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); // TODO: Add your update logic here if (kb.IsKeyDown(Keys.A)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[0] = true; } else if (kb.IsKeyDown(Keys.E)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[1] = true; } else if (kb.IsKeyDown(Keys.O)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[2] = true; } else if (kb.IsKeyDown(Keys.NumPad1)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 1; } else if (kb.IsKeyDown(Keys.NumPad2)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 2; } else if (kb.IsKeyDown(Keys.NumPad3)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 3; } else if (kb.IsKeyDown(Keys.NumPad4)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 4; } else if (kb.IsKeyDown(Keys.NumPad5)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 5; } else if (kb.IsKeyDown(Keys.NumPad6)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[3] = true; rotateDuck = 6; } else if (kb.IsKeyDown(Keys.D1) || kb.IsKeyDown(Keys.D6)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[4] = true; duckSX = 0; duckBX = (GraphicsDevice.Viewport.Width / 2) - 50; moveDuckS = 1; moveDuckB = 6; } else if (kb.IsKeyDown(Keys.D2) || kb.IsKeyDown(Keys.D5)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[4] = true; duckSX = 0; duckBX = (GraphicsDevice.Viewport.Width / 2) - 50; moveDuckS = 2; moveDuckB = 5; } else if (kb.IsKeyDown(Keys.D3) || kb.IsKeyDown(Keys.D4)) { for (int i = 0; i < events.Length; i++) events[i] = false; events[4] = true; duckSX = 0; duckBX = (GraphicsDevice.Viewport.Width / 2) - 50; moveDuckS = 3; moveDuckB = 4; } if (events[0]) { for (int i = 0; i < rotations.Length; i++) rotations[i] -= 10; motionDucks = false; } else if (events[1]) { for (int i = 0; i < rotations.Length; i++) { if (i % 2 != 0) rotations[i] += 30; } motionDucks = false; } else if (events[2]) { for (int i = 0; i < rotations.Length; i++) { if (i % 2 == 0) rotations[i] -= 30; } motionDucks = false; } else if (events[3]) { rotations[rotateDuck - 1] += 30; motionDucks = false; } else if (events[4]) { motionDucks = true; if (hitS) duckSX -= 4; else duckSX += 4; if (hitB) duckBX -= 2; else duckBX += 2; } if (duckSX == GraphicsDevice.Viewport.Width - 100) hitS = true; else if (duckSX == 0) hitS = false; if (duckBX == GraphicsDevice.Viewport.Width - 100) hitB = true; else if (duckBX == 0) hitB = false; if (kb.IsKeyDown(Keys.Space)) { for (int i = 0; i < rotations.Length; i++) { if (i == 4) rotations[i] = 180; else rotations[i] = 0; } for (int i = 0; i < events.Length; i++) events[i] = false; rotateDuck = moveDuckS = moveDuckB = duckBX = duckSX = -1; motionDucks = false; } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // TODO: Add your drawing code here if (!motionDucks) { // 1 spriteBatch.Draw(duckies, new Rectangle(100, 100, 100, 100), new Rectangle(0, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[0]), new Vector2(100), sfx, 0); // 2 spriteBatch.Draw(duckies, new Rectangle(310, 100, 100, 100), new Rectangle(200, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[1]), new Vector2(100), sfx, 0); // 3 spriteBatch.Draw(duckies, new Rectangle(510, 100, 100, 100), new Rectangle(400, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[2]), new Vector2(100), sfx, 0); // 4 spriteBatch.Draw(duckies, new Rectangle(100, 230, 100, 100), new Rectangle(600, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[3]), new Vector2(100), sfx, 0); // 5 spriteBatch.Draw(duckies, new Rectangle(310, 230, 100, 100), new Rectangle(800, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[4]), new Vector2(100), sfx, 0); // 6 spriteBatch.Draw(duckies, new Rectangle(510, 230, 100, 100), new Rectangle(1000, 0, 200, 177), Color.White, (float)((Math.PI / 180) * rotations[5]), new Vector2(100), sfx, 0); } else { Rectangle smallRct = new Rectangle((moveDuckS * 200) - 200, 0, 200, 177); Rectangle bigRct = new Rectangle((moveDuckB * 200) - 200, 0, 200, 177); spriteBatch.Draw(duckies, new Rectangle(duckSX, (GraphicsDevice.Viewport.Height / 2) - 50, 100, 100), smallRct, Color.White); spriteBatch.Draw(duckies, new Rectangle(duckBX, 0, 100, 100), bigRct, Color.White); } spriteBatch.End(); base.Draw(gameTime); } } }
// <copyright file="XmlUnmarshallingContext.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using BeanIO.Stream; namespace BeanIO.Internal.Parser.Format.Xml { internal class XmlUnmarshallingContext : UnmarshallingContext { /// <summary> /// This stack of elements is used to store the last XML node parsed for a field or bean collection. /// </summary> private readonly Stack<XElement> _elementStack = new Stack<XElement>(); /// <summary> /// Store previously matched groups for parsing subsequent records in a record group /// </summary> private readonly IXmlNode[] _groupStack; /// <summary> /// The DOM to parse /// </summary> private XDocument _document; /// <summary> /// The last parsed node in the document, which is the parent node of the next field/bean to parse /// </summary> private XElement _position; /// <summary> /// Initializes a new instance of the <see cref="XmlUnmarshallingContext"/> class. /// </summary> /// <param name="groupDepth">the maximum depth of an element mapped to a <see cref="Group"/> in the DOM</param> public XmlUnmarshallingContext(int groupDepth) { _groupStack = new IXmlNode[groupDepth]; } /// <summary> /// Gets the XML document object model (DOM) for the current record. /// </summary> public XDocument Document => _document; /// <summary> /// Gets the current unmarshalled position in the DOM tree, or null /// if a node has not been matched yet. /// </summary> public XElement Position => _position; /// <summary> /// Gets or sets the last parsed DOM element for a field or bean collection. /// </summary> public XElement PreviousElement { get { return _elementStack.Peek(); } set { _elementStack.Pop(); _elementStack.Push(value); } } /// <summary> /// Sets the value of the record returned from the <see cref="IRecordReader"/> /// </summary> /// <param name="value">the record value read by a <see cref="IRecordReader"/></param> public override void SetRecordValue(object value) { var node = (XNode)value; switch (node.NodeType) { case XmlNodeType.Document: _document = (XDocument)value; _position = null; break; case XmlNodeType.Element: _document = node.Document; _position = (XElement)node; break; default: _document = node.Document; _position = null; break; } } /// <summary> /// Pushes an <see cref="IIteration"/> onto a stack for adjusting /// field positions and indices. /// </summary> /// <param name="iteration">the <see cref="IIteration"/> to push</param> public override void PushIteration(IIteration iteration) { base.PushIteration(iteration); _elementStack.Push(null); } /// <summary> /// Pops the last <see cref="IIteration"/> pushed onto the stack. /// </summary> /// <returns>the top most <see cref="IIteration"/></returns> public override IIteration PopIteration() { _elementStack.Pop(); return base.PopIteration(); } /// <summary> /// Updates <see cref="Position"/> by finding a child of the current position /// that matches a given node. /// </summary> /// <remarks> /// If <tt>isGroup</tt> is true, the node is indexed by its depth so that /// calls to this method for subsequent records in the same group can /// update <see cref="Position"/> according to the depth of the record. /// </remarks> /// <param name="node">the <see cref="IXmlNode"/> to match</param> /// <param name="depth">e depth of the node in the DOM tree</param> /// <param name="isGroup">whether the node is mapped to a <see cref="Group"/></param> /// <returns>the matched node or null if not matched</returns> public virtual XElement PushPosition(IXmlNode node, int depth, bool isGroup) { // if the pushed node is a group node, add it to the group stack // for the workaround below if (isGroup) _groupStack[depth] = node; // this is a workaround for handling bean objects that span multiple records // once the first record is identified, parent groups are not called for // subsequent records so the current position will be null even though we // already deeper in the parser tree if (_position == null && depth > 0) { for (int i = 0; i < depth; i++) { _position = FindElement(_groupStack[i]); if (_position == null) return null; } // if we still don't match, update the position back to null var element = PushPosition(node); if (element == null) _position = null; return element; } return PushPosition(node); } /// <summary> /// Updates <see cref="Position"/> by finding a child of the current position /// that matches a given node. /// </summary> /// <param name="node">the <see cref="IXmlNode"/> to match</param> /// <returns>the matching element, or null if not found</returns> public virtual XElement PushPosition(IXmlNode node) { var element = FindElement(node); if (element == null) return null; _position = element; return _position; } /// <summary> /// Updates <see cref="Position"/> to its parent (element), or null if the parent element is the document itself. /// </summary> public virtual void PopPosition() { if (_position == null) return; var n = _position.Parent; if (n == null || n.NodeType == XmlNodeType.Document) { _position = null; } else { _position = n; } } /// <summary> /// Finds a child element of the current <see cref="Position"/>. /// </summary> /// <param name="node">the <see cref="IXmlNode"/></param> /// <returns>the matched element or null if not found</returns> public virtual XElement FindElement(IXmlNode node) { var parent = _position; XElement element; if (node.IsRepeating) { int index = GetRelativeFieldIndex(); if (index > 0) { element = XmlNodeUtil.FindSibling(PreviousElement, node, node.GetNameVariants()); } else { element = XmlNodeUtil.FindChild(parent, node, index, node.GetNameVariants()); } if (element != null) { PreviousElement = element; } } else { if (parent == null) { element = XmlNodeUtil.FindChild(_document, node, 0, node.GetNameVariants()); } else { element = XmlNodeUtil.FindChild(parent, node, 0, node.GetNameVariants()); } } return element; } /// <summary> /// Converts a <see cref="XElement"/> to a record value. /// </summary> /// <param name="element">The <see cref="XElement"/> to convert</param> /// <returns>the record value, or null if not supported</returns> public override object ToRecordValue(XContainer element) { return element; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Security; namespace Python.Runtime { /// <summary> /// Performs data conversions between managed types and Python types. /// </summary> [SuppressUnmanagedCodeSecurity] internal class Converter { private Converter() { } private static Type objectType; private static Type stringType; private static Type singleType; private static Type doubleType; private static Type int16Type; private static Type int32Type; private static Type int64Type; private static Type boolType; private static Type typeType; static Converter() { objectType = typeof(Object); stringType = typeof(String); int16Type = typeof(Int16); int32Type = typeof(Int32); int64Type = typeof(Int64); singleType = typeof(Single); doubleType = typeof(Double); boolType = typeof(Boolean); typeType = typeof(Type); } /// <summary> /// Given a builtin Python type, return the corresponding CLR type. /// </summary> internal static Type? GetTypeByAlias(BorrowedReference op) { if (op == Runtime.PyStringType) return stringType; if (op == Runtime.PyUnicodeType) return stringType; if (op == Runtime.PyLongType) return int32Type; if (op == Runtime.PyLongType) return int64Type; if (op == Runtime.PyFloatType) return doubleType; if (op == Runtime.PyBoolType) return boolType; return null; } internal static BorrowedReference GetPythonTypeByAlias(Type op) { if (op == stringType) return Runtime.PyUnicodeType.Reference; if (op == int16Type) return Runtime.PyLongType.Reference; if (op == int32Type) return Runtime.PyLongType.Reference; if (op == int64Type) return Runtime.PyLongType.Reference; if (op == doubleType) return Runtime.PyFloatType.Reference; if (op == singleType) return Runtime.PyFloatType.Reference; if (op == boolType) return Runtime.PyBoolType.Reference; return BorrowedReference.Null; } internal static NewReference ToPython<T>(T value) => ToPython(value, typeof(T)); private static readonly Func<object, bool> IsTransparentProxy = GetIsTransparentProxy(); private static bool Never(object _) => false; private static Func<object, bool> GetIsTransparentProxy() { var remoting = typeof(int).Assembly.GetType("System.Runtime.Remoting.RemotingServices"); if (remoting is null) return Never; var isProxy = remoting.GetMethod("IsTransparentProxy", new[] { typeof(object) }); if (isProxy is null) return Never; return (Func<object, bool>)Delegate.CreateDelegate( typeof(Func<object, bool>), isProxy, throwOnBindFailure: true); } internal static NewReference ToPythonDetectType(object? value) => value is null ? new NewReference(Runtime.PyNone) : ToPython(value, value.GetType()); internal static NewReference ToPython(object? value, Type type) { if (value is PyObject pyObj) { return new NewReference(pyObj); } // Null always converts to None in Python. if (value == null) { return new NewReference(Runtime.PyNone); } if (EncodableByUser(type, value)) { var encoded = PyObjectConversions.TryEncode(value, type); if (encoded != null) { return new NewReference(encoded); } } if (type.IsInterface) { var ifaceObj = (InterfaceObject)ClassManager.GetClassImpl(type); return ifaceObj.TryWrapObject(value); } if (type.IsArray || type.IsEnum) { return CLRObject.GetReference(value, type); } // it the type is a python subclass of a managed type then return the // underlying python object rather than construct a new wrapper object. var pyderived = value as IPythonDerivedType; if (null != pyderived) { if (!IsTransparentProxy(pyderived)) return ClassDerivedObject.ToPython(pyderived); } // ModuleObjects are created in a way that their wrapping them as // a CLRObject fails, the ClassObject has no tpHandle. Return the // pyHandle as is, do not convert. if (value is ModuleObject modobj) { throw new NotImplementedException(); } // hmm - from Python, we almost never care what the declared // type is. we'd rather have the object bound to the actual // implementing class. type = value.GetType(); if (type.IsEnum) { return CLRObject.GetReference(value, type); } TypeCode tc = Type.GetTypeCode(type); switch (tc) { case TypeCode.Object: return CLRObject.GetReference(value, type); case TypeCode.String: return Runtime.PyString_FromString((string)value); case TypeCode.Int32: return Runtime.PyInt_FromInt32((int)value); case TypeCode.Boolean: if ((bool)value) { return new NewReference(Runtime.PyTrue); } return new NewReference(Runtime.PyFalse); case TypeCode.Byte: return Runtime.PyInt_FromInt32((byte)value); case TypeCode.Char: return Runtime.PyUnicode_FromOrdinal((int)((char)value)); case TypeCode.Int16: return Runtime.PyInt_FromInt32((short)value); case TypeCode.Int64: return Runtime.PyLong_FromLongLong((long)value); case TypeCode.Single: return Runtime.PyFloat_FromDouble((float)value); case TypeCode.Double: return Runtime.PyFloat_FromDouble((double)value); case TypeCode.SByte: return Runtime.PyInt_FromInt32((sbyte)value); case TypeCode.UInt16: return Runtime.PyInt_FromInt32((ushort)value); case TypeCode.UInt32: return Runtime.PyLong_FromUnsignedLongLong((uint)value); case TypeCode.UInt64: return Runtime.PyLong_FromUnsignedLongLong((ulong)value); default: return CLRObject.GetReference(value, type); } } static bool EncodableByUser(Type type, object value) { TypeCode typeCode = Type.GetTypeCode(type); return type.IsEnum || typeCode is TypeCode.DateTime or TypeCode.Decimal || typeCode == TypeCode.Object && value.GetType() != typeof(object) && value is not Type; } /// <summary> /// In a few situations, we don't have any advisory type information /// when we want to convert an object to Python. /// </summary> internal static NewReference ToPythonImplicit(object? value) { if (value == null) { return new NewReference(Runtime.PyNone); } return ToPython(value, objectType); } /// <summary> /// Return a managed object for the given Python object, taking funny /// byref types into account. /// </summary> /// <param name="value">A Python object</param> /// <param name="type">The desired managed type</param> /// <param name="result">Receives the managed object</param> /// <param name="setError">If true, call <c>Exceptions.SetError</c> with the reason for failure.</param> /// <returns>True on success</returns> internal static bool ToManaged(BorrowedReference value, Type type, out object? result, bool setError) { if (type.IsByRef) { type = type.GetElementType(); } return Converter.ToManagedValue(value, type, out result, setError); } internal static bool ToManagedValue(BorrowedReference value, Type obType, out object? result, bool setError) { if (obType == typeof(PyObject)) { result = new PyObject(value); return true; } if (obType.IsSubclassOf(typeof(PyObject)) && !obType.IsAbstract && obType.GetConstructor(new[] { typeof(PyObject) }) is { } ctor) { var untyped = new PyObject(value); result = ToPyObjectSubclass(ctor, untyped, setError); return result is not null; } // Common case: if the Python value is a wrapped managed object // instance, just return the wrapped object. result = null; switch (ManagedType.GetManagedObject(value)) { case CLRObject co: object tmp = co.inst; if (obType.IsInstanceOfType(tmp)) { result = tmp; return true; } if (setError) { string typeString = tmp is null ? "null" : tmp.GetType().ToString(); Exceptions.SetError(Exceptions.TypeError, $"{typeString} value cannot be converted to {obType}"); } return false; case ClassBase cb: if (!cb.type.Valid) { Exceptions.SetError(Exceptions.TypeError, cb.type.DeletedMessage); return false; } result = cb.type.Value; return true; case null: break; default: throw new ArgumentException("We should never receive instances of other managed types"); } if (value == Runtime.PyNone && !obType.IsValueType) { result = null; return true; } if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>)) { if( value == Runtime.PyNone ) { result = null; return true; } // Set type to underlying type obType = obType.GetGenericArguments()[0]; } if (obType.ContainsGenericParameters) { if (setError) { Exceptions.SetError(Exceptions.TypeError, $"Cannot create an instance of the open generic type {obType}"); } return false; } if (obType.IsArray) { return ToArray(value, obType, out result, setError); } // Conversion to 'Object' is done based on some reasonable default // conversions (Python string -> managed string). if (obType == objectType) { if (Runtime.IsStringType(value)) { return ToPrimitive(value, stringType, out result, setError); } if (Runtime.PyBool_Check(value)) { return ToPrimitive(value, boolType, out result, setError); } if (Runtime.PyFloat_Check(value)) { return ToPrimitive(value, doubleType, out result, setError); } // give custom codecs a chance to take over conversion of ints and sequences BorrowedReference pyType = Runtime.PyObject_TYPE(value); if (PyObjectConversions.TryDecode(value, pyType, obType, out result)) { return true; } if (Runtime.PyInt_Check(value)) { result = new PyInt(value); return true; } if (Runtime.PySequence_Check(value)) { return ToArray(value, typeof(object[]), out result, setError); } result = new PyObject(value); return true; } // Conversion to 'Type' is done using the same mappings as above for objects. if (obType == typeType) { if (value == Runtime.PyStringType) { result = stringType; return true; } if (value == Runtime.PyBoolType) { result = boolType; return true; } if (value == Runtime.PyLongType) { result = typeof(PyInt); return true; } if (value == Runtime.PyFloatType) { result = doubleType; return true; } if (value == Runtime.PyListType) { result = typeof(PyList); return true; } if (value == Runtime.PyTupleType) { result = typeof(PyTuple); return true; } if (setError) { Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type"); } return false; } if (DecodableByUser(obType)) { BorrowedReference pyType = Runtime.PyObject_TYPE(value); if (PyObjectConversions.TryDecode(value, pyType, obType, out result)) { return true; } } return ToPrimitive(value, obType, out result, setError); } /// <remarks> /// Unlike <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>, /// this method does not have a <c>setError</c> parameter, because it should /// only be called after <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>. /// </remarks> internal static bool ToManagedExplicit(BorrowedReference value, Type obType, out object? result) { result = null; // this method would potentially clean any existing error resulting in information loss Debug.Assert(Runtime.PyErr_Occurred() == null); string? converterName = IsInteger(obType) ? "__int__" : IsFloatingNumber(obType) ? "__float__" : null; if (converterName is null) return false; Debug.Assert(obType.IsPrimitive); using var converter = Runtime.PyObject_GetAttrString(value, converterName); if (converter.IsNull()) { Exceptions.Clear(); return false; } using var explicitlyCoerced = Runtime.PyObject_CallObject(converter.Borrow(), BorrowedReference.Null); if (explicitlyCoerced.IsNull()) { Exceptions.Clear(); return false; } return ToPrimitive(explicitlyCoerced.Borrow(), obType, out result, false); } static object? ToPyObjectSubclass(ConstructorInfo ctor, PyObject instance, bool setError) { try { return ctor.Invoke(new object[] { instance }); } catch (TargetInvocationException ex) { if (setError) { Exceptions.SetError(ex.InnerException); } return null; } catch (SecurityException ex) { if (setError) { Exceptions.SetError(ex); } return null; } } static bool DecodableByUser(Type type) { TypeCode typeCode = Type.GetTypeCode(type); return type.IsEnum || typeCode is TypeCode.Object or TypeCode.Decimal or TypeCode.DateTime; } internal delegate bool TryConvertFromPythonDelegate(BorrowedReference pyObj, out object? result); internal static int ToInt32(BorrowedReference value) { nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { throw PythonException.ThrowLastAsClrException(); } return checked((int)num); } /// <summary> /// Convert a Python value to an instance of a primitive managed type. /// </summary> private static bool ToPrimitive(BorrowedReference value, Type obType, out object? result, bool setError) { result = null; if (obType.IsEnum) { if (setError) { Exceptions.SetError(Exceptions.TypeError, "since Python.NET 3.0 int can not be converted to Enum implicitly. Use Enum(int_value)"); } return false; } TypeCode tc = Type.GetTypeCode(obType); switch (tc) { case TypeCode.String: string? st = Runtime.GetManagedString(value); if (st == null) { goto type_error; } result = st; return true; case TypeCode.Int32: { // Python3 always use PyLong API nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > Int32.MaxValue || num < Int32.MinValue) { goto overflow; } result = (int)num; return true; } case TypeCode.Boolean: if (value == Runtime.PyTrue) { result = true; return true; } if (value == Runtime.PyFalse) { result = false; return true; } if (setError) { goto type_error; } return false; case TypeCode.Byte: { if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) { IntPtr bytePtr = Runtime.PyBytes_AsString(value); result = (byte)Marshal.ReadByte(bytePtr); return true; } goto type_error; } nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > Byte.MaxValue || num < Byte.MinValue) { goto overflow; } result = (byte)num; return true; } case TypeCode.SByte: { if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) { IntPtr bytePtr = Runtime.PyBytes_AsString(value); result = (sbyte)Marshal.ReadByte(bytePtr); return true; } goto type_error; } nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > SByte.MaxValue || num < SByte.MinValue) { goto overflow; } result = (sbyte)num; return true; } case TypeCode.Char: { if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) { IntPtr bytePtr = Runtime.PyBytes_AsString(value); result = (char)Marshal.ReadByte(bytePtr); return true; } goto type_error; } else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType)) { if (Runtime.PyUnicode_GetLength(value) == 1) { IntPtr unicodePtr = Runtime.PyUnicode_AsUnicode(value); Char[] buff = new Char[1]; Marshal.Copy(unicodePtr, buff, 0, 1); result = buff[0]; return true; } goto type_error; } nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > Char.MaxValue || num < Char.MinValue) { goto overflow; } result = (char)num; return true; } case TypeCode.Int16: { nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > Int16.MaxValue || num < Int16.MinValue) { goto overflow; } result = (short)num; return true; } case TypeCode.Int64: { if (Runtime.Is32Bit) { if (!Runtime.PyLong_Check(value)) { goto type_error; } long? num = Runtime.PyLong_AsLongLong(value); if (num is null) { goto convert_error; } result = num.Value; return true; } else { nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } result = (long)num; return true; } } case TypeCode.UInt16: { nint num = Runtime.PyLong_AsSignedSize_t(value); if (num == -1 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > UInt16.MaxValue || num < UInt16.MinValue) { goto overflow; } result = (ushort)num; return true; } case TypeCode.UInt32: { nuint num = Runtime.PyLong_AsUnsignedSize_t(value); if (num == unchecked((nuint)(-1)) && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > UInt32.MaxValue) { goto overflow; } result = (uint)num; return true; } case TypeCode.UInt64: { ulong? num = Runtime.PyLong_AsUnsignedLongLong(value); if (num is null) { goto convert_error; } result = num.Value; return true; } case TypeCode.Single: { if (!Runtime.PyFloat_Check(value) && !Runtime.PyInt_Check(value)) { goto type_error; } double num = Runtime.PyFloat_AsDouble(value); if (num == -1.0 && Exceptions.ErrorOccurred()) { goto convert_error; } if (num > Single.MaxValue || num < Single.MinValue) { if (!double.IsInfinity(num)) { goto overflow; } } result = (float)num; return true; } case TypeCode.Double: { if (!Runtime.PyFloat_Check(value) && !Runtime.PyInt_Check(value)) { goto type_error; } double num = Runtime.PyFloat_AsDouble(value); if (num == -1.0 && Exceptions.ErrorOccurred()) { goto convert_error; } result = num; return true; } default: goto type_error; } convert_error: if (!setError) { Exceptions.Clear(); } return false; type_error: if (setError) { string tpName = Runtime.PyObject_GetTypeName(value); Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}"); } return false; overflow: // C# level overflow error if (setError) { Exceptions.SetError(Exceptions.OverflowError, "value too large to convert"); } return false; } private static void SetConversionError(BorrowedReference value, Type target) { // PyObject_Repr might clear the error Runtime.PyErr_Fetch(out var causeType, out var causeVal, out var causeTrace); var ob = Runtime.PyObject_Repr(value); string src = "'object has no repr'"; if (ob.IsNull()) { Exceptions.Clear(); } else { src = Runtime.GetManagedString(ob.Borrow()) ?? src; } ob.Dispose(); Runtime.PyErr_Restore(causeType.StealNullable(), causeVal.StealNullable(), causeTrace.StealNullable()); Exceptions.RaiseTypeError($"Cannot convert {src} to {target}"); } /// <summary> /// Convert a Python value to a correctly typed managed array instance. /// The Python value must support the Python iterator protocol or and the /// items in the sequence must be convertible to the target array type. /// </summary> private static bool ToArray(BorrowedReference value, Type obType, out object? result, bool setError) { Type elementType = obType.GetElementType(); result = null; using var IterObject = Runtime.PyObject_GetIter(value); if (IterObject.IsNull()) { if (setError) { SetConversionError(value, obType); } else { // PyObject_GetIter will have set an error Exceptions.Clear(); } return false; } IList list; try { // MakeGenericType can throw because elementType may not be a valid generic argument even though elementType[] is a valid array type. // For example, if elementType is a pointer type. // See https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype#System_Type_MakeGenericType_System_Type var constructedListType = typeof(List<>).MakeGenericType(elementType); bool IsSeqObj = Runtime.PySequence_Check(value); object[] constructorArgs = Array.Empty<object>(); if (IsSeqObj) { var len = Runtime.PySequence_Size(value); if (len >= 0) { if (len <= int.MaxValue) { constructorArgs = new object[] { (int)len }; } } else { // for the sequences, that explicitly deny calling __len__() Exceptions.Clear(); } } // CreateInstance can throw even if MakeGenericType succeeded. // See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_ list = (IList)Activator.CreateInstance(constructedListType, args: constructorArgs); } catch (Exception e) { if (setError) { Exceptions.SetError(e); SetConversionError(value, obType); } return false; } while (true) { using var item = Runtime.PyIter_Next(IterObject.Borrow()); if (item.IsNull()) break; if (!Converter.ToManaged(item.Borrow(), elementType, out var obj, setError)) { return false; } list.Add(obj); } if (Exceptions.ErrorOccurred()) { if (!setError) Exceptions.Clear(); return false; } Array items = Array.CreateInstance(elementType, list.Count); list.CopyTo(items, 0); result = items; return true; } internal static bool IsFloatingNumber(Type type) => type == typeof(float) || type == typeof(double); internal static bool IsInteger(Type type) => type == typeof(Byte) || type == typeof(SByte) || type == typeof(Int16) || type == typeof(UInt16) || type == typeof(Int32) || type == typeof(UInt32) || type == typeof(Int64) || type == typeof(UInt64); } public static class ConverterExtension { public static PyObject ToPython(this object? o) { if (o is null) return Runtime.None; return Converter.ToPython(o, o.GetType()).MoveToPyObject(); } } }
// // FieldPage.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 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.Collections.Generic; using Gtk; using Hyena.Gui; using Banshee.Collection; namespace Banshee.Gui.TrackEditor { public class FieldPage : VBox { public delegate string FieldLabelClosure (EditorTrackInfo track, Widget widget); public delegate void FieldValueClosure (EditorTrackInfo track, Widget widget); private TrackEditorDialog dialog; protected TrackEditorDialog Dialog { get { return dialog; } } private EditorTrackInfo current_track; protected EditorTrackInfo CurrentTrack { get { return current_track; } } public struct FieldSlot { public Widget Parent; public Widget Container; public Widget Label; public Widget Field; public Button SyncButton; public FieldLabelClosure LabelClosure; public FieldValueClosure ReadClosure; public FieldValueClosure WriteClosure; } private object tooltip_host; private List<FieldSlot> field_slots = new List<FieldSlot> (); public IEnumerable<FieldSlot> FieldSlots { get { return field_slots; } } public FieldPage () { Spacing = EditorUtilities.RowSpacing; tooltip_host = TooltipSetter.CreateHost (); } public void Initialize (TrackEditorDialog dialog) { this.dialog = dialog; AddFields (); } protected virtual void AddFields () { } public virtual bool MultipleTracks { get { return dialog.TrackCount > 1; } } public virtual Widget Widget { get { return this; } } public Gtk.Widget TabWidget { get { return null; } } public virtual PageType PageType { get { return PageType.Edit; } } public FieldSlot AddField (Box parent, Widget field, string syncTooltip, FieldLabelClosure labelClosure, FieldValueClosure readClosure, FieldValueClosure writeClosure) { return AddField (parent, EditorUtilities.CreateLabel (String.Empty), field, syncTooltip, labelClosure, readClosure, writeClosure, FieldOptions.None); } public FieldSlot AddField (Box parent, Widget field, string syncTooltip, FieldLabelClosure labelClosure, FieldValueClosure readClosure, FieldValueClosure writeClosure, FieldOptions options) { return AddField (parent, EditorUtilities.CreateLabel (String.Empty), field, syncTooltip, labelClosure, readClosure, writeClosure, options); } public FieldSlot AddField (Box parent, Widget label, Widget field, string syncTooltip, FieldLabelClosure labelClosure, FieldValueClosure readClosure, FieldValueClosure writeClosure) { return AddField (parent, label, field, syncTooltip, labelClosure, readClosure, writeClosure, FieldOptions.None); } public FieldSlot AddField (Box parent, Widget label, Widget field, string syncTooltip, FieldLabelClosure labelClosure, FieldValueClosure readClosure, FieldValueClosure writeClosure, FieldOptions options) { FieldSlot slot = new FieldSlot (); slot.Parent = parent; slot.Label = label; slot.Field = field; slot.LabelClosure = labelClosure; slot.ReadClosure = readClosure; slot.WriteClosure = writeClosure; if (MultipleTracks && (options & FieldOptions.NoSync) == 0) { slot.SyncButton = new SyncButton (); if (syncTooltip != null) { TooltipSetter.Set (tooltip_host, slot.SyncButton, syncTooltip); } slot.SyncButton.Clicked += delegate { dialog.ForeachNonCurrentTrack (delegate (EditorTrackInfo track) { slot.WriteClosure (track, slot.Field); }); }; } Table table = new Table (1, 1, false); table.ColumnSpacing = 1; table.Attach (field, 0, 1, 1, 2, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Fill, 0, 0); IEditorField editor_field = field as IEditorField; if (editor_field != null) { editor_field.Changed += delegate { if (CurrentTrack != null) { slot.WriteClosure (CurrentTrack, slot.Field); } }; } if (slot.SyncButton != null) { table.Attach (slot.SyncButton, 1, 2, 1, 2, AttachOptions.Fill, AttachOptions.Fill, 0, 0); } if (label != null) { if (label is Label) { ((Label)label).MnemonicWidget = field; } table.Attach (label, 0, table.NColumns, 0, 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill, 0, 0); } table.ShowAll (); if ((options & FieldOptions.Shrink) == 0) { slot.Container = table; parent.PackStart (table, false, false, 0); } else { HBox shrink = new HBox (); shrink.Show (); slot.Container = shrink; shrink.PackStart (table, false, false, 0); parent.PackStart (shrink, false, false, 0); } field_slots.Add (slot); return slot; } public void RemoveField (FieldSlot slot) { field_slots.Remove (slot); } public virtual void LoadTrack (EditorTrackInfo track) { current_track = null; foreach (FieldSlot slot in field_slots) { UpdateLabel (track, slot); slot.ReadClosure (track, slot.Field); } current_track = track; } private void UpdateLabel (EditorTrackInfo track, FieldSlot slot) { Label label = slot.Label as Label; if (label != null && slot.LabelClosure != null) { string value = slot.LabelClosure (track, slot.Label); label.TextWithMnemonic = value ?? String.Empty; } } } }
// 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.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Outlining; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { /// <summary> /// Collects the content types in the view's buffer graph. /// </summary> public static ISet<IContentType> GetContentTypes(this ITextView textView) { return new HashSet<IContentType>( textView.BufferGraph.GetTextBuffers(_ => true).Select(b => b.ContentType)); } public static bool IsReadOnlyOnSurfaceBuffer(this ITextView textView, SnapshotSpan span) { var spansInView = textView.BufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); return spansInView.Any(spanInView => textView.TextBuffer.IsReadOnly(spanInView.Span)); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { var caret = textView.Caret.Position; var span = textView.BufferGraph.MapUpOrDownToBuffer(new SnapshotSpan(caret.BufferPosition, 0), subjectBuffer); if (span.HasValue) { return span.Value.Start; } else { return null; } } public static SnapshotPoint? GetCaretPoint(this ITextView textView, Predicate<ITextSnapshot> match) { var caret = textView.Caret.Position; var span = textView.BufferGraph.MapUpOrDownToFirstMatch(new SnapshotSpan(caret.BufferPosition, 0), match); if (span.HasValue) { return span.Value.Start; } else { return null; } } public static VirtualSnapshotPoint? GetVirtualCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { if (subjectBuffer == textView.TextBuffer) { return textView.Caret.Position.VirtualBufferPosition; } var mappedPoint = textView.BufferGraph.MapDownToBuffer( textView.Caret.Position.VirtualBufferPosition.Position, PointTrackingMode.Negative, subjectBuffer, PositionAffinity.Predecessor); return mappedPoint.HasValue ? new VirtualSnapshotPoint(mappedPoint.Value) : default(VirtualSnapshotPoint); } public static ITextBuffer GetBufferContainingCaret(this ITextView textView, string contentType = ContentTypeNames.RoslynContentType) { var point = GetCaretPoint(textView, s => s.ContentType.IsOfType(contentType)); return point.HasValue ? point.Value.Snapshot.TextBuffer : null; } public static SnapshotPoint? GetPositionInView(this ITextView textView, SnapshotPoint point) { return textView.BufferGraph.MapUpToSnapshot(point, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); } public static NormalizedSnapshotSpanCollection GetSpanInView(this ITextView textView, SnapshotSpan span) { return textView.BufferGraph.MapUpToSnapshot(span, SpanTrackingMode.EdgeInclusive, textView.TextSnapshot); } public static void SetSelection( this ITextView textView, VirtualSnapshotPoint anchorPoint, VirtualSnapshotPoint activePoint) { var isReversed = activePoint < anchorPoint; var start = isReversed ? activePoint : anchorPoint; var end = isReversed ? anchorPoint : activePoint; SetSelection(textView, new SnapshotSpan(start.Position, end.Position), isReversed); } public static void SetSelection( this ITextView textView, SnapshotSpan span, bool isReversed = false) { var spanInView = textView.GetSpanInView(span).Single(); textView.Selection.Select(spanInView, isReversed); textView.Caret.MoveTo(isReversed ? spanInView.Start : spanInView.End); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, SnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { return textView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(point), outliningManagerService, ensureSpanVisibleOptions); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, VirtualSnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { if (textView.IsClosed) { return false; } var pointInView = textView.GetPositionInView(point.Position); if (!pointInView.HasValue) { return false; } // If we were given an outlining service, we need to expand any outlines first, or else // the Caret.MoveTo won't land in the correct location if our target is inside a // collapsed outline. if (outliningManagerService != null) { var outliningManager = outliningManagerService.GetOutliningManager(textView); if (outliningManager != null) { outliningManager.ExpandAll(new SnapshotSpan(pointInView.Value, length: 0), match: _ => true); } } var newPosition = textView.Caret.MoveTo(new VirtualSnapshotPoint(pointInView.Value, point.VirtualSpaces)); // We use the caret's position in the view's current snapshot here in case something // changed text in response to a caret move (e.g. line commit) var spanInView = new SnapshotSpan(newPosition.BufferPosition, 0); textView.ViewScroller.EnsureSpanVisible(spanInView, ensureSpanVisibleOptions); return true; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { return textView.GetOrCreateAutoClosingProperty(typeof(TProperty), valueCreator); } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { TProperty value; GetOrCreateAutoClosingProperty(textView, key, valueCreator, out value); return value; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static bool GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) where TTextView : ITextView { return AutoClosingViewProperty<TProperty, TTextView>.GetOrCreateValue(textView, key, valueCreator, out value); } /// <summary> /// Gets or creates a per subject buffer property. /// </summary> public static TProperty GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator) where TTextView : class, ITextView { TProperty value; GetOrCreatePerSubjectBufferProperty(textView, subjectBuffer, key, valueCreator, out value); return value; } /// <summary> /// Gets or creates a per subject buffer property, returning true if it needed to create it. /// </summary> public static bool GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(valueCreator); return PerSubjectBufferProperty<TProperty, TTextView>.GetOrCreateValue(textView, subjectBuffer, key, valueCreator, out value); } public static bool TryGetPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); return PerSubjectBufferProperty<TProperty, TTextView>.TryGetValue(textView, subjectBuffer, key, out value); } public static void AddPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.AddValue(textView, subjectBuffer, key, value); } public static void RemovePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.RemoveValue(textView, subjectBuffer, key); } public static bool TypeCharWasHandledStrangely( this ITextView textView, ITextBuffer subjectBuffer, char ch) { var finalCaretPositionOpt = textView.GetCaretPoint(subjectBuffer); if (finalCaretPositionOpt == null) { // Caret moved outside of our buffer. Don't want to handle this typed character. return true; } var previousPosition = finalCaretPositionOpt.Value.Position - 1; var inRange = previousPosition >= 0 && previousPosition < subjectBuffer.CurrentSnapshot.Length; if (!inRange) { // The character before the caret isn't even in the buffer we care about. Don't // handle this. return true; } if (subjectBuffer.CurrentSnapshot[previousPosition] != ch) { // The character that was typed is not in the buffer at the typed location. Don't // handle this character. return true; } return false; } public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot( line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) { return null; } var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); } public static bool TryGetSurfaceBufferSpan( this ITextView textView, VirtualSnapshotSpan virtualSnapshotSpan, out VirtualSnapshotSpan surfaceBufferSpan) { // If we are already on the surface buffer, then there's no reason to attempt mappings // as we'll lose virtualness if (virtualSnapshotSpan.Snapshot.TextBuffer == textView.TextBuffer) { surfaceBufferSpan = virtualSnapshotSpan; return true; } // We have to map. We'll lose virtualness in this process because // mapping virtual points through projections is poorly defined. var targetSpan = textView.BufferGraph.MapUpToSnapshot( virtualSnapshotSpan.SnapshotSpan, SpanTrackingMode.EdgeExclusive, textView.TextSnapshot).FirstOrNullable(); if (targetSpan.HasValue) { surfaceBufferSpan = new VirtualSnapshotSpan(targetSpan.Value); return true; } surfaceBufferSpan = default(VirtualSnapshotSpan); return false; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.Services; namespace MGTK.Controls { public class TitleBar : Control { public int TitleBarHeight = 23; private bool mouseDown = false; private int mX, mY; Button btnCloseWindow; Button btnMaximizeWindow; Button btnMinimizeWindow; Button btnWindowOptions; public Color TextColorFocused = Color.White; public Color TextColorUnfocused = Color.Black; private int OwnerPreviousX, OwnerPreviousY, OwnerPreviousWidth, OwnerPreviousHeight; public bool MaximizeWindowButtonVisible { get { return btnMaximizeWindow.Visible; } set { btnMaximizeWindow.Visible = value; AdjustControlsCoordinatesAndSize(); } } public bool MinimizeWindowButtonVisible { get { return btnMinimizeWindow.Visible; } set { btnMinimizeWindow.Visible = value; AdjustControlsCoordinatesAndSize(); } } public bool CloseWindowButtonVisible { get { return btnCloseWindow.Visible; } set { btnCloseWindow.Visible = value; AdjustControlsCoordinatesAndSize(); } } public bool WindowOptionsButtonVisible { get { return btnWindowOptions.Visible; } set { btnWindowOptions.Visible = value; AdjustControlsCoordinatesAndSize(); } } public event EventHandler OnMaximizeButtonClick; public TitleBar(Form formowner) : base(formowner) { btnCloseWindow = new Button(formowner) { Width = 15, Height = 15 }; btnMaximizeWindow = new Button(formowner) { Width = 15, Height = 15 }; btnMinimizeWindow = new Button(formowner) { Width = 15, Height = 15 }; btnWindowOptions = new Button(formowner) { Width = 15, Height = 15 }; btnCloseWindow.Parent = btnMaximizeWindow.Parent = btnMinimizeWindow.Parent = btnWindowOptions.Parent = this; Controls.AddRange(new Control [] { btnCloseWindow, btnMaximizeWindow, btnMinimizeWindow, btnWindowOptions }); btnCloseWindow.Click += new EventHandler(btnCloseWindow_Click); this.MouseLeftDown += new EventHandler(TitleBar_MouseLeftDown); this.Init += new EventHandler(TitleBar_Init); btnMaximizeWindow.Click += new EventHandler(btnMaximizeWindow_Click); Owner.WidthChanged += new EventHandler(Owner_SizeChanged); Owner.HeightChanged += new EventHandler(Owner_SizeChanged); } void btnMaximizeWindow_Click(object sender, EventArgs e) { if (OnMaximizeButtonClick != null) OnMaximizeButtonClick(this, new EventArgs()); else HandleWindowStateChange(); } private void HandleWindowStateChange() { if (Owner.WindowState != FormWindowState.Maximized) { OwnerPreviousX = Owner.X; OwnerPreviousY = Owner.Y; OwnerPreviousWidth = Owner.Width; OwnerPreviousHeight = Owner.Height; Owner.X = Owner.Y = 0; Owner.Width = WindowManager.MaximizedWindowWidth; Owner.Height = WindowManager.MaximizedWindowHeight + Owner.EdgeHeight; Owner.WindowState = FormWindowState.Maximized; } else { Owner.X = OwnerPreviousX; Owner.Y = OwnerPreviousY; Owner.Width = OwnerPreviousWidth; Owner.Height = OwnerPreviousHeight; Owner.WindowState = FormWindowState.Normal; } SetMaximizeButtonImage(); } private void SetMaximizeButtonImage() { if (Owner.WindowState == FormWindowState.Maximized) btnMaximizeWindow.Image = Theme.UnMaximize; else if (Owner.WindowState == FormWindowState.Normal) btnMaximizeWindow.Image = Theme.Maximize; } void Owner_SizeChanged(object sender, EventArgs e) { AdjustControlsCoordinatesAndSize(); } private void AdjustControlsCoordinatesAndSize() { int buttonX; Width = Owner.Width; Height = TitleBarHeight; btnWindowOptions.X = 4; buttonX = Width - 4 - btnCloseWindow.Width; btnCloseWindow.X = buttonX; if (btnCloseWindow.Visible) buttonX -= btnCloseWindow.Width; btnMaximizeWindow.X = buttonX; if (btnMaximizeWindow.Visible) buttonX -= btnMaximizeWindow.Width; btnMinimizeWindow.X = buttonX; btnCloseWindow.Y = btnMaximizeWindow.Y = btnMinimizeWindow.Y = btnWindowOptions.Y = 4; } void TitleBar_Init(object sender, EventArgs e) { Font = Theme.FontBold; btnCloseWindow.Image = Theme.CloseIcon; btnMaximizeWindow.Image = Theme.Maximize; btnMinimizeWindow.Image = Theme.Minimize; btnWindowOptions.Image = Theme.WindowOptions; } void btnCloseWindow_Click(object sender, EventArgs e) { Owner.Visible = false; } void TitleBar_MouseLeftDown(object sender, EventArgs e) { if (!mouseDown && Owner.WindowState != FormWindowState.Maximized) { mX = WindowManager.MouseX - OwnerX; mY = WindowManager.MouseY - OwnerY; mouseDown = true; } } public override void Draw() { List<Texture2D> TitleBarFrame; if (Owner.Focused) TitleBarFrame = Theme.TitleBarFocusedFrame; else TitleBarFrame = Theme.TitleBarUnfocusedFrame; DrawingService.DrawFrame(spriteBatch, TitleBarFrame, Owner.X + X, Owner.Y + Y, Owner.Width, TitleBarHeight, Z - 0.00001f); DrawingService.DrawBMCenteredText(spriteBatch, Font, Text, Owner.X + X + Width / 2, Owner.Y + Y + Height / 2 - DrawingService.GetBMFontHeight(Font) / 2 + 1, Owner.Focused ? TextColorFocused : TextColorUnfocused, null, Z - 0.001f); //base.Draw(); } public override void Update() { if (!WindowManager.MouseLeftPressed) mouseDown = false; if (mouseDown && Owner.Focused) { this.Owner.X = (WindowManager.MouseX - mX); this.Owner.Y = (WindowManager.MouseY - mY); } base.Update(); } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Serialization; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Microsoft.CodeAnalysis.SyntaxNodeExtensions; /// <summary> /// Code generator which generates serializers. /// </summary> public static class SerializerGenerator { private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions( ClassSuffix, includeGenericParameters: false, includeTypeParameters: false, nestedClassSeparator: '_', includeGlobal: false); /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; private static readonly RuntimeTypeHandle IntPtrTypeHandle = typeof(IntPtr).TypeHandle; private static readonly RuntimeTypeHandle UIntPtrTypeHandle = typeof(UIntPtr).TypeHandle; private static readonly TypeInfo DelegateTypeInfo = typeof(Delegate).GetTypeInfo(); /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal static string GetGeneratedClassName(Type type) => CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions); /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="className">The name for the generated class.</param> /// <param name="type">The type which this serializer is being generated for.</param> /// <param name="onEncounteredType"> /// The callback invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(string className, Type type, Action<Type> onEncounteredType) { var typeInfo = type.GetTypeInfo(); var genericTypes = typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray() : new TypeParameterSyntax[0]; var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(SerializerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false)))) }; var fields = GetFields(type); // Mark each field type for generation foreach (var field in fields) { var fieldType = field.FieldInfo.FieldType; onEncounteredType(fieldType); } var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields)) { GenerateDeepCopierMethod(type, fields), GenerateSerializerMethod(type, fields), GenerateDeserializerMethod(type, fields), }; var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Returns syntax for the deserializer method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deserializer method.</returns> private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action<IDeserializationContext>> deserializeInner = ctx => ctx.DeserializeInner(default(Type)); var contextParameter = SF.IdentifierName("context"); var resultDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax> { resultDeclaration }; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.GetTypeInfo().IsValueType) { // Record the result for cyclic deserialization. Expression<Action<IDeserializationContext>> recordObject = ctx => ctx.RecordObject(default(object)); var currentSerializationContext = contextParameter; body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = deserializeInner.Invoke(contextParameter) .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(field.Type))); body.Add( SF.ExpressionStatement( field.GetSetter( resultVariable, SF.CastExpression(field.Type, deserialized)))); } // If the type implements the internal IOnDeserialized lifecycle method, invoke it's method now. if (typeof(IOnDeserialized).IsAssignableFrom(type)) { Expression<Action<IOnDeserialized>> onDeserializedMethod = _ => _.OnDeserialized(default(ISerializerContext)); // C#: ((IOnDeserialized)result).OnDeserialized(context); var typedResult = SF.ParenthesizedExpression(SF.CastExpression(typeof(IOnDeserialized).GetTypeSyntax(), resultVariable)); var invokeOnDeserialized = onDeserializedMethod.Invoke(typedResult).AddArgumentListArguments(SF.Argument(contextParameter)); body.Add(SF.ExpressionStatement(invokeOnDeserialized)); } body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable))); return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()), SF.Parameter(SF.Identifier("context")).WithType(typeof(IDeserializationContext).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))); } private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action<ISerializationContext>> serializeInner = ctx => ctx.SerializeInner(default(object), default(Type)); var contextParameter = SF.IdentifierName("context"); var body = new List<StatementSyntax> { SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput")))))) }; var inputExpression = SF.IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( SF.ExpressionStatement( serializeInner.Invoke(contextParameter) .AddArgumentListArguments( SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax()))))); } return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()), SF.Parameter(SF.Identifier("context")).WithType(typeof(ISerializationContext).GetTypeSyntax()), SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the deep copier method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deep copier method.</returns> private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields) { var originalVariable = SF.IdentifierName("original"); var inputVariable = SF.IdentifierName("input"); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax>(); if (type.GetTypeInfo().GetCustomAttribute<ImmutableAttribute>() != null) { // Immutable types do not require copying. var typeName = type.GetParseableName(new TypeFormattingOptions(includeGlobal: false)); var comment = SF.Comment($"// No deep copy required since {typeName} is marked with the [Immutable] attribute."); body.Add(SF.ReturnStatement(originalVariable).WithLeadingTrivia(comment)); } else { body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.ParenthesizedExpression( SF.CastExpression(type.GetTypeSyntax(), originalVariable))))))); body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))))); // Record this serialization. Expression<Action<ICopyContext>> recordObject = ctx => ctx.RecordCopy(default(object), default(object)); var context = SF.IdentifierName("context"); body.Add( SF.ExpressionStatement( recordObject.Invoke(context) .AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable)))); // Copy all members from the input to the result. foreach (var field in fields) { body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable, context)))); } body.Add(SF.ReturnStatement(resultVariable)); } return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax()), SF.Parameter(SF.Identifier("context")).WithType(typeof(ICopyContext).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the static fields of the serializer class. /// </summary> /// <param name="fields">The fields.</param> /// <returns>Syntax for the static fields of the serializer class.</returns> private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Expression<Action<TypeInfo>> getField = _ => _.GetField(string.Empty, BindingFlags.Default); Expression<Action<Type>> getTypeInfo = _ => _.GetTypeInfo(); Expression<Action> getGetter = () => FieldUtils.GetGetter(default(FieldInfo)); Expression<Action> getReferenceSetter = () => FieldUtils.GetReferenceSetter(default(FieldInfo)); Expression<Action> getValueSetter = () => FieldUtils.GetValueSetter(default(FieldInfo)); // Expressions for specifying binding flags. var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); // Add each field and initialize it. foreach (var field in fields) { var fieldInfo = getField.Invoke(getTypeInfo.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax()))) .AddArgumentListArguments( SF.Argument(field.FieldInfo.Name.GetLiteralExpression()), SF.Argument(bindingFlags)); var fieldInfoVariable = SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo)); var fieldInfoField = SF.IdentifierName(field.InfoFieldName); if (!field.IsGettableProperty || !field.IsSettableProperty) { result.Add( SF.FieldDeclaration( SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldGetterVariable = SF.VariableDeclarator(field.GetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( getterType, getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.GetTypeInfo().IsValueType) { var setterType = typeof(ValueTypeSetter<,>).MakeGenericType( field.FieldInfo.DeclaringType, field.FieldInfo.FieldType).GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getValueSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getReferenceSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for initializing a new instance of the provided type.</returns> private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type) { ExpressionSyntax result; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { // Use the default value. result = SF.DefaultExpression(typeInfo.AsType().GetTypeSyntax()); } else if (typeInfo.GetConstructor(Type.EmptyTypes) != null) { // Use the default constructor. result = SF.ObjectCreationExpression(typeInfo.AsType().GetTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. Expression<Func<object>> getUninitializedObject = () => FormatterServices.GetUninitializedObject(default(Type)); result = SF.CastExpression( type.GetTypeSyntax(), getUninitializedObject.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(typeInfo.AsType().GetTypeSyntax())))); } return result; } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>A sorted list of the fields of the provided type.</returns> private static List<FieldInfoMember> GetFields(Type type) { var result = type.GetAllFields() .Where(field => ShouldSerializeField(field)) .Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i }) .ToList(); result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Returns <see langowrd="true"/> if the provided field should be serialized, <see langword="false"/> otherwise. /// </summary> /// <param name="field">The field.</param> /// <returns> /// <see langowrd="true"/> if the provided field should be serialized, <see langword="false"/> otherwise. /// </returns> private static bool ShouldSerializeField(FieldInfo field) { if (field.IsNotSerialized()) return false; var fieldType = field.GetType(); if (fieldType.IsPointer || fieldType.IsByRef) return false; var handle = fieldType.TypeHandle; if (handle.Equals(IntPtrTypeHandle)) return false; if (handle.Equals(UIntPtrTypeHandle)) return false; if (DelegateTypeInfo.IsAssignableFrom(fieldType)) return false; return true; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private PropertyInfo property; /// <summary> /// Gets or sets the underlying <see cref="FieldInfo"/> instance. /// </summary> public FieldInfo FieldInfo { get; set; } /// <summary> /// Sets the ordinal assigned to this field. /// </summary> public int FieldNumber { private get; set; } /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName { get { return "field" + this.FieldNumber; } } /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName { get { return "getField" + this.FieldNumber; } } /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName { get { return "setField" + this.FieldNumber; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type { get { return this.FieldInfo.FieldType.GetTypeSyntax(); } } /// <summary> /// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private PropertyInfo PropertyInfo { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$"); if (propertyName.Success && this.FieldInfo.DeclaringType != null) { var name = propertyName.Groups[1].Value; this.property = this.FieldInfo.DeclaringType.GetTypeInfo() .GetProperty(name, BindingFlags.Instance | BindingFlags.Public); } return this.property; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete { get { var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>(); // Get the attribute from the property, if present. if (this.property != null && obsoleteAttr == null) { obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>(); } return obsoleteAttr != null; } } /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable()) { // Return the value without deep-copying it. return getValueExpression; } // Addressable arguments must be converted to references before passing. // IGrainObserver instances cannot be directly converted to references, therefore they are not included. ExpressionSyntax deepCopyValueExpression; if (typeof(IAddressable).IsAssignableFrom(this.FieldInfo.FieldType) && this.FieldInfo.FieldType.GetTypeInfo().IsInterface && !typeof(IGrainObserver).IsAssignableFrom(this.FieldInfo.FieldType)) { var getAsReference = getValueExpression.Member( (IAddressable grain) => grain.AsReference<IGrain>(), this.FieldInfo.FieldType); // If the value is not a GrainReference, convert it to a strongly-typed GrainReference. // C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>() deepCopyValueExpression = SF.ConditionalExpression( SF.ParenthesizedExpression( SF.BinaryExpression( SyntaxKind.LogicalOrExpression, SF.BinaryExpression( SyntaxKind.EqualsExpression, getValueExpression, SF.LiteralExpression(SyntaxKind.NullLiteralExpression)), SF.BinaryExpression( SyntaxKind.IsExpression, getValueExpression, typeof(GrainReference).GetTypeSyntax()))), getValueExpression, SF.InvocationExpression(getAsReference)); } else { deepCopyValueExpression = getValueExpression; } // Deep-copy the value. Expression<Action<ICopyContext>> deepCopyInner = ctx => ctx.DeepCopyInner(default(object)); var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax(); return SF.CastExpression( typeSyntax, deepCopyInner.Invoke(serializationContextExpression) .AddArgumentListArguments( SF.Argument(deepCopyValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete) { return SF.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.PropertyInfo.Name), value); } var instanceArg = SF.Argument(instance); if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.GetTypeInfo().IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword)); } return SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, SF.Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete) { result = instance.Member(this.PropertyInfo.Name); } else { // Retrieve the field using the generated getter. result = SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(SF.Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// The singleton instance. /// </summary> private static readonly Comparer Singleton = new Comparer(); /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get { return Singleton; } } public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal); } } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities { using System.Activities.DynamicUpdate; using System.Activities.Runtime; using System.Activities.Validation; using System.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; public abstract class AsyncCodeActivity : Activity, IAsyncCodeActivity { static AsyncCallback onExecuteComplete; protected AsyncCodeActivity() { } protected internal sealed override Version ImplementationVersion { get { return null; } set { if (value != null) { throw FxTrace.Exception.AsError(new NotSupportedException()); } } } [IgnoreDataMember] [Fx.Tag.KnownXamlExternal] protected sealed override Func<Activity> Implementation { get { return null; } set { if (value != null) { throw FxTrace.Exception.AsError(new NotSupportedException()); } } } internal static AsyncCallback OnExecuteComplete { get { if (onExecuteComplete == null) { onExecuteComplete = Fx.ThunkCallback(new AsyncCallback(CompleteAsynchronousExecution)); } return onExecuteComplete; } } internal override bool InternalCanInduceIdle { get { return true; } } protected abstract IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state); protected abstract void EndExecute(AsyncCodeActivityContext context, IAsyncResult result); // called on the Cancel and Abort paths to allow cleanup of outstanding async work protected virtual void Cancel(AsyncCodeActivityContext context) { } sealed internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) { // first set up an async context AsyncOperationContext asyncContext = executor.SetupAsyncOperationBlock(instance); instance.IncrementBusyCount(); AsyncCodeActivityContext context = new AsyncCodeActivityContext(asyncContext, instance, executor); bool success = false; try { IAsyncResult result = BeginExecute(context, AsyncCodeActivity.OnExecuteComplete, asyncContext); if (result == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BeginExecuteMustNotReturnANullAsyncResult)); } if (!object.ReferenceEquals(result.AsyncState, asyncContext)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BeginExecuteMustUseProvidedStateAsAsyncResultState)); } if (result.CompletedSynchronously) { EndExecute(context, result); asyncContext.CompleteOperation(); } success = true; } finally { context.Dispose(); if (!success) { asyncContext.CancelOperation(); } } } void IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext context, IAsyncResult result) { this.EndExecute(context, result); } internal static void CompleteAsynchronousExecution(IAsyncResult result) { if (result.CompletedSynchronously) { return; } AsyncOperationContext asyncContext = result.AsyncState as AsyncOperationContext; // User code may not have correctly passed the AsyncOperationContext thru as the "state" parameter for // BeginInvoke. If is null, don't bother going any further. We would have thrown an exception out of the // workflow from InternalExecute. In that case, AsyncOperationContext.CancelOperation will be called in // InternalExecute. if (asyncContext != null) { asyncContext.CompleteAsyncCodeActivity(new CompleteAsyncCodeActivityData(asyncContext, result)); } } sealed internal override void InternalCancel(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) { AsyncOperationContext asyncContext; if (executor.TryGetPendingOperation(instance, out asyncContext)) { AsyncCodeActivityContext context = new AsyncCodeActivityContext(asyncContext, instance, executor); try { asyncContext.HasCalledAsyncCodeActivityCancel = true; Cancel(context); } finally { context.Dispose(); } } } sealed internal override void InternalAbort(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason) { AsyncOperationContext asyncContext; if (executor.TryGetPendingOperation(instance, out asyncContext)) { try { if (!asyncContext.HasCalledAsyncCodeActivityCancel) { asyncContext.IsAborting = true; InternalCancel(instance, executor, null); } } finally { // we should always abort outstanding contexts if (asyncContext.IsStillActive) { asyncContext.CancelOperation(); } } } } sealed internal override void OnInternalCacheMetadata(bool createEmptyBindings) { CodeActivityMetadata metadata = new CodeActivityMetadata(this, this.GetParentEnvironment(), createEmptyBindings); CacheMetadata(metadata); metadata.Dispose(); } internal sealed override void OnInternalCreateDynamicUpdateMap(DynamicUpdateMapBuilder.Finalizer finalizer, DynamicUpdateMapBuilder.IDefinitionMatcher matcher, Activity originalActivity) { } protected sealed override void OnCreateDynamicUpdateMap(UpdateMapMetadata metadata, Activity originalActivity) { // NO OP } protected sealed override void CacheMetadata(ActivityMetadata metadata) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WrongCacheMetadataForCodeActivity)); } protected virtual void CacheMetadata(CodeActivityMetadata metadata) { // We bypass the metadata call to avoid the null checks SetArgumentsCollection(ReflectedInformation.GetArguments(this), metadata.CreateEmptyBindings); } class CompleteAsyncCodeActivityData : AsyncOperationContext.CompleteData { IAsyncResult result; public CompleteAsyncCodeActivityData(AsyncOperationContext context, IAsyncResult result) : base(context, false) { this.result = result; } protected override void OnCallExecutor() { this.Executor.CompleteOperation(new CompleteAsyncCodeActivityWorkItem(this.AsyncContext, this.Instance, this.result)); } // not [DataContract] since this workitem will never happen when persistable class CompleteAsyncCodeActivityWorkItem : ActivityExecutionWorkItem { IAsyncResult result; AsyncOperationContext asyncContext; public CompleteAsyncCodeActivityWorkItem(AsyncOperationContext asyncContext, ActivityInstance instance, IAsyncResult result) : base(instance) { this.result = result; this.asyncContext = asyncContext; this.ExitNoPersistRequired = true; } public override void TraceCompleted() { if (TD.CompleteBookmarkWorkItemIsEnabled()) { TD.CompleteBookmarkWorkItem(this.ActivityInstance.Activity.GetType().ToString(), this.ActivityInstance.Activity.DisplayName, this.ActivityInstance.Id, ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark), ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark.Scope)); } } public override void TraceScheduled() { if (TD.ScheduleBookmarkWorkItemIsEnabled()) { TD.ScheduleBookmarkWorkItem(this.ActivityInstance.Activity.GetType().ToString(), this.ActivityInstance.Activity.DisplayName, this.ActivityInstance.Id, ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark), ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark.Scope)); } } public override void TraceStarting() { if (TD.StartBookmarkWorkItemIsEnabled()) { TD.StartBookmarkWorkItem(this.ActivityInstance.Activity.GetType().ToString(), this.ActivityInstance.Activity.DisplayName, this.ActivityInstance.Id, ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark), ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark.Scope)); } } public override bool Execute(ActivityExecutor executor, BookmarkManager bookmarkManager) { AsyncCodeActivityContext context = null; try { context = new AsyncCodeActivityContext(this.asyncContext, this.ActivityInstance, executor); IAsyncCodeActivity owner = (IAsyncCodeActivity)this.ActivityInstance.Activity; owner.FinishExecution(context, this.result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.ExceptionToPropagate = e; } finally { if (context != null) { context.Dispose(); } } return true; } } } } public abstract class AsyncCodeActivity<TResult> : Activity<TResult>, IAsyncCodeActivity { protected AsyncCodeActivity() { } protected internal sealed override Version ImplementationVersion { get { return null; } set { if (value != null) { throw FxTrace.Exception.AsError(new NotSupportedException()); } } } [IgnoreDataMember] [Fx.Tag.KnownXamlExternal] protected sealed override Func<Activity> Implementation { get { return null; } set { if (value != null) { throw FxTrace.Exception.AsError(new NotSupportedException()); } } } internal override bool InternalCanInduceIdle { get { return true; } } protected abstract IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state); protected abstract TResult EndExecute(AsyncCodeActivityContext context, IAsyncResult result); // called on the Cancel and Abort paths to allow cleanup of outstanding async work protected virtual void Cancel(AsyncCodeActivityContext context) { } sealed internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) { // first set up an async context AsyncOperationContext asyncContext = executor.SetupAsyncOperationBlock(instance); instance.IncrementBusyCount(); AsyncCodeActivityContext context = new AsyncCodeActivityContext(asyncContext, instance, executor); bool success = false; try { IAsyncResult result = BeginExecute(context, AsyncCodeActivity.OnExecuteComplete, asyncContext); if (result == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BeginExecuteMustNotReturnANullAsyncResult)); } if (!object.ReferenceEquals(result.AsyncState, asyncContext)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BeginExecuteMustUseProvidedStateAsAsyncResultState)); } if (result.CompletedSynchronously) { ((IAsyncCodeActivity)this).FinishExecution(context, result); asyncContext.CompleteOperation(); } success = true; } finally { context.Dispose(); if (!success) { asyncContext.CancelOperation(); } } } void IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext context, IAsyncResult result) { TResult executionResult = this.EndExecute(context, result); this.Result.Set(context, executionResult); } sealed internal override void InternalCancel(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) { AsyncOperationContext asyncContext; if (executor.TryGetPendingOperation(instance, out asyncContext)) { AsyncCodeActivityContext context = new AsyncCodeActivityContext(asyncContext, instance, executor); try { asyncContext.HasCalledAsyncCodeActivityCancel = true; Cancel(context); } finally { context.Dispose(); } } } sealed internal override void InternalAbort(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason) { AsyncOperationContext asyncContext; if (executor.TryGetPendingOperation(instance, out asyncContext)) { try { if (!asyncContext.HasCalledAsyncCodeActivityCancel) { asyncContext.IsAborting = true; InternalCancel(instance, executor, null); } } finally { // we should always abort outstanding contexts if (asyncContext.IsStillActive) { asyncContext.CancelOperation(); } } } } sealed internal override void OnInternalCacheMetadataExceptResult(bool createEmptyBindings) { CodeActivityMetadata metadata = new CodeActivityMetadata(this, this.GetParentEnvironment(), createEmptyBindings); CacheMetadata(metadata); metadata.Dispose(); } internal sealed override void OnInternalCreateDynamicUpdateMap(DynamicUpdateMapBuilder.Finalizer finalizer, DynamicUpdateMapBuilder.IDefinitionMatcher matcher, Activity originalActivity) { } protected sealed override void OnCreateDynamicUpdateMap(UpdateMapMetadata metadata, Activity originalActivity) { // NO OP } protected sealed override void CacheMetadata(ActivityMetadata metadata) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WrongCacheMetadataForCodeActivity)); } protected virtual void CacheMetadata(CodeActivityMetadata metadata) { // We bypass the metadata call to avoid the null checks SetArgumentsCollection(ReflectedInformation.GetArguments(this), metadata.CreateEmptyBindings); } } }
// // System.Data.ConstraintCollection.cs // // Author: // Franklin Wise <[email protected]> // Daniel Morgan // // (C) Ximian, Inc. 2002 // (C) 2002 Franklin Wise // (C) 2002 Daniel Morgan // // // Copyright (C) 2004 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 System.Collections; using System.ComponentModel; namespace System.Data { [Editor] [Serializable] internal delegate void DelegateValidateRemoveConstraint(ConstraintCollection sender, Constraint constraintToRemove, ref bool fail,ref string failReason); /// <summary> /// hold collection of constraints for data table /// </summary> [DefaultEvent ("CollectionChanged")] [EditorAttribute("Microsoft.VSDesigner.Data.Design.ConstraintsCollectionEditor, "+Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+Consts.AssemblySystem_Drawing )] [Serializable] public class ConstraintCollection : InternalDataCollectionBase { //private bool beginInit = false; public event CollectionChangeEventHandler CollectionChanged; private DataTable table; // Call this to set the "table" property of the UniqueConstraint class // intialized with UniqueConstraint( string, string[], bool ); // And also validate that the named columns exist in the "table" private delegate void PostAddRange( DataTable table ); // Keep reference to most recent constraints passed to AddRange() // so that they can be added when EndInit() is called. private Constraint [] _mostRecentConstraints; //Don't allow public instantiation //Will be instantianted from DataTable internal ConstraintCollection(DataTable table){ this.table = table; } internal DataTable Table{ get{ return this.table; } } public virtual Constraint this[string name] { get { //If the name is not found we just return null int index = IndexOf(name); //case insensitive if (-1 == index) return null; return this[index]; } } public virtual Constraint this[int index] { get { if (index < 0 || index >= List.Count) throw new IndexOutOfRangeException(); return (Constraint)List[index]; } } private void _handleBeforeConstraintNameChange(object sender, string newName) { //null or empty if (newName == null || newName == "") throw new ArgumentException("ConstraintName cannot be set to null or empty " + " after it has been added to a ConstraintCollection."); if (_isDuplicateConstraintName(newName,(Constraint)sender)) throw new DuplicateNameException("Constraint name already exists."); } private bool _isDuplicateConstraintName(string constraintName, Constraint excludeFromComparison) { foreach (Constraint cst in List) { if (String.Compare (constraintName, cst.ConstraintName, false, Table.Locale) == 0 && cst != excludeFromComparison) return true; } return false; } //finds an open name slot of ConstraintXX //where XX is a number private string _createNewConstraintName() { bool loopAgain = false; int index = 1; do { loopAgain = false; foreach (Constraint cst in List) { //Case insensitive if (String.Compare (cst.ConstraintName, "Constraint" + index, !Table.CaseSensitive, Table.Locale) == 0) { loopAgain = true; index++; break; } } } while (loopAgain); return "Constraint" + index.ToString(); } // Overloaded Add method (5 of them) // to add Constraint object to the collection public void Add(Constraint constraint) { //not null if (null == constraint) throw new ArgumentNullException("Can not add null."); //check constraint membership //can't already exist in this collection or any other if (this == constraint.ConstraintCollection) throw new ArgumentException("Constraint already belongs to this collection."); if (null != constraint.ConstraintCollection) throw new ArgumentException("Constraint already belongs to another collection."); //check for duplicate name if (_isDuplicateConstraintName(constraint.ConstraintName,null) ) throw new DuplicateNameException("Constraint name already exists."); // Check whether Constraint is UniqueConstraint and initailized with the special // constructor - UniqueConstraint( string, string[], bool ); // If yes, It must be added via AddRange() only // Environment.StackTrace can help us // FIXME: Is a different mechanism to do this? if (constraint is UniqueConstraint){ if ((constraint as UniqueConstraint).DataColsNotValidated == true){ if ( Environment.StackTrace.IndexOf( "AddRange" ) == -1 ){ throw new ArgumentException(" Some DataColumns are invalid - They may not belong to the table associated with this Constraint Collection" ); } } } if (constraint is ForeignKeyConstraint){ if ((constraint as ForeignKeyConstraint).DataColsNotValidated == true){ if ( Environment.StackTrace.IndexOf( "AddRange" ) == -1 ){ throw new ArgumentException(" Some DataColumns are invalid - They may not belong to the table associated with this Constraint Collection" ); } } } //Allow constraint to run validation rules and setup constraint.AddToConstraintCollectionSetup(this); //may throw if it can't setup //Run Constraint to check existing data in table // this is redundant, since AddToConstraintCollectionSetup // calls AssertConstraint right before this call //constraint.AssertConstraint(); //if name is null or empty give it a name if (constraint.ConstraintName == null || constraint.ConstraintName == "" ) { constraint.ConstraintName = _createNewConstraintName(); } //Add event handler for ConstraintName change constraint.BeforeConstraintNameChange += new DelegateConstraintNameChange( _handleBeforeConstraintNameChange); constraint.ConstraintCollection = this; List.Add(constraint); if (constraint is UniqueConstraint && ((UniqueConstraint)constraint).IsPrimaryKey) { table.PrimaryKey = ((UniqueConstraint)constraint).Columns; } OnCollectionChanged( new CollectionChangeEventArgs( CollectionChangeAction.Add, this) ); } public virtual Constraint Add(string name, DataColumn column, bool primaryKey) { UniqueConstraint uc = new UniqueConstraint(name, column, primaryKey); Add(uc); return uc; } public virtual Constraint Add(string name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn) { ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumn, foreignKeyColumn); Add(fc); return fc; } public virtual Constraint Add(string name, DataColumn[] columns, bool primaryKey) { UniqueConstraint uc = new UniqueConstraint(name, columns, primaryKey); Add(uc); return uc; } public virtual Constraint Add(string name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns) { ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumns, foreignKeyColumns); Add(fc); return fc; } public void AddRange(Constraint[] constraints) { //When AddRange() occurs after BeginInit, //it does not add any elements to the collection until EndInit is called. if (this.table.fInitInProgress) { // Keep reference so that they can be added when EndInit() is called. _mostRecentConstraints = constraints; return; } if ( (constraints == null) || (constraints.Length == 0)) return; // Check whether the constraint is UniqueConstraint // And whether it was initialized with the special ctor // i.e UniqueConstraint( string, string[], bool ); for (int i = 0; i < constraints.Length; i++){ if (constraints[i] is UniqueConstraint){ if (( constraints[i] as UniqueConstraint).DataColsNotValidated == true){ PostAddRange _postAddRange= new PostAddRange ((constraints[i] as UniqueConstraint).PostAddRange); // UniqueConstraint.PostAddRange() validates whether all named // columns exist in the table associated with this instance of // ConstraintCollection. _postAddRange (this.table); } } else if (constraints [i] is ForeignKeyConstraint){ if (( constraints [i] as ForeignKeyConstraint).DataColsNotValidated == true){ (constraints [i] as ForeignKeyConstraint).postAddRange (this.table); } } } foreach (Constraint constraint in constraints) Add (constraint); } // Helper AddRange() - Call this function when EndInit is called internal void PostEndInit() { Constraint[] constraints = _mostRecentConstraints; _mostRecentConstraints = null; AddRange (constraints); } public bool CanRemove(Constraint constraint) { return constraint.CanRemoveFromCollection(this, false); } public void Clear() { // Clear should also remove PrimaryKey Table.PrimaryKey = null; //CanRemove? See Lamespec below. //the Constraints have a reference to us //and we listen to name change events //we should remove these before clearing foreach (Constraint con in List) { con.ConstraintCollection = null; con.BeforeConstraintNameChange -= new DelegateConstraintNameChange( _handleBeforeConstraintNameChange); } //LAMESPEC: MSFT implementation allows this //even when a ForeignKeyConstraint exist for a UniqueConstraint //thus violating the CanRemove logic //CanRemove will throws Exception incase of the above List.Clear(); //Will violate CanRemove rule OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this) ); } public bool Contains(string name) { return (-1 != IndexOf(name)); } public int IndexOf(Constraint constraint) { return List.IndexOf(constraint); } public virtual int IndexOf(string constraintName) { //LAMESPEC: Spec doesn't say case insensitive //it should to be consistant with the other //case insensitive comparisons in this class int index = 0; foreach (Constraint con in List) { if (String.Compare (constraintName, con.ConstraintName, !Table.CaseSensitive, Table.Locale) == 0) { return index; } index++; } return -1; //not found } public void Remove(Constraint constraint) { //LAMESPEC: spec doesn't document the ArgumentException the //will be thrown if the CanRemove rule is violated //LAMESPEC: spec says an exception will be thrown //if the element is not in the collection. The implementation //doesn't throw an exception. ArrayList.Remove doesn't throw if the //element doesn't exist //ALSO the overloaded remove in the spec doesn't say it throws any exceptions //not null if (null == constraint) throw new ArgumentNullException(); if (!constraint.CanRemoveFromCollection(this, true)) return; constraint.RemoveFromConstraintCollectionCleanup(this); List.Remove(constraint); OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Remove,this)); } public void Remove(string name) { //if doesn't exist fail quietly int index = IndexOf(name); if (-1 == index) return; Remove(this[index]); } public void RemoveAt(int index) { Remove(this[index]); } protected override ArrayList List { get{ return base.List; } } protected virtual void OnCollectionChanged( CollectionChangeEventArgs ccevent) { if (null != CollectionChanged) { CollectionChanged(this, ccevent); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Diadoc.Api.Com; using Diadoc.Api.Proto.Documents; namespace Diadoc.Api.Proto.Events { [ComVisible(true)] [Guid("ABF440A3-BC33-4DF4-80CF-6889F7B004A3")] public interface IMessage { string MessageId { get; } string FromBoxId { get; } string FromTitle { get; } string ToBoxId { get; } string ToTitle { get; } bool IsDraft { get; } bool IsDeleted { get; } bool IsTest { get; } bool IsInternal { get; } ReadonlyList EntitiesList { get; } bool DraftIsLocked { get; } bool DraftIsRecycled { get; } string CreatedFromDraftId { get; } string DraftIsTransformedToMessageId { get; } DateTime Timestamp { get; } DateTime LastPatchTimestamp { get; } } [ComVisible(true)] [Guid("26C32890-61DE-4FB9-9EED-B815E41050B7")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IMessage))] public partial class Message : SafeComObject, IMessage { public string DraftIsTransformedToMessageId { get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); } } public DateTime Timestamp { get { return new DateTime(TimestampTicks, DateTimeKind.Utc); } } public DateTime LastPatchTimestamp { get { return new DateTime(LastPatchTimestampTicks, DateTimeKind.Utc); } } public ReadonlyList EntitiesList { get { return new ReadonlyList(Entities); } } } [ComVisible(true)] [Guid("DFF0AEBA-4DCC-4910-B34A-200F1B919F4E")] public interface IEntity { string EntityId { get; } string ParentEntityId { get; } Com.EntityType EntityTypeValue { get; } Com.AttachmentType AttachmentTypeValue { get; } string FileName { get; } bool NeedRecipientSignature { get; } bool NeedReceipt { get; } Content Content { get; } Document DocumentInfo { get; } ResolutionInfo ResolutionInfo { get; } string SignerBoxId { get; } string SignerDepartmentId { get; } DateTime CreationTime { get; } string NotDeliveredEventId { get; } ResolutionRouteAssignmentInfo ResolutionRouteAssignmentInfo { get; } ResolutionRouteRemovalInfo ResolutionRouteRemovalInfo { get; } } [ComVisible(true)] [Guid("E7D82A2C-A0BF-4D0B-9466-9E8DA15B99B7")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IEntity))] public partial class Entity : SafeComObject, IEntity { public DateTime CreationTime { get { return new DateTime(RawCreationDate, DateTimeKind.Utc); } } public Com.EntityType EntityTypeValue { get { return (Com.EntityType) ((int) EntityType); } } public Com.AttachmentType AttachmentTypeValue { get { return (Com.AttachmentType) ((int) AttachmentType); } } } [ComVisible(true)] [Guid("D3BD7130-16A6-4202-B1CE-5FB1A9AFD4EF")] public interface IEntityPatch { string EntityId { get; } bool DocumentIsDeleted { get; } string MovedToDepartment { get; } bool DocumentIsRestored { get; } bool ContentIsPatched { get; } } [ComVisible(true)] [Guid("4C05AB1C-5385-41A2-8C04-8855FC7E8341")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IEntityPatch))] public partial class EntityPatch : SafeComObject, IEntityPatch { } [ComVisible(true)] [Guid("AE4037C5-DA6E-4D69-A738-5E6B64490492")] public interface IBoxEvent { string EventId { get; } string MessageId { get; } DateTime Timestamp { get; } ReadonlyList EntitiesList { get; } bool HasMessage { get; } bool HasPatch { get; } Message Message { get; } MessagePatch Patch { get; } } [ComVisible(true)] [Guid("C59A22CF-9744-457A-8359-3569B19A31C8")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IBoxEvent))] public partial class BoxEvent : SafeComObject, IBoxEvent { public string MessageId { get { return (Message != null ? Message.MessageId : null) ?? (Patch != null ? Patch.MessageId : null); } } public DateTime Timestamp { get { if (Message != null) return Message.Timestamp; if (Patch != null) return Patch.Timestamp; return default(DateTime); } } public ReadonlyList EntitiesList { get { var entities = (Message != null ? Message.Entities : null) ?? (Patch != null ? Patch.Entities : null); return entities != null ? new ReadonlyList(entities) : null; } } public List<Entity> Entities { get { var entities = (Message != null ? Message.Entities : null) ?? (Patch != null ? Patch.Entities : null); return entities != null ? new List<Entity>(entities) : new List<Entity>(); } } public bool HasMessage { get { return Message != null; } } public bool HasPatch { get { return Patch != null; } } } [ComVisible(true)] [Guid("581C269C-67A5-4CDF-AC77-CDB2D05E03A0")] public interface IBoxEventList { int TotalCount { get; } ReadonlyList EventsList { get; } } [ComVisible(true)] [Guid("793E451E-3F4A-4A3E-BDBB-F47ED13305F5")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IBoxEventList))] public partial class BoxEventList : SafeComObject, IBoxEventList { public ReadonlyList EventsList { get { return new ReadonlyList(Events); } } } [ComVisible(true)] [Guid("527CD64F-A219-4B45-8219-CC48586D521B")] public interface IMessagePatch { string MessageId { get; } ReadonlyList EntitiesList { get; } ReadonlyList EntityPatchesList { get; } DateTime Timestamp { get; } bool ForDraft { get; } bool DraftIsRecycled { get; } string DraftIsTransformedToMessageId { get; } bool DraftIsLocked { get; } bool MessageIsDeleted { get; } bool MessageIsRestored { get; } bool MessageIsDelivered { get; } string DeliveredPatchId { get; } string PatchId { get; } } [ComVisible(true)] [Guid("949C9C09-DD1A-4787-A5AD-94D8677A5439")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IMessagePatch))] public partial class MessagePatch : SafeComObject, IMessagePatch { public DateTime Timestamp { get { return new DateTime(TimestampTicks, DateTimeKind.Utc); } } public string DraftIsTransformedToMessageId { get { return DraftIsTransformedToMessageIdList.FirstOrDefault(); } } public ReadonlyList EntitiesList { get { return new ReadonlyList(Entities); } } public ReadonlyList EntityPatchesList { get { return new ReadonlyList(EntityPatches); } } } [ComVisible(true)] [Guid("32176AA9-AF39-4E0C-A47B-0CEA3C1DA211")] public interface IGeneratedFile { string FileName { get; } byte[] Content { get; } void SaveContentToFile(string path); } [ComVisible(true)] [Guid("D4E7012E-1A64-42EC-AD5E-B27754AC24FE")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IGeneratedFile))] public class GeneratedFile : SafeComObject, IGeneratedFile { private readonly string fileName; private readonly byte[] content; public GeneratedFile(string fileName, byte[] content) { this.fileName = fileName; this.content = content; } public void SaveContentToFile(string path) { File.WriteAllBytes(path, Content); } public string FileName { get { return fileName; } } public byte[] Content { get { return content; } } } [ComVisible(true)] [Guid("34FD4B0B-CE38-41CE-AB76-4C6234A6C542")] public interface IMessageToPost { string FromBoxId { get; set; } string FromDepartmentId { get; set; } string ToBoxId { get; set; } string ToDepartmentId { get; set; } bool IsInternal { get; set; } bool IsDraft { get; set; } bool LockDraft { get; set; } bool LockPacket { get; set; } bool StrictDraftValidation { get; set; } bool DelaySend { get; set; } TrustConnectionRequestAttachment TrustConnectionRequest { get; set; } void AddInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddXmlTorg12SellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddXmlAcceptanceCertificateSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddTorg12([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddAcceptanceCertificate([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddProformaInvoice([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddStructuredData([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddPriceList([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddPriceListAgreement([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddCertificateRegistry([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddReconciliationAct([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddContract([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddTorg13([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddServiceDetails([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddSupplementaryAgreement([MarshalAs(UnmanagedType.IDispatch)] object supplementaryAgreement); void AddUniversalTransferDocumentSellerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment); } [ComVisible(true)] [ProgId("Diadoc.Api.MessageToPost")] [Guid("6EABD544-6DDC-49b4-95A1-0D7936C08C31")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IMessageToPost))] public partial class MessageToPost : SafeComObject, IMessageToPost { //That property was deletes from proto description, but we can't delete this property here because COM need continuous sequence of methods public TrustConnectionRequestAttachment TrustConnectionRequest { get { return null; } set { } } public void AddInvoice(object attachment) { Invoices.Add((XmlDocumentAttachment)attachment); } public void AddXmlTorg12SellerTitle(object attachment) { XmlTorg12SellerTitles.Add((XmlDocumentAttachment)attachment); } public void AddXmlAcceptanceCertificateSellerTitle(object attachment) { XmlAcceptanceCertificateSellerTitles.Add((XmlDocumentAttachment)attachment); } public void AddAttachment(object attachment) { NonformalizedDocuments.Add((NonformalizedAttachment)attachment); } public void AddTorg12(object attachment) { Torg12Documents.Add((BasicDocumentAttachment)attachment); } public void AddAcceptanceCertificate(object attachment) { AcceptanceCertificates.Add((AcceptanceCertificateAttachment) attachment); } public void AddProformaInvoice(object attachment) { ProformaInvoices.Add((BasicDocumentAttachment) attachment); } public void AddStructuredData(object attachment) { StructuredDataAttachments.Add((StructuredDataAttachment) attachment); } public void AddPriceList(object attachment) { PriceLists.Add((PriceListAttachment) attachment); } public void AddPriceListAgreement(object attachment) { PriceListAgreements.Add((NonformalizedAttachment) attachment); } public void AddCertificateRegistry(object attachment) { CertificateRegistries.Add((NonformalizedAttachment) attachment); } public void AddReconciliationAct(object attachment) { ReconciliationActs.Add((ReconciliationActAttachment) attachment); } public void AddContract(object attachment) { Contracts.Add((ContractAttachment) attachment); } public void AddTorg13(object attachment) { Torg13Documents.Add((Torg13Attachment) attachment); } public void AddServiceDetails(object attachment) { ServiceDetailsDocuments.Add((ServiceDetailsAttachment) attachment); } public void AddSupplementaryAgreement(object supplementaryAgreement) { SupplementaryAgreements.Add((SupplementaryAgreementAttachment)supplementaryAgreement); } public void AddUniversalTransferDocumentSellerTitle(object attachment) { UniversalTransferDocumentSellerTitles.Add((XmlDocumentAttachment)attachment); } } [ComVisible(true)] [Guid("A0C93B1F-5FD2-4738-B8F9-994AE05B5B63")] public interface ISupplementaryAgreementAttachment { SignedContent SignedContent { get; set; } string FileName { get; set; } string Comment { get; set; } void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); string CustomDocumentId { get; set; } string DocumentDate { get; set; } string DocumentNumber { get; set; } string Total { get; set; } string ContractNumber { get; set; } string ContractDate { get; set; } string ContractType { get; set; } bool NeedReceipt { get; set; } void AddCustomDataItem([MarshalAs(UnmanagedType.IDispatch)] object customDataItem); } [ComVisible(true)] [ProgId("Diadoc.Api.SupplementaryAgreementAttachment")] [Guid("9AA39127-85C9-4B40-A456-9C18D5BF8348")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ISupplementaryAgreementAttachment))] public partial class SupplementaryAgreementAttachment : SafeComObject, ISupplementaryAgreementAttachment { public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId)documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId)documentId); } public void AddCustomDataItem(object customDataItem) { CustomData.Add((CustomDataItem)customDataItem); } } [ComVisible(true)] [Guid("0D648002-53CC-4EAB-969B-68364BB4F3CE")] public interface IMessagePatchToPost { string BoxId { get; set; } string MessageId { get; set; } void AddReceipt([MarshalAs(UnmanagedType.IDispatch)] object receipt); void AddCorrectionRequest([MarshalAs(UnmanagedType.IDispatch)] object correctionRequest); void AddSignature([MarshalAs(UnmanagedType.IDispatch)] object signature); void AddRequestedSignatureRejection( [MarshalAs(UnmanagedType.IDispatch)] object signatureRejection); void AddXmlTorg12BuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddXmlAcceptanceCertificateBuyerTitle([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddResolution([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddRevocationRequestAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddXmlSignatureRejectionAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddUniversalTransferDocumentBuyerTitleAttachment([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddResolutionRouteAssignment([MarshalAs(UnmanagedType.IDispatch)] object attachment); void AddResolutoinRouteRemoval([MarshalAs(UnmanagedType.IDispatch)] object attachment); } [ComVisible(true)] [ProgId("Diadoc.Api.MessagePatchToPost")] [Guid("F917FD6D-AEE9-4b21-A79F-11981E805F5D")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IMessagePatchToPost))] public partial class MessagePatchToPost : SafeComObject, IMessagePatchToPost { public void AddReceipt(object receipt) { Receipts.Add((ReceiptAttachment)receipt); } public void AddCorrectionRequest(object correctionRequest) { CorrectionRequests.Add((CorrectionRequestAttachment)correctionRequest); } public void AddSignature(object signature) { Signatures.Add((DocumentSignature)signature); } public void AddRequestedSignatureRejection(object signatureRejection) { RequestedSignatureRejections.Add((RequestedSignatureRejection)signatureRejection); } public void AddXmlTorg12BuyerTitle(object attachment) { XmlTorg12BuyerTitles.Add((ReceiptAttachment)attachment); } public void AddXmlAcceptanceCertificateBuyerTitle(object attachment) { XmlAcceptanceCertificateBuyerTitles.Add((ReceiptAttachment)attachment); } public void AddUniversalTransferDocumentBuyerTitle(object attachment) { UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment); } public void AddResolution(object attachment) { Resolutions.Add((ResolutionAttachment)attachment); } public void AddResolutionRequestAttachment(object attachment) { ResolutionRequests.Add((ResolutionRequestAttachment)attachment); } public void AddResolutionRequestCancellationAttachment(object attachment) { ResolutionRequestCancellations.Add((ResolutionRequestCancellationAttachment)attachment); } public void AddResolutionRequestDenialAttachment(object attachment) { ResolutionRequestDenials.Add((ResolutionRequestDenialAttachment)attachment); } public void AddResolutionRequestDenialCancellationAttachment(object attachment) { ResolutionRequestDenialCancellations.Add((ResolutionRequestDenialCancellationAttachment)attachment); } public void AddRevocationRequestAttachment(object attachment) { RevocationRequests.Add((RevocationRequestAttachment)attachment); } public void AddXmlSignatureRejectionAttachment(object attachment) { XmlSignatureRejections.Add((XmlSignatureRejectionAttachment)attachment); } public void AddUniversalTransferDocumentBuyerTitleAttachment(object attachment) { UniversalTransferDocumentBuyerTitles.Add((ReceiptAttachment)attachment); } public void AddResolutionRouteAssignment(object attachment) { ResolutionRouteAssignments.Add((ResolutionRouteAssignment)attachment); } public void AddResolutoinRouteRemoval(object attachment) { ResolutionRouteRemovals.Add((ResolutionRouteRemoval)attachment); } } [ComVisible(true)] [Guid("10AC1159-A121-4F3E-9437-7CF22A1B60A1")] public interface IXmlDocumentAttachment { string CustomDocumentId { get; set; } SignedContent SignedContent { get; set; } string Comment { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); } [ComVisible(true)] [ProgId("Diadoc.Api.XmlDocumentAttachment")] [Guid("E6B32174-37DE-467d-A947-B88AEDC2ECEC")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IXmlDocumentAttachment))] public partial class XmlDocumentAttachment : SafeComObject, IXmlDocumentAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId) documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId)documentId); } } [ComVisible(true)] [Guid("B43D2BF4-E100-4F49-8F8F-D87EA3ECE453")] public interface INonformalizedAttachment { string CustomDocumentId { get; set; } string FileName { get; set; } string DocumentNumber { get; set; } string DocumentDate { get; set; } bool NeedRecipientSignature { get; set; } string Comment { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); } [ComVisible(true)] [ProgId("Diadoc.Api.NonformalizedAttachment")] [Guid("9904995A-1EF3-4182-8C3E-61DBEADC159C")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (INonformalizedAttachment))] public partial class NonformalizedAttachment : SafeComObject, INonformalizedAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId) documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId) documentId); } } [ComVisible(true)] [Guid("8FC16D12-EEE7-44F1-AD9C-ACD907EF286D")] public interface IBasicDocumentAttachment { string CustomDocumentId { get; set; } string FileName { get; set; } string DocumentNumber { get; set; } string DocumentDate { get; set; } string Total { get; set; } string Vat { get; set; } string Grounds { get; set; } string Comment { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); } [ComVisible(true)] [Guid("E7DA152C-B651-4F3A-B9D7-25F6E5BABC1D")] public interface IAcceptanceCertificateAttachment { string CustomDocumentId { get; set; } string FileName { get; set; } string DocumentNumber { get; set; } string DocumentDate { get; set; } string Total { get; set; } string Vat { get; set; } string Grounds { get; set; } string Comment { get; set; } SignedContent SignedContent { get; set; } bool NeedRecipientSignature { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); } [ComVisible(true)] [ProgId("Diadoc.Api.BasicDocumentAttachment")] [Guid("776261C4-361D-42BF-929C-8B368DEE917D")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IBasicDocumentAttachment))] public partial class BasicDocumentAttachment : SafeComObject, IBasicDocumentAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent)signedContent; } public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId)documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId)documentId); } } [ComVisible(true)] [ProgId("Diadoc.Api.AcceptanceCertificateAttachment")] [Guid("9BCBE1E4-11C5-45BF-887A-FE63D074D71A")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IAcceptanceCertificateAttachment))] public partial class AcceptanceCertificateAttachment : SafeComObject, IAcceptanceCertificateAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId) documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId) documentId); } } [ComVisible(true)] [Guid("2860C8D8-72C3-4D83-A3EB-DF36A2A8EB2E")] public interface ITrustConnectionRequestAttachment { string FileName { get; set; } string Comment { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); } [ComVisible(true)] [ProgId("Diadoc.Api.TrustConnectionRequestAttachment")] [Guid("139BB7DA-D92A-49F0-840A-3FB541323632")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ITrustConnectionRequestAttachment))] public partial class TrustConnectionRequestAttachment : SafeComObject, ITrustConnectionRequestAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } } [ComVisible(true)] [Guid("DA50195B-0B15-42DB-AFE3-35C1280C9EA6")] public interface IStructuredDataAttachment { string ParentCustomDocumentId { get; set; } string FileName { get; set; } byte[] Content { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.StructuredDataAttachment")] [Guid("E35327B6-F774-476A-93B4-CC68DE7432D1")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IStructuredDataAttachment))] public partial class StructuredDataAttachment : SafeComObject, IStructuredDataAttachment { } [ComVisible(true)] [Guid("4D8D636A-91D8-4734-8371-913E144FED66")] public interface ISignedContent { byte[] Content { get; set; } byte[] Signature { get; set; } [Obsolete] bool SignByAttorney { get; set; } bool SignWithTestSignature { get; set; } string NameOnShelf { get; set; } void LoadContentFromFile(string fileName); void SaveContentToFile(string fileName); void LoadSignatureFromFile(string fileName); void SaveSignatureToFile(string fileName); } [ComVisible(true)] [Guid("A42D43EB-C083-4765-86C2-A5BD7DE58C3E")] public interface IPriceListAttachment { string CustomDocumentId { get; set; } string FileName { get; set; } string DocumentNumber { get; set; } string DocumentDate { get; set; } string PriceListEffectiveDate { get; set; } string ContractDocumentDate { get; set; } string ContractDocumentNumber { get; set; } string Comment { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void AddInitialDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); void AddSubordinateDocumentId([MarshalAs(UnmanagedType.IDispatch)] object documentId); } [ComVisible(true)] [ProgId("Diadoc.Api.PriceListAttachment")] [Guid("2D0A054F-E3FA-4FBD-A64F-9C4EB73901BB")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IPriceListAttachment))] public partial class PriceListAttachment : SafeComObject, IPriceListAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } public void AddInitialDocumentId(object documentId) { InitialDocumentIds.Add((DocumentId) documentId); } public void AddSubordinateDocumentId(object documentId) { SubordinateDocumentIds.Add((DocumentId) documentId); } } [ComVisible(true)] [ProgId("Diadoc.Api.SignedContent")] [Guid("0EC71E3F-F203-4c49-B1D6-4DA6BFDD279B")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ISignedContent))] public partial class SignedContent : SafeComObject, ISignedContent { public bool SignByAttorney { get { return false; } set { } } public void LoadContentFromFile(string fileName) { Content = File.ReadAllBytes(fileName); } public void SaveContentToFile(string fileName) { if (Content != null) File.WriteAllBytes(fileName, Content); } public void LoadSignatureFromFile(string fileName) { Signature = File.ReadAllBytes(fileName); } public void SaveSignatureToFile(string fileName) { File.WriteAllBytes(fileName, Signature); } } [ComVisible(true)] [Guid("BD1E9A9B-E74C-41AD-94CE-199601346DDB")] public interface IDocumentSignature { string ParentEntityId { get; set; } byte[] Signature { get; set; } [Obsolete] bool SignByAttorney { get; set; } bool SignWithTestSignature { get; set; } void LoadFromFile(string fileName); } [ComVisible(true)] [ProgId("Diadoc.Api.DocumentSignature")] [Guid("28373DE6-3147-4d8b-B166-6D653F50EED3")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IDocumentSignature))] public partial class DocumentSignature : SafeComObject, IDocumentSignature { public bool SignByAttorney { get { return false; } set { } } public void LoadFromFile(string fileName) { Signature = File.ReadAllBytes(fileName); } } [ComVisible(true)] [Guid("F60296C5-6981-48A7-9E93-72B819B81172")] public interface IRequestedSignatureRejection { string ParentEntityId { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); void LoadComment(string commentFileName, string signatureFileName); } [ComVisible(true)] [ProgId("Diadoc.Api.RequestedSignatureRejection")] [Guid("C0106095-AF9F-462A-AEC0-A3E0B1ACAC6B")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IRequestedSignatureRejection))] public partial class RequestedSignatureRejection : SafeComObject, IRequestedSignatureRejection { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } public void LoadComment(string commentFileName, string signatureFileName) { SignedContent = new SignedContent { Content = File.ReadAllBytes(commentFileName), Signature = File.ReadAllBytes(signatureFileName), }; } } [ComVisible(true)] [Guid("8E18ECC8-18B4-4A9C-B322-1CF03DB3E07F")] public interface IReceiptAttachment { string ParentEntityId { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); } [ComVisible(true)] [ProgId("Diadoc.Api.ReceiptAttachment")] [Guid("45053335-83C3-4e62-9973-D6CC1872A60A")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IReceiptAttachment))] public partial class ReceiptAttachment : SafeComObject, IReceiptAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } } [ComVisible(true)] [Guid("5902A325-F31B-4B9B-978E-99C1CC7C9209")] public interface IResolutionAttachment { string InitialDocumentId { get; set; } Com.ResolutionType ResolutionTypeValue { get; set; } string Comment { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionAttachment")] [Guid("89D739B0-03F1-4E6C-8301-E3FEA9FD2AD6")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IResolutionAttachment))] public partial class ResolutionAttachment : SafeComObject, IResolutionAttachment { public Com.ResolutionType ResolutionTypeValue { get { return (Com.ResolutionType) ResolutionType; } set { ResolutionType = (ResolutionType) value; } } } [ComVisible(true)] [Guid("F19CEEBD-ECE5-49D2-A0FC-FE8C4B1B9E4C")] public interface IResolutionRequestAttachment { string InitialDocumentId { get; set; } Com.ResolutionRequestType RequestType { get; set; } string TargetUserId { get; set; } string TargetDepartmentId { get; set; } string Comment { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRequest")] [Guid("6043455B-3087-4A63-9870-66D54E8E34FB")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IResolutionRequestAttachment))] public partial class ResolutionRequestAttachment : SafeComObject, IResolutionRequestAttachment { public Com.ResolutionRequestType RequestType { get { return (Com.ResolutionRequestType) Type; } set { Type = (ResolutionRequestType) value; } } } [ComVisible(true)] [Guid("F23FCA9D-4FD3-4AE7-A431-275CAB51C7A1")] public interface IResolutionRequestCancellationAttachment { string InitialResolutionRequestId { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRequestCancellation")] [Guid("E80B8699-9883-4259-AA67-B84B03DD5F09")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IResolutionRequestCancellationAttachment))] public partial class ResolutionRequestCancellationAttachment : SafeComObject, IResolutionRequestCancellationAttachment { } [ComVisible(true)] [Guid("96F3613E-9DAA-4F2E-B8AB-7A8895D9E3AE")] public interface IResolutionRequestDenialAttachment { string InitialResolutionRequestId { get; set; } string Comment { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRequestDenial")] [Guid("BD79962A-D6AC-4831-9498-162C36AFD6E1")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IResolutionRequestDenialAttachment))] public partial class ResolutionRequestDenialAttachment : SafeComObject, IResolutionRequestDenialAttachment { } [ComVisible(true)] [Guid("39F44156-E889-4EFB-9368-350D1ED40B2F")] public interface IResolutionRequestDenialCancellationAttachment { string InitialResolutionRequestDenialId { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRequestDenialCancellation")] [Guid("4E8A0DEF-B6F7-4820-9CBE-D94A38E34DFC")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IResolutionRequestDenialCancellationAttachment))] public partial class ResolutionRequestDenialCancellationAttachment : SafeComObject, IResolutionRequestDenialCancellationAttachment { } [ComVisible(true)] [Guid("4BA8315A-FDAA-4D4F-BB14-9707E12DFA39")] public interface ICorrectionRequestAttachment { string ParentEntityId { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); } [ComVisible(true)] [ProgId("Diadoc.Api.CorrectionRequestAttachment")] [Guid("D78FC023-2BEF-49a4-BDBE-3B791168CE98")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ICorrectionRequestAttachment))] public partial class CorrectionRequestAttachment : SafeComObject, ICorrectionRequestAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent)signedContent; } } [ComVisible(true)] [Guid("D9B32F6D-C203-49DB-B224-6B30BB1F2BAA")] public interface IDocumentSenderSignature { string ParentEntityId { get; set; } byte[] Signature { get; set; } bool SignWithTestSignature { get; set; } void LoadFromFile(string fileName); } [ComVisible(true)] [ProgId("Diadoc.Api.DocumentSenderSignature")] [Guid("19CB816D-F518-4E91-94A2-F19B0CF7CC71")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IDocumentSenderSignature))] public partial class DocumentSenderSignature : SafeComObject, IDocumentSenderSignature { public void LoadFromFile(string fileName) { Signature = File.ReadAllBytes(fileName); } } [ComVisible(true)] [Guid("BDCD849E-F6A9-4EA4-8B84-482E10173DED")] public interface IDraftToSend { string BoxId { get; set; } string DraftId { get; set; } string ToBoxId { get; set; } string ToDepartmentId { get; set; } void AddDocumentSignature([MarshalAs(UnmanagedType.IDispatch)] object signature); } [ComVisible(true)] [ProgId("Diadoc.Api.DraftToSend")] [Guid("37127975-95FC-4247-8393-052EF27D1575")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IDraftToSend))] public partial class DraftToSend : SafeComObject, IDraftToSend { public void AddDocumentSignature(object signature) { DocumentSignatures.Add((DocumentSenderSignature) signature); } } [ComVisible(true)] [Guid("0A28FEDA-8108-49CE-AC56-31B16B2D036B")] public interface IRevocationRequestAttachment { string ParentEntityId { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); } [ComVisible(true)] [ProgId("Diadoc.Api.RevocationRequestAttachment")] [Guid("D2616BCD-A691-42B5-9707-6CE12742C5D3")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IRevocationRequestAttachment))] public partial class RevocationRequestAttachment : SafeComObject, IRevocationRequestAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent)signedContent; } } [ComVisible(true)] [Guid("4EED1BE6-7136-4B46-86C7-44F9A0FFD530")] public interface IXmlSignatureRejectionAttachment { string ParentEntityId { get; set; } SignedContent SignedContent { get; set; } void SetSignedContent([MarshalAs(UnmanagedType.IDispatch)] object signedContent); } [ComVisible(true)] [ProgId("Diadoc.Api.XmlSignatureRejectionAttachment")] [Guid("553DC13F-81B4-4010-886C-260DBD60D486")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (IXmlSignatureRejectionAttachment))] public partial class XmlSignatureRejectionAttachment : SafeComObject, IXmlSignatureRejectionAttachment { public void SetSignedContent(object signedContent) { SignedContent = (SignedContent) signedContent; } } [ComVisible(true)] [Guid("1B7169E9-455A-47C8-BD0F-5227B436CC61")] public interface IResolutionRouteAssignment { string InitialDocumentId { get; set; } string RouteId { get; set; } string Comment { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRouteAssignment")] [Guid("B4C90587-3DB9-4BFB-84A0-E1A8E082978D")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IResolutionRouteAssignment))] public partial class ResolutionRouteAssignment : SafeComObject, IResolutionRouteAssignment { } [ComVisible(true)] [Guid("DBCE6766-25F7-4EAB-9C4F-C59AB0054E57")] public interface IResolutionRouteRemoval { string ParentEntityId { get; set; } string RouteId { get; set; } string Comment { get; set; } } [ComVisible(true)] [ProgId("Diadoc.Api.ResolutionRouteRemoval")] [Guid("F1356D51-625B-4A24-AF11-3402D72908C8")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IResolutionRouteRemoval))] public partial class ResolutionRouteRemoval : SafeComObject, IResolutionRouteRemoval { } [ComVisible(true)] [Guid("12A46076-9F0F-4E89-8E49-68E3C5FC8C04")] public interface IResolutionRouteAssignmentInfo { string RouteId { get; } string Author { get; } } [ComVisible(true)] [Guid("AF775D73-D1BB-40C7-9DF5-D0305B606DC7")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IResolutionRouteAssignmentInfo))] public partial class ResolutionRouteAssignmentInfo : SafeComObject, IResolutionRouteAssignmentInfo { } [ComVisible(true)] [Guid("180C7D5E-7E8B-48ED-BAA4-AAA29D9467CC")] public interface IResolutionRouteRemovalInfo { string RouteId { get; } string Author { get; } } [ComVisible(true)] [Guid("AAB466D3-6BF3-4DB4-B7C9-DA7BD8F74837")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IResolutionRouteRemovalInfo))] public partial class ResolutionRouteRemovalInfo : SafeComObject, IResolutionRouteRemovalInfo { } }
using UnityEngine; namespace UnityStandardAssets.Characters.ThirdPerson { [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] public class ThirdPersonCharacter : MonoBehaviour { [SerializeField] float m_MovingTurnSpeed = 360; [SerializeField] float m_StationaryTurnSpeed = 180; [SerializeField] float m_JumpPower = 12f; [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f; [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others [SerializeField] float m_MoveSpeedMultiplier = 1f; [SerializeField] float m_AnimSpeedMultiplier = 1f; [SerializeField] float m_GroundCheckDistance = 0.1f; Rigidbody m_Rigidbody; Animator m_Animator; bool m_IsGrounded; float m_OrigGroundCheckDistance; const float k_Half = 0.5f; float m_TurnAmount; float m_ForwardAmount; Vector3 m_GroundNormal; float m_CapsuleHeight; Vector3 m_CapsuleCenter; CapsuleCollider m_Capsule; bool m_Crouching; void Start() { m_Animator = GetComponent<Animator>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; m_OrigGroundCheckDistance = m_GroundCheckDistance; } public void Move(Vector3 move, bool crouch, bool jump) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { HandleGroundedMovement(crouch, jump); } else { HandleAirborneMovement(); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); } void ScaleCapsuleForCrouching(bool crouch) { if (m_IsGrounded && crouch) { if (m_Crouching) return; m_Capsule.height = m_Capsule.height / 2f; m_Capsule.center = m_Capsule.center / 2f; m_Crouching = true; } else { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { m_Crouching = true; return; } m_Capsule.height = m_CapsuleHeight; m_Capsule.center = m_CapsuleCenter; m_Crouching = false; } } void PreventStandingInLowHeadroom() { // prevent standing up in crouch-only zones if (!m_Crouching) { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore)) { m_Crouching = true; } } } void UpdateAnimator(Vector3 move) { // update the animator parameters m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime); m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime); //m_Animator.SetBool("Crouch", m_Crouching); //m_Animator.SetBool("OnGround", m_IsGrounded); /*if (!m_IsGrounded) { m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y); }*/ // calculate which leg is behind, so as to leave that leg trailing in the jump animation // (This code is reliant on the specific run cycle offset in our animations, // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5) float runCycle = Mathf.Repeat( m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1); float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount; /*if (m_IsGrounded) { m_Animator.SetFloat("JumpLeg", jumpLeg); }*/ // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector, // which affects the movement speed because of the root motion. if (m_IsGrounded && move.magnitude > 0) { m_Animator.speed = m_AnimSpeedMultiplier; } else { // don't use that while airborne m_Animator.speed = 1; } } void HandleAirborneMovement() { // apply extra gravity from multiplier: Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity; m_Rigidbody.AddForce(extraGravityForce); m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f; } void HandleGroundedMovement(bool crouch, bool jump) { // check whether conditions are right to allow a jump: /*if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded")) { // jump! m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z); m_IsGrounded = false; m_Animator.applyRootMotion = false; m_GroundCheckDistance = 0.1f; }*/ } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount); transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0); } public void OnAnimatorMove() { // we implement this function to override the default root motion. // this allows us to modify the positional speed before it's applied. if (m_IsGrounded && Time.deltaTime > 0) { Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; } } void CheckGroundStatus() { RaycastHit hitInfo; #if UNITY_EDITOR // helper to visualise the ground check ray in the scene view Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance)); #endif // 0.1f is a small offset to start the ray from inside the character // it is also good to note that the transform position in the sample assets is at the base of the character if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance)) { m_GroundNormal = hitInfo.normal; m_IsGrounded = true; m_Animator.applyRootMotion = true; } else { m_IsGrounded = false; m_GroundNormal = Vector3.up; m_Animator.applyRootMotion = false; } } } }
using org.javarosa.core.model.condition; using org.javarosa.core.model.data; using org.javarosa.core.model.instance.utils; using org.javarosa.core.model.util.restorable; /* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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 org.javarosa.core.util.externalizable; using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace org.javarosa.core.model.instance { /** * An element of a FormInstance. * * TreeElements represent an XML node in the instance. It may either have a value (e.g., <name>Drew</name>), * a number of TreeElement children (e.g., <meta><device /><timestamp /><user_id /></meta>), or neither (e.g., * <empty_node />) * * TreeElements can also represent attributes. Attributes are unique from normal elements in that they are * not "children" of their parent, and are always leaf nodes: IE cannot have children. * * @author Acellam Guy , Clayton Sims * */ public class TreeElement : Externalizable { private String name; // can be null only for hidden root node public int multiplicity; // see TreeReference for special values private TreeElement parent; public Boolean repeatable; public Boolean isAttribute; private IAnswerData value; private ArrayList children = new ArrayList(); /* model properties */ public int dataType = Constants.DATATYPE_NULL; //TODO public Boolean required = false;// TODO private Constraint constraint = null; private String preloadHandler = null; private String preloadParams = null; private Boolean relevant = true; private Boolean enabled = true; // inherited properties private Boolean relevantInherited = true; private Boolean enabledInherited = true; private ArrayList observers; private List<TreeElement> attributes; private String namespace_; /** * TreeElement with null name and 0 multiplicity? (a "hidden root" node?) */ public TreeElement() : this(null, TreeReference.DEFAULT_MUTLIPLICITY) { } public TreeElement(String name) : this(name, TreeReference.DEFAULT_MUTLIPLICITY) { } public TreeElement(String name, int multiplicity) { this.name = name; this.multiplicity = multiplicity; this.parent = null; attributes = new List<TreeElement>(0); } /** * Construct a TreeElement which represents an attribute with the provided * namespace and name. * * @param namespace * @param name * @return A new instance of a TreeElement */ public static TreeElement constructAttributeElement(String namespace_, String name) { TreeElement element = new TreeElement(name); element.isAttribute = true; element.namespace_ = namespace_; element.multiplicity = TreeReference.INDEX_ATTRIBUTE; return element; } public Boolean isLeaf() { return (children.Count == 0); } public Boolean isChildable() { return (value == null); } public void setValue(IAnswerData value) { if (isLeaf()) { this.value = value; } else { throw new SystemException("Can't set data value for node that has children!"); } } public TreeElement getChild(String name, int multiplicity) { if (name.Equals(TreeReference.NAME_WILDCARD)) { if (multiplicity == TreeReference.INDEX_TEMPLATE || this.children.Count < multiplicity + 1) { return null; } return (TreeElement)this.children[multiplicity]; //droos: i'm suspicious of this } else { for (int i = 0; i < this.children.Count; i++) { TreeElement child = (TreeElement)this.children[i]; if (name.Equals(child.getName()) && child.getMult() == multiplicity) { return child; } } } return null; } /** * * Get all the child nodes of this element, with specific name * * @param name * @return */ public List<TreeElement> getChildrenWithName(String name) { return getChildrenWithName(name, false); } private List<TreeElement> getChildrenWithName(String name, Boolean includeTemplate) { List<TreeElement> v = new List<TreeElement>(); for (int i = 0; i < this.children.Count; i++) { TreeElement child = (TreeElement)this.children[i]; if ((child.getName().Equals(name) || name.Equals(TreeReference.NAME_WILDCARD)) && (includeTemplate || child.multiplicity != TreeReference.INDEX_TEMPLATE)) v.Add(child); } return v; } public int getNumChildren() { return this.children.Count; } public TreeElement getChildAt(int i) { return (TreeElement)children[i]; } /** * Add a child to this element * * @param child */ public void addChild(TreeElement child) { addChild(child, false); } private void addChild(TreeElement child, Boolean checkDuplicate) { if (!isChildable()) { throw new SystemException("Can't add children to node that has data value!"); } if (child.multiplicity == TreeReference.INDEX_UNBOUND) { throw new SystemException("Cannot add child with an unbound index!"); } if (checkDuplicate) { TreeElement existingChild = getChild(child.name, child.multiplicity); if (existingChild != null) { throw new SystemException("Attempted to add duplicate child!"); } } // try to keep things in order int i = children.Count; if (child.getMult() == TreeReference.INDEX_TEMPLATE) { TreeElement anchor = getChild(child.getName(), 0); if (anchor != null) i = children.IndexOf(anchor); } else { TreeElement anchor = getChild(child.getName(), (child.getMult() == 0 ? TreeReference.INDEX_TEMPLATE : child.getMult() - 1)); if (anchor != null) i = children.IndexOf(anchor) + 1; } children.Insert(i, child); child.setParent(this); child.setRelevant(isRelevant(), true); child.setEnabled(isEnabled(), true); } public void removeChild(TreeElement child) { children.Remove(child); } public void removeChild(String name, int multiplicity) { TreeElement child = getChild(name, multiplicity); if (child != null) { removeChild(child); } } public void removeChildren(String name) { removeChildren(name, false); } public void removeChildren(String name, Boolean includeTemplate) { List<TreeElement> v = getChildrenWithName(name, includeTemplate); for (int i = 0; i < v.Count; i++) { removeChild((TreeElement)v[i]); } } public void removeChildAt(int i) { children.RemoveAt(i); } public int getChildMultiplicity(String name) { return getChildrenWithName(name, false).Count; } public TreeElement shallowCopy() { TreeElement newNode = new TreeElement(name, multiplicity); newNode.parent = parent; newNode.repeatable = repeatable; newNode.dataType = dataType; newNode.relevant = relevant; newNode.required = required; newNode.enabled = enabled; newNode.constraint = constraint; newNode.preloadHandler = preloadHandler; newNode.preloadParams = preloadParams; newNode.setAttributesFromSingleStringVector(getSingleStringAttributeVector()); if (value != null) { newNode.value = (IAnswerData)value.Clone(); } newNode.children = children; return newNode; } public TreeElement deepCopy(Boolean includeTemplates) { TreeElement newNode = shallowCopy(); newNode.children = new ArrayList(); for (int i = 0; i < children.Count; i++) { TreeElement child = (TreeElement) children[i]; if (includeTemplates || child.getMult() != TreeReference.INDEX_TEMPLATE) { newNode.addChild(child.deepCopy(includeTemplates)); } } return newNode; } /* ==== MODEL PROPERTIES ==== */ // factoring inheritance rules public Boolean isRelevant() { return relevantInherited && relevant; } // factoring in inheritance rules public Boolean isEnabled() { return enabledInherited && enabled; } /* ==== SPECIAL SETTERS (SETTERS WITH SIDE-EFFECTS) ==== */ public Boolean setAnswer(IAnswerData answer) { if (value != null || answer != null) { setValue(answer); alertStateObservers(FormElementStateListener_Fields.CHANGE_DATA); return true; } else { return false; } } public void setRequired(Boolean required) { if (this.required != required) { this.required = required; alertStateObservers(FormElementStateListener_Fields.CHANGE_REQUIRED); } } public void setRelevant(Boolean relevant) { setRelevant(relevant, false); } private void setRelevant(Boolean relevant, Boolean inherited) { Boolean oldRelevancy = isRelevant(); if (inherited) { this.relevantInherited = relevant; } else { this.relevant = relevant; } if (isRelevant() != oldRelevancy) { for (int i = 0; i < children.Count; i++) { ((TreeElement) children[i]).setRelevant(isRelevant(), true); } for(int i = 0 ; i < attributes.Count; ++i ) { attributes[i].setRelevant(isRelevant(), true); } alertStateObservers(FormElementStateListener_Fields.CHANGE_RELEVANT); } } public void setEnabled(Boolean enabled) { setEnabled(enabled, false); } public void setEnabled(Boolean enabled, Boolean inherited) { Boolean oldEnabled = isEnabled(); if (inherited) { this.enabledInherited = enabled; } else { this.enabled = enabled; } if (isEnabled() != oldEnabled) { for (int i = 0; i < children.Count; i++) { ((TreeElement) children[i]).setEnabled(isEnabled(), true); } alertStateObservers(FormElementStateListener_Fields.CHANGE_ENABLED); } } /* ==== OBSERVER PATTERN ==== */ public void registerStateObserver(FormElementStateListener qsl) { if (observers == null) observers = new ArrayList(); if (!observers.Contains(qsl)) { observers.Add(qsl); } } public void unregisterStateObserver(FormElementStateListener qsl) { if (observers != null) { observers.Remove(qsl); if (observers.Count<1) observers = null; } } public void unregisterAll() { observers = null; } public void alertStateObservers(int changeFlags) { if (observers != null) { for (IEnumerator e = observers.GetEnumerator(); e.MoveNext(); ) ((FormElementStateListener)e.Current) .formElementStateChanged(this, changeFlags); } } /* ==== VISITOR PATTERN ==== */ /** * Visitor pattern acceptance method. * * @param visitor * The visitor traveling this tree */ public void accept(ITreeVisitor visitor) { visitor.visit(this); IEnumerator en = children.GetEnumerator(); while (en.MoveNext()) { ((TreeElement)en.Current).accept(visitor); } } /* ==== Attributes ==== */ /** * Returns the number of attributes of this element. */ public int getAttributeCount() { return attributes.Count; } /** * get namespace of attribute at 'index' in the vector * * @param index * @return String */ public String getAttributeNamespace(int index) { return attributes[index].namespace_; } /** * get name of attribute at 'index' in the vector * * @param index * @return String */ public String getAttributeName(int index) { return attributes[index].name; } /** * get value of attribute at 'index' in the vector * * @param index * @return String */ public String getAttributeValue(int index) { return getAttributeValue(attributes[index]); } /** * Get the String value of the provided attribute * * @param attribute * @return */ private String getAttributeValue(TreeElement attribute) { if (attribute.getValue() == null) { return null; } else { return attribute.getValue().uncast().String; } } /** * Retrieves the TreeElement representing the attribute at * the provided namespace and name, or null if none exists. * * If 'null' is provided for the namespace, it will match the first * attribute with the matching name. * * @param index * @return TreeElement */ public TreeElement getAttribute(String namespace_, String name) { foreach (TreeElement attribute in attributes) { if (attribute.getName().Equals(name) && (namespace_ == null || namespace_.Equals(attribute.namespace_))) { return attribute; } } return null; } /** * get value of attribute with namespace:name' in the vector * * @param index * @return String */ public String getAttributeValue(String namespace_, String name) { TreeElement element = getAttribute(namespace_, name); return element == null ? null : getAttributeValue(element); } /** * Sets the given attribute; a value of null removes the attribute * * */ public void setAttribute(String namespace_, String name, String value) { for (int i = attributes.Count - 1; i >= 0; i--) { TreeElement attribut = attributes[i]; if (attribut.name.Equals(name) && (namespace_ == null || namespace_.Equals(attribut.namespace_))) { if (value == null) { attributes.RemoveAt(i); } else { attribut.setValue(new UncastData(value)); } return; } } if (namespace_ == null) { namespace_ = ""; } TreeElement attr = TreeElement.constructAttributeElement(namespace_, name); attr.setValue(new UncastData(value)); attr.setParent(this); attributes.Add(attr); } /** * A method for producing a vector of single strings - from the current * attribute vector of string [] arrays. * * @return */ public ArrayList getSingleStringAttributeVector() { ArrayList strings = new ArrayList(); if (attributes.Count == 0) return null; else { for (int i = 0; i < this.attributes.Count; i++) { TreeElement attribute = attributes[i]; String value = getAttributeValue(attribute); if (attribute.namespace_ == null || attribute.namespace_ == "") strings.Add(attribute.getName()+ "=" + value); else strings.Add(attribute.namespace_ + ":" + attribute.getName() + "=" + value); } return strings; } } /* public List<SelectChoice> getSingleStringAttributeVector() { List<SelectChoice> strings = new List<SelectChoice>(); if (attributes.Count == 0) return null; else { for (int i = 0; i < this.attributes.Count; i++) { TreeElement attribute = attributes[i]; String value = getAttributeValue(attribute); if (attribute.namespace_ == null || attribute.namespace_ == "") strings.Add((attribute.getName() + "=" + value); else strings.Add(attribute.namespace_ + ":" + attribute.getName() + "=" + value); } return strings; } }*/ /** * Method to repopulate the attribute vector from a vector of singleStrings * * @param attStrings */ public void setAttributesFromSingleStringVector(ArrayList attStrings) { this.attributes = new List<TreeElement>(0); if (attStrings != null) { for (int i = 0; i < attStrings.Count; i++) { addSingleAttribute(i, attStrings); } } } private void addSingleAttribute(int i, ArrayList attStrings) { String att = (String)attStrings[i]; String[] array = new String[3]; int start = 0; // get namespace int pos = -1; // Clayton Sims - Jun 1, 2009 : Updated this code: // We want to find the _last_ possible ':', not the // first one. Namespaces can have URLs in them. //int pos = att.indexOf(":"); while (att.IndexOf(":", pos + 1) != -1) { pos = att.IndexOf(":", pos + 1); } if (pos == -1) { array[0] = null; start = 0; } else { array[0] = att.Substring(start, pos); start = ++pos; } // get attribute name pos = att.IndexOf("="); array[1] = att.Substring(start, pos); start = ++pos; array[2] = att.Substring(start); this.setAttribute(array[0], array[1], array[2]); } /* ==== SERIALIZATION ==== */ /* * TODO: * * this new serialization scheme is kind of lame. ideally, we shouldn't have * to sub-class TreeElement at all; we should have an API that can * seamlessly represent complex data model objects (like weight history or * immunizations) as if they were explicity XML subtrees underneath the * parent TreeElement * * failing that, we should wrap this scheme in an ExternalizableWrapper */ /* * (non-Javadoc) * * @see * org.javarosa.core.services.storage.utilities.Externalizable#readExternal * (java.io.DataInputStream) */ public void readExternal(BinaryReader in_renamed, PrototypeFactory pf) { name = ExtUtil.nullIfEmpty(ExtUtil.readString(in_renamed)); multiplicity = ExtUtil.readInt(in_renamed); repeatable = ExtUtil.readBool(in_renamed); value = (IAnswerData)ExtUtil.read(in_renamed, new ExtWrapNullable(new ExtWrapTagged()), pf); // children = ExtUtil.nullIfEmpty((Vector)ExtUtil.read(in, new // ExtWrapList(TreeElement.class), pf)); // Jan 22, 2009 - [email protected] // old line: children = ExtUtil.nullIfEmpty((Vector)ExtUtil.read(in, new // ExtWrapList(TreeElement.class), pf)); // New Child deserialization // 1. read null status as boolean // 2. read number of children // 3. for i < number of children // 3.1 if read boolean true , then create TreeElement and deserialize // directly. // 3.2 if read boolean false then create tagged element and deserialize // child if (!ExtUtil.readBool(in_renamed)) { // 1. children = null; } else { children = new ArrayList(); // 2. int numChildren = (int)ExtUtil.readNumeric(in_renamed); // 3. for (int i = 0; i < numChildren; ++i) { Boolean normal = ExtUtil.readBool(in_renamed); TreeElement child; if (normal) { // 3.1 child = new TreeElement(); child.readExternal(in_renamed, pf); } else { // 3.2 child = (TreeElement)ExtUtil.read(in_renamed, new ExtWrapTagged(), pf); } child.setParent(this); children.Add(child); } } // end Jan 22, 2009 dataType = ExtUtil.readInt(in_renamed); relevant = ExtUtil.readBool(in_renamed); required = ExtUtil.readBool(in_renamed); enabled = ExtUtil.readBool(in_renamed); relevantInherited = ExtUtil.readBool(in_renamed); enabledInherited = ExtUtil.readBool(in_renamed); constraint = (Constraint)ExtUtil.read(in_renamed, new ExtWrapNullable( typeof(Constraint)), pf); preloadHandler = ExtUtil.nullIfEmpty(ExtUtil.readString(in_renamed)); preloadParams = ExtUtil.nullIfEmpty(ExtUtil.readString(in_renamed)); ArrayList attStrings = ExtUtil.nullIfEmpty((ArrayList)ExtUtil.read(in_renamed, new ExtWrapList(typeof(String)), pf)); setAttributesFromSingleStringVector(attStrings); } /* * (non-Javadoc) * * @see * org.javarosa.core.services.storage.utilities.Externalizable#writeExternal * (java.io.DataOutputStream) */ public void writeExternal(BinaryWriter out_renamed) { ExtUtil.writeString(out_renamed, ExtUtil.emptyIfNull(name)); ExtUtil.writeNumeric(out_renamed, multiplicity); ExtUtil.writeBool(out_renamed, repeatable); ExtUtil.write(out_renamed, new ExtWrapNullable(value == null ? null : new ExtWrapTagged(value))); // Jan 22, 2009 - [email protected] // old line: ExtUtil.write(out, new // ExtWrapList(ExtUtil.emptyIfNull(children))); // New Child serialization // 1. write null status as boolean // 2. write number of children // 3. for all child in children // 3.1 if child type == TreeElement write boolean true , then serialize // directly. // 3.2 if child type != TreeElement, write boolean false, then tagged // child if (children == null) { // 1. ExtUtil.writeBool(out_renamed, false); } else { // 1. ExtUtil.writeBool(out_renamed, true); // 2. ExtUtil.writeNumeric(out_renamed, children.Count); // 3. IEnumerator en = children.GetEnumerator(); while (en.MoveNext()) { TreeElement child = (TreeElement)en.Current; if (child.GetType() == typeof(TreeElement)) { // 3.1 ExtUtil.writeBool(out_renamed, true); child.writeExternal(out_renamed); } else { // 3.2 ExtUtil.writeBool(out_renamed, false); ExtUtil.write(out_renamed, new ExtWrapTagged(child)); } } } // end Jan 22, 2009 ExtUtil.writeNumeric(out_renamed, dataType); ExtUtil.writeBool(out_renamed, relevant); ExtUtil.writeBool(out_renamed, required); ExtUtil.writeBool(out_renamed, enabled); ExtUtil.writeBool(out_renamed, relevantInherited); ExtUtil.writeBool(out_renamed, enabledInherited); ExtUtil.write(out_renamed, new ExtWrapNullable(constraint)); // TODO: inefficient for repeats ExtUtil.writeString(out_renamed, ExtUtil.emptyIfNull(preloadHandler)); ExtUtil.writeString(out_renamed, ExtUtil.emptyIfNull(preloadParams)); ArrayList attStrings = getSingleStringAttributeVector(); ArrayList al = ExtUtil.emptyIfNull(attStrings); ExtUtil.write(out_renamed, new ExtWrapList(al)); } //rebuilding a node from an imported instance // there's a lot of error checking we could do on the received instance, but it's // easier to just ignore the parts that are incorrect public void populate(TreeElement incoming, FormDef f) { if (this.isLeaf()) { // check that incoming doesn't have children? IAnswerData value = incoming.getValue(); if (value == null) { this.setValue(null); } else if (this.dataType == Constants.DATATYPE_TEXT || this.dataType == Constants.DATATYPE_NULL) { this.setValue(value); // value is a StringData } else { String textVal = value.ToString(); IAnswerData typedVal = RestoreUtils.xfFact.parseData(textVal, this.dataType, this.getRef(), f); this.setValue(typedVal); } } else { ArrayList names = new ArrayList(); for (int i = 0; i < this.getNumChildren(); i++) { TreeElement child = this.getChildAt(i); if (!names.Contains(child.getName())) { names.Add(child.getName()); } } // remove all default repetitions from skeleton data model (_preserving_ templates, though) for (int i = 0; i < this.getNumChildren(); i++) { TreeElement child = this.getChildAt(i); if (child.repeatable && child.getMult() != TreeReference.INDEX_TEMPLATE) { this.removeChildAt(i); i--; } } // make sure ordering is preserved (needed for compliance with xsd schema) if (this.getNumChildren() != names.Count) { throw new SystemException("sanity check failed"); } for (int i = 0; i < this.getNumChildren(); i++) { TreeElement child = this.getChildAt(i); String expectedName = (String) names[i]; if (!child.getName().Equals(expectedName)) { TreeElement child2 = null; int j; for (j = i + 1; j < this.getNumChildren(); j++) { child2 = this.getChildAt(j); if (child2.getName().Equals(expectedName)) { break; } } if (j == this.getNumChildren()) { throw new SystemException("sanity check failed"); } this.removeChildAt(j); this.children.Insert(i,child2); } } // java i hate you so much for (int i = 0; i < this.getNumChildren(); i++) { TreeElement child = this.getChildAt(i); List<TreeElement> newChildren = incoming.getChildrenWithName(child.getName()); if (child.repeatable) { for (int k = 0; k < newChildren.Count; k++) { TreeElement newChild = child.deepCopy(true); newChild.setMult(k); this.children.Insert(i + k + 1,newChild); newChild.populate((TreeElement)newChildren[k], f); } i += newChildren.Count; } else { if (newChildren.Count == 0) { child.setRelevant(false); } else { child.populate((TreeElement)newChildren[0], f); } } } } } //this method is for copying in the answers to an itemset. the template node of the destination //is used for overall structure (including data types), and the itemset source node is used for //raw data. note that data may be coerced across types, which may result in type conversion error //very similar in structure to populate() public void populateTemplate(TreeElement incoming, FormDef f) { if (this.isLeaf()) { IAnswerData value = incoming.value; if (value == null) { this.setValue(null); } else { Type classType = CompactInstanceWrapper.classForDataType(this.dataType); if (classType == null) { throw new SystemException("data type [" + value.GetType().Name + "] not supported inside itemset"); } else if (classType.IsAssignableFrom(value.GetType()) && !(value is SelectOneData || value is SelectMultiData)) { this.setValue(value); } else { String textVal = RestoreUtils.xfFact.serializeData(value); IAnswerData typedVal = RestoreUtils.xfFact.parseData(textVal, this.dataType, this.getRef(), f); this.setValue(typedVal); } } } else { for (int i = 0; i < this.getNumChildren(); i++) { TreeElement child = this.getChildAt(i); List<TreeElement> newChildren = incoming.getChildrenWithName(child.getName()); if (child.repeatable) { for (int k = 0; k < newChildren.Count; k++) { TreeElement template = f.Instance.getTemplate(child.getRef()); TreeElement newChild = template.deepCopy(false); newChild.setMult(k); this.children.Insert(i + k + 1,newChild); newChild.populateTemplate((TreeElement)newChildren[k], f); } i += newChildren.Count; } else { child.populateTemplate((TreeElement)newChildren[0], f); } } } } //return the tree reference that corresponds to this tree element public TreeReference getRef() { TreeElement elem = this; TreeReference ref_ = TreeReference.selfRef(); while (elem != null) { TreeReference step; if (elem.name != null) { step = TreeReference.selfRef(); step.add(elem.name, elem.multiplicity); } else { step = TreeReference.rootRef(); } ref_ = ref_.parent(step); elem = elem.parent; } return ref_; } public int getDepth() { TreeElement elem = this; int depth = 0; while (elem.name != null) { depth++; elem = elem.parent; } return depth; } public String getPreloadHandler() { return preloadHandler; } public Constraint getConstraint() { return constraint; } public void setPreloadHandler(String preloadHandler) { this.preloadHandler = preloadHandler; } public void setConstraint(Constraint constraint) { this.constraint = constraint; } public String getPreloadParams() { return preloadParams; } public void setPreloadParams(String preloadParams) { this.preloadParams = preloadParams; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMult() { return multiplicity; } public void setMult(int multiplicity) { this.multiplicity = multiplicity; } public void setParent(TreeElement parent) { this.parent = parent; } public TreeElement getParent() { return parent; } public IAnswerData getValue() { return value; } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseSourceAttribute indicates the source to be used to /// provide test cases for a test method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture { private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestCaseSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// The name of a the method, property or fiend to be used as a source /// </summary> public string SourceName { get; private set; } /// <summary> /// A Type to be used as a source /// </summary> public Type SourceType { get; private set; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string Category { get; set; } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The IMethod for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { foreach (TestCaseParameters parms in GetTestCasesFor(method)) yield return _builder.BuildTestMethod(method, suite, parms); } #endregion #region Helper Methods /// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { #if NETCF int numParameters = method.IsGenericMethodDefinition ? 0 : method.GetParameters().Length; #else int numParameters = method.GetParameters().Length; #endif foreach (object item in source) { var parms = item as ITestCaseData; if (parms == null) { object[] args = item as object[]; if (args != null) { #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); numParameters = mi == null ? 0 : mi.GetParameters().Length; } #endif if (args.Length != numParameters)//parameters.Length) args = new object[] { item }; } else if (item is Array) { Array array = item as Array; #if NETCF if (array.Rank == 1 && (method.IsGenericMethodDefinition || array.Length == numParameters))//parameters.Length)) #else if (array.Rank == 1 && array.Length == numParameters)//parameters.Length) #endif { args = new object[array.Length]; for (int i = 0; i < array.Length; i++) args[i] = array.GetValue(i); #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); if (mi == null || array.Length != mi.GetParameters().Length) args = new object[] {item}; } #endif } else { args = new object[] { item }; } } else { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; } private IEnumerable GetTestCaseSource(IMethodInfo method) { Type sourceType = SourceType ?? method.TypeInfo.Type; // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (IEnumerable)field.GetValue(null) : SourceMustBeStaticError(); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (IEnumerable)property.GetValue(null, null) : SourceMustBeStaticError(); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (IEnumerable)m.Invoke(null, null) : SourceMustBeStaticError(); } return null; } private static IEnumerable SourceMustBeStaticError() { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."); return new TestCaseParameters[] { parms }; } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Management.RecoveryServices.Backup.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices.Backup { /// <summary> /// The Resource Manager API includes operations for triggering and /// managing the backups of items protected by your Recovery Services /// Vault. /// </summary> internal partial class BackupOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IBackupOperations { /// <summary> /// Initializes a new instance of the BackupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal BackupOperations(RecoveryServicesBackupManagementClient client) { this._client = client; } private RecoveryServicesBackupManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient. /// </summary> public RecoveryServicesBackupManagementClient Client { get { return this._client; } } /// <summary> /// The Trigger Backup Operation starts an operation in the service /// which triggers the backup of the specified item in the specified /// container in your Recovery Services Vault. This is an asynchronous /// operation. To determine whether the backend service has finished /// processing the request, call Get Protected Item Operation Result /// API. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='customRequestHeaders'> /// Required. Request header parameters. /// </param> /// <param name='fabricName'> /// Optional. Fabric name of the protected item. /// </param> /// <param name='containerName'> /// Optional. Name of the container where the protected item belongs to. /// </param> /// <param name='protectedItemName'> /// Optional. Name of the protected item which has to be backed up. /// </param> /// <param name='request'> /// Optional. Backup request for the backup item. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Base recovery job response for all the asynchronous operations. /// </returns> public async Task<BaseRecoveryServicesJobResponse> TriggerBackupAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, TriggerBackupRequest request, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } if (request != null) { if (request.Item != null) { if (request.Item.Properties == null) { throw new ArgumentNullException("request.Item.Properties"); } } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("request", request); TracingAdapter.Enter(invocationId, this, "TriggerBackupAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupFabrics/"; if (fabricName != null) { url = url + Uri.EscapeDataString(fabricName); } url = url + "/protectionContainers/"; if (containerName != null) { url = url + Uri.EscapeDataString(containerName); } url = url + "/protectedItems/"; if (protectedItemName != null) { url = url + Uri.EscapeDataString(protectedItemName); } url = url + "/backup"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; if (request != null) { if (request.Item != null) { JObject itemValue = new JObject(); requestDoc = itemValue; JObject propertiesValue = new JObject(); itemValue["properties"] = propertiesValue; if (request.Item.Properties is IaaSVMBackupRequest) { propertiesValue["objectType"] = "IaasVMBackupRequest"; IaaSVMBackupRequest derived = ((IaaSVMBackupRequest)request.Item.Properties); if (derived.RecoveryPointExpiryTimeInUTC != null) { propertiesValue["recoveryPointExpiryTimeInUTC"] = derived.RecoveryPointExpiryTimeInUTC.Value; } } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result BaseRecoveryServicesJobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BaseRecoveryServicesJobResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"]; if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null) { string azureAsyncOperationInstance = ((string)azureAsyncOperationValue); result.AzureAsyncOperation = azureAsyncOperationInstance; } JToken retryAfterValue = responseDoc["retryAfter"]; if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null) { string retryAfterInstance = ((string)retryAfterValue); result.RetryAfter = retryAfterInstance; } JToken statusValue = responseDoc["Status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using Zenject; using NUnit.Framework; using System.Linq; using ModestTree; using Assert=ModestTree.Assert; namespace Zenject.Tests { [TestFixture] public class TestTestOptional : TestWithContainer { class Test1 { } class Test2 { [Inject] public Test1 val1 = null; } class Test3 { [InjectOptional] public Test1 val1 = null; } class Test0 { [InjectOptional] public int Val1 = 5; } [Test] public void TestFieldRequired() { Container.Bind<Test2>().ToSingle(); Assert.That(Container.ValidateResolve<Test2>().Any()); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Test2>(); }); } [Test] public void TestFieldOptional() { Container.Bind<Test3>().ToSingle(); Assert.That(Container.ValidateResolve<Test3>().IsEmpty()); var test = Container.Resolve<Test3>(); Assert.That(test.val1 == null); } [Test] public void TestFieldOptional2() { Container.Bind<Test3>().ToSingle(); var test1 = new Test1(); Container.Bind<Test1>().ToInstance(test1); Assert.That(Container.ValidateResolve<Test3>().IsEmpty()); Assert.IsEqual(Container.Resolve<Test3>().val1, test1); } [Test] public void TestFieldOptional3() { Container.Bind<Test0>().ToTransient(); // Should not redefine the hard coded value in this case Assert.IsEqual(Container.Resolve<Test0>().Val1, 5); Container.Bind<int>().ToInstance(3); Assert.IsEqual(Container.Resolve<Test0>().Val1, 3); } class Test4 { public Test4(Test1 val1) { } } class Test5 { public Test1 Val1; public Test5( [InjectOptional] Test1 val1) { Val1 = val1; } } [Test] public void TestParameterRequired() { Container.Bind<Test4>().ToSingle(); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Test4>(); }); Assert.That(Container.ValidateResolve<Test2>().Any()); } [Test] public void TestParameterOptional() { Container.Bind<Test5>().ToSingle(); Assert.That(Container.ValidateResolve<Test5>().IsEmpty()); var test = Container.Resolve<Test5>(); Assert.That(test.Val1 == null); } class Test6 { public Test6(Test2 test2) { } } [Test] public void TestChildDependencyOptional() { Container.Bind<Test6>().ToSingle(); Container.Bind<Test2>().ToSingle(); Assert.That(Container.ValidateResolve<Test6>().Any()); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Test6>(); }); } class Test7 { public int Val1; public Test7( [InjectOptional] int val1) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesDefault() { Container.Bind<Test7>().ToSingle(); Assert.That(Container.ValidateResolve<Test7>().IsEmpty()); Assert.IsEqual(Container.Resolve<Test7>().Val1, 0); } class Test8 { public int Val1; public Test8( [InjectOptional] int val1 = 5) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesExplicitDefault() { Container.Bind<Test8>().ToSingle(); Assert.That(Container.ValidateResolve<Test8>().IsEmpty()); Assert.IsEqual(Container.Resolve<Test8>().Val1, 5); } class Test8_2 { public int Val1; public Test8_2(int val1 = 5) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalUsesExplicitDefault2() { Container.Bind<Test8_2>().ToSingle(); Assert.That(Container.ValidateResolve<Test8_2>().IsEmpty()); Assert.IsEqual(Container.Resolve<Test8_2>().Val1, 5); } class Test9 { public int? Val1; public Test9( [InjectOptional] int? val1) { Val1 = val1; } } [Test] public void TestPrimitiveParamOptionalNullable() { Container.Bind<Test9>().ToSingle(); Assert.That(Container.ValidateResolve<Test9>().IsEmpty()); Assert.That(!Container.Resolve<Test9>().Val1.HasValue); } } }
using Baseline; using Marten.Schema.Identity; using Marten.Schema.Identity.Sequences; using Marten.Schema.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Schema.Testing.Identity.Sequences { [Collection("sequences")] public class hilo_configuration_overrides { [Fact] public void can_establish_the_hilo_starting_point() { // SAMPLE: ResetHiloSequenceFloor var store = DocumentStore.For(opts => { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "sequences"; }); // Resets the minimum Id number for the IntDoc document // type to 2500 store.Tenancy.Default.ResetHiloSequenceFloor<IntDoc>(2500); // ENDSAMPLE using (var session = store.OpenSession()) { var doc1 = new IntDoc(); var doc2 = new IntDoc(); var doc3 = new IntDoc(); session.Store(doc1, doc2, doc3); doc1.Id.ShouldBeGreaterThanOrEqualTo(2500); doc2.Id.ShouldBeGreaterThanOrEqualTo(2500); doc3.Id.ShouldBeGreaterThanOrEqualTo(2500); } } [Fact] public void default_everything() { var defaults = new HiloSettings(); var store = DocumentStore.For(opts => { opts.Connection(ConnectionSource.ConnectionString); opts.DatabaseSchemaName = "sequences"; }); var mapping = store.Storage.MappingFor(typeof (IntDoc)); mapping.ToIdAssignment<IntDoc>(store.Tenancy.Default) .As<IdAssigner<IntDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).MaxLo.ShouldBe(defaults.MaxLo); } [Fact] public void override_the_global_settings() { // SAMPLE: configuring-global-hilo-defaults var store = DocumentStore.For(_ => { _.HiloSequenceDefaults.MaxLo = 55; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sequences"; }); // ENDSAMPLE var mapping = store.Storage.MappingFor(typeof(IntDoc)); var idStrategy = mapping.ToIdAssignment<IntDoc>(store.Tenancy.Default) .As<IdAssigner<IntDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).MaxLo.ShouldBe(55); } [Fact] public void override_by_document_on_marten_registry() { // SAMPLE: overriding-hilo-with-marten-registry var store = DocumentStore.For(_ => { // Overriding the Hilo settings for the document type "IntDoc" _.Schema.For<IntDoc>() .HiloSettings(new HiloSettings {MaxLo = 66}); _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sequences"; }); // ENDSAMPLE var mapping = store.Storage.MappingFor(typeof(IntDoc)); mapping.ToIdAssignment<IntDoc>(store.Tenancy.Default) .As<IdAssigner<IntDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).MaxLo.ShouldBe(66); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).As<HiloSequence>().EntityName.ShouldBe("IntDoc"); } [Fact] public void can_override_at_document_level_with_attribute() { var store = DocumentStore.For(_ => { _.HiloSequenceDefaults.MaxLo = 33; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sequences"; }); var mapping = store.Storage.MappingFor(typeof(IntDoc)); mapping.ToIdAssignment<IntDoc>(store.Tenancy.Default) .As<IdAssigner<IntDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).MaxLo.ShouldBe(33); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).As<HiloSequence>().EntityName.ShouldBe("IntDoc"); mapping = store.Storage.MappingFor(typeof(OverriddenHiloDoc)); mapping.ToIdAssignment<OverriddenHiloDoc>(store.Tenancy.Default) .As<IdAssigner<OverriddenHiloDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(OverriddenHiloDoc)).MaxLo.ShouldBe(66); store.Tenancy.Default.Sequences .SequenceFor(typeof(OverriddenHiloDoc)).As<HiloSequence>().EntityName.ShouldBe("Entity"); } [Fact] public void set_default_sequencename() { var store = DocumentStore.For(_ => { _.HiloSequenceDefaults.MaxLo = 33; _.HiloSequenceDefaults.SequenceName = "ID"; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sequences"; }); var mapping = store.Storage.MappingFor(typeof(IntDoc)); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).MaxLo.ShouldBe(33); store.Tenancy.Default.Sequences .SequenceFor(typeof(IntDoc)).As<HiloSequence>().EntityName.ShouldBe("ID"); mapping = store.Storage.MappingFor(typeof(OverriddenHiloDoc)); mapping.ToIdAssignment<OverriddenHiloDoc>(store.Tenancy.Default) .As<IdAssigner<OverriddenHiloDoc, int>>().Generator .ShouldBeOfType<IntHiloGenerator>(); store.Tenancy.Default.Sequences .SequenceFor(typeof(OverriddenHiloDoc)).MaxLo.ShouldBe(66); store.Tenancy.Default.Sequences .SequenceFor(typeof(OverriddenHiloDoc)).As<HiloSequence>().EntityName.ShouldBe("Entity"); } [Fact] public void create_docs_with_global_id() { // SAMPLE: configuring-global-hilo-defaults-sequencename var store = DocumentStore.For(_ => { _.HiloSequenceDefaults.SequenceName = "Entity"; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sequences"; }); // ENDSAMPLE using (var session = store.OpenSession()) { var doc1 = new IntDoc(); var doc2 = new Int2Doc(); var doc3 = new IntDoc(); var doc4 = new Int2Doc(); session.Store(doc1); session.Store(doc2); session.Store(doc3); session.Store(doc4); doc1.Id.ShouldBeGreaterThanOrEqualTo(1); doc2.Id.ShouldBe(doc1.Id + 1); doc3.Id.ShouldBe(doc2.Id + 1); doc4.Id.ShouldBe(doc3.Id + 1); } } } public class Int2Doc { public int Id { get; set; } } // SAMPLE: overriding-hilo-with-attribute [HiloSequence(MaxLo = 66, SequenceName = "Entity")] public class OverriddenHiloDoc { public int Id { get; set; } } // ENDSAMPLE }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Drawing; using System.ComponentModel; using System.Text.RegularExpressions; namespace StickFactory { /// <summary> /// Dictionary which could be (de)serialized. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <remarks>Documented by Dev05, 2007-08-10</remarks> [Serializable] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { /// <summary> /// This property is reserved, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"></see> to the class instead. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"></see> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"></see> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"></see> method. /// </returns> /// <remarks>Documented by Dev05, 2007-08-08</remarks> public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"></see> stream from which the object is deserialized.</param> /// <remarks>Documented by Dev05, 2007-08-08</remarks> public void ReadXml(XmlReader reader) { bool keyIsAtomic = false; XmlSerializer keySerializer = null; if (TypeIsAtomic(typeof(TKey))) keyIsAtomic = true; else keySerializer = new XmlSerializer(typeof(TKey)); bool valueIsAtomic = false; XmlSerializer valueSerializer = null; if (TypeIsAtomic(typeof(TValue))) valueIsAtomic = true; else valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) { return; } while (reader.NodeType != XmlNodeType.EndElement) { TKey key; if (keyIsAtomic) //Shorter version, but works only for simple types (int, string, enum, Color, Font, ...) key = (TKey)GetValue(typeof(TKey), reader.GetAttribute("key")); else { if (!valueIsAtomic) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); } key = (TKey)keySerializer.Deserialize(reader); if (!valueIsAtomic) reader.ReadEndElement(); } TValue value; if (valueIsAtomic) //Shorter version, but works only for simple types (int, string, enum, Color, Font, ...) value = (TValue)GetValue(typeof(TValue), reader.GetAttribute("value")); else { if (keyIsAtomic) reader.ReadStartElement("item"); else reader.ReadStartElement("value"); value = (TValue)valueSerializer.Deserialize(reader); if (!keyIsAtomic) reader.ReadEndElement(); } this.Add(key, value); if (!keyIsAtomic || !valueIsAtomic) reader.ReadEndElement(); else reader.Read(); reader.MoveToContent(); } reader.ReadEndElement(); } /// <summary> /// Parses the specified string read form the XML and returns the value /// it represents as the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-08</remarks> private object GetValue(Type type, string value) { if (type == typeof(string)) { return value; } else if (type == typeof(bool)) { return Convert.ToBoolean(value); } else if (type.IsEnum) { return Enum.Parse(type, value, true); } else if (type == typeof(Color)) { Regex regEx = new Regex(@"A=(?<AV>\d{1,3}),\s*R=(?<RV>\d{1,3}),\s*G=(?<GV>\d{1,3}),\s*B=(?<BV>\d{1,3})"); Match match = regEx.Match(value); if (match.Success) return Color.FromArgb(Convert.ToInt32(match.Groups["AV"].Value), Convert.ToInt32(match.Groups["RV"].Value), Convert.ToInt32(match.Groups["GV"].Value), Convert.ToInt32(match.Groups["BV"].Value)); else { regEx = new Regex(@"\[(?<NAME>\w+)\]"); match = regEx.Match(value); if (match.Success) return Color.FromName(match.Groups["NAME"].Value); else return Color.Empty; } } else if (type == typeof(DateTime)) { if (value.Length == 0) { return DateTime.MinValue; } else { return DateTime.Parse(value); } } else if (type == typeof(TimeSpan)) { return TimeSpan.Parse(value); } else if (type == typeof(Int16)) { return Convert.ToInt16(value); } else if (type == typeof(Int32)) { return Convert.ToInt32(value); } else if (type == typeof(Int64)) { return Convert.ToInt64(value); } else if (type == typeof(float)) { return Convert.ToSingle(value); } else if (type == typeof(double)) { return Convert.ToDouble(value); } else if (type == typeof(decimal)) { return Convert.ToDecimal(value); } else if (type == typeof(char)) { return Convert.ToChar(value); } else if (type == typeof(byte)) { return Convert.ToByte(value); } else if (type == typeof(UInt16)) { return Convert.ToUInt16(value); } else if (type == typeof(UInt32)) { return Convert.ToUInt32(value); } else if (type == typeof(UInt64)) { return Convert.ToUInt64(value); } else if (type == typeof(Guid)) { return new Guid(value); } else { return GetFromInvariantString(type, value); } } /// <summary> /// Gets the object from the invariant string. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-13</remarks> private object GetFromInvariantString(Type type, string value) { TypeConverter converter = TypeDescriptor.GetConverter(type); return converter.ConvertFromInvariantString(value); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"></see> stream to which the object is serialized.</param> /// <remarks>Documented by Dev05, 2007-08-08</remarks> public void WriteXml(XmlWriter writer) { bool keyIsAtomic = false; XmlSerializer keySerializer = null; if (TypeIsAtomic(typeof(TKey))) keyIsAtomic = true; else keySerializer = new XmlSerializer(typeof(TKey)); bool valueIsAtomic = false; XmlSerializer valueSerializer = null; if (TypeIsAtomic(typeof(TValue))) valueIsAtomic = true; else valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); if (keyIsAtomic) //Shorter version, but works only for simple types (int, string, enum, Color, Font, ...) writer.WriteAttributeString("key", GetString(typeof(TKey), key)); else { if (!valueIsAtomic) writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); if (!valueIsAtomic) writer.WriteEndElement(); } if (valueIsAtomic) //Shorter version, but works only for simple types (int, string, enum, Color, Font, ...) writer.WriteAttributeString("value", GetString(typeof(TValue), this[key])); else { if (!keyIsAtomic) writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); if (!keyIsAtomic) writer.WriteEndElement(); } writer.WriteEndElement(); } } /// <summary> /// Gets the string representing the given object. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-13</remarks> private string GetString(Type type, object value) { if (type == typeof(string)) { return (string)value; } else if (type == typeof(bool) || type.IsEnum || type == typeof(Color) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(char) || type == typeof(byte) || type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64) || type == typeof(Guid)) { return value.ToString(); } else { return GetInvariantString(type, value); } } /// <summary> /// Gets the invariant string of the object. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2007-08-13</remarks> private string GetInvariantString(Type type, object value) { TypeConverter converter = TypeDescriptor.GetConverter(type); return converter.ConvertToInvariantString(value); } /// <summary> /// Works out which types to treat as attibutes and which the treat as child objects. /// </summary> /// <param name="type">The Type to check.</param> /// <returns>true if the Type is atomic (e.g. string, date, enum or number), false if it is arrayList compound sub-object.</returns> /// <exception cref="ArgumentNullException">Thrown if <i>type</i> is null (Nothing in Visual Basic).</exception> public static bool TypeIsAtomic(Type type) { if (type == typeof(string) || TypeIsNumeric(type) || type == typeof(bool) || type == typeof(DateTime) || type == typeof(TimeSpan) || type == typeof(char) || type == typeof(byte) || type.IsSubclassOf(typeof(Enum)) || type == typeof(Guid) || type == typeof(Color) || type == typeof(Font)) { return true; } return false; } /// <summary> /// Returns true if the specified type is one of the numeric types /// (Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal) /// </summary> /// <param name="type">The Type to check.</param> /// <returns> /// true if the specified type is one of the numeric types /// (Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal) /// </returns> public static bool TypeIsNumeric(Type type) { if (type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64) || type == typeof(float) || type == typeof(double) || type == typeof(decimal) || type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64)) { return true; } return false; } } }
// ReSharper disable RedundantNameQualifier namespace Gu.Wpf.UiAutomation { using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Gu.Wpf.UiAutomation.Internals; using Color = System.Drawing.Color; public class ImageDiffWindow : System.Windows.Window { private static readonly SolidColorBrush[] Backgrounds = new[] { System.Windows.Media.Brushes.Gray, System.Windows.Media.Brushes.White, System.Windows.Media.Brushes.Black, System.Windows.Media.Brushes.LightGreen, }; private ImageDiffWindow(Bitmap? expected, Bitmap actual) { AutomationProperties.SetAutomationId(this, "Gu.Wpf.UiAutomationOverlayWindow"); AutomationProperties.SetName(this, "Gu.Wpf.UiAutomationOverlayWindow"); this.SizeToContent = SizeToContent.WidthAndHeight; this.WindowStyle = WindowStyle.SingleBorderWindow; this.Topmost = true; this.ShowActivated = false; this.Title = "Image diff"; this.Background = System.Windows.Media.Brushes.Gray; if (expected is null) { this.Padding = new Thickness(10); this.Content = CreateImage(actual, null); this.KeyDown += (_, e) => { switch (e.Key) { case System.Windows.Input.Key.Up: this.Background = NextBackground(1); break; case System.Windows.Input.Key.Down: this.Background = NextBackground(-1); break; } }; this.ToolTip = new System.Windows.Controls.ToolTip { Content = new System.Windows.Controls.TextBlock { Text = "Up and down to change background.", }, }; } else { this.Content = new Grid { RowDefinitions = { new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = GridLength.Auto }, }, Children = { new Grid { Margin = new Thickness(10), Background = System.Windows.Media.Brushes.Transparent, Children = { CreateImage(expected, nameof(ImageDiffViewModel.ExpectedVisibility)), CreateImage(actual, nameof(ImageDiffViewModel.ActualVisibility)), CreateImage(Diff(expected, actual), nameof(ImageDiffViewModel.DiffVisibility)), }, }, CreateButtonGrid(), }, }; var viewModel = new ImageDiffViewModel(); this.DataContext = viewModel; this.KeyDown += (_, e) => { switch (e.Key) { case System.Windows.Input.Key.Left: if (viewModel.Expected) { viewModel.Diff = true; } else if (viewModel.Actual) { viewModel.Expected = true; } else if (viewModel.Both) { viewModel.Actual = true; } else if (viewModel.Diff) { viewModel.Both = true; } break; case System.Windows.Input.Key.Right: if (viewModel.Expected) { viewModel.Actual = true; } else if (viewModel.Actual) { viewModel.Both = true; } else if (viewModel.Both) { viewModel.Diff = true; } else if (viewModel.Diff) { viewModel.Expected = true; } break; case System.Windows.Input.Key.Up: this.Background = NextBackground(1); break; case System.Windows.Input.Key.Down: this.Background = NextBackground(-1); break; } }; this.ToolTip = new System.Windows.Controls.ToolTip { Content = new System.Windows.Controls.TextBlock { Text = "Use left and right arrows to change image. Up and down to change background.", }, }; } SolidColorBrush NextBackground(int increment) { var index = Array.IndexOf(Backgrounds, this.Background) + increment; if (index >= Backgrounds.Length) { index = 0; } if (index < 0) { index = Backgrounds.Length - 1; } return Backgrounds[index]; } } public static void Show(Bitmap? expected, Bitmap actual) { if (actual is null) { throw new System.ArgumentNullException(nameof(actual)); } var dispatcher = WpfDispatcher.Create(); dispatcher!.Invoke(() => { var window = new ImageDiffWindow(expected, actual); _ = window.ShowDialog(); }); dispatcher.InvokeShutdown(); _ = dispatcher.Thread.Join(1000); } private static System.Windows.Controls.Image CreateImage(Bitmap bitmap, string? visibilityPropertyName) { var image = new System.Windows.Controls.Image { Source = CreateBitmapSource(bitmap), Height = bitmap.Height, Width = bitmap.Width, InputBindings = { new MouseBinding( ApplicationCommands.Save, new MouseGesture(MouseAction.LeftDoubleClick)), }, ContextMenu = new System.Windows.Controls.ContextMenu { Items = { new System.Windows.Controls.MenuItem { Header = "Save", Command = ApplicationCommands.Save, CommandBindings = { SaveBinding(), }, }, }, }, CommandBindings = { SaveBinding(), }, }; if (visibilityPropertyName is { }) { _ = BindingOperations.SetBinding( image, System.Windows.Controls.Image.VisibilityProperty, new Binding { Path = new PropertyPath(visibilityPropertyName), Mode = BindingMode.OneWay, }); _ = BindingOperations.SetBinding( image, System.Windows.Controls.Image.OpacityProperty, new Binding { Path = new PropertyPath(nameof(ImageDiffViewModel.Opacity)), Mode = BindingMode.OneWay, }); } Grid.SetRow(image, 0); return image; CommandBinding SaveBinding() { return new CommandBinding( ApplicationCommands.Save, (sender, args) => { var dialog = new Microsoft.Win32.SaveFileDialog(); if (dialog.ShowDialog() == true) { bitmap.Save(dialog.FileName); } }); } } private static UniformGrid CreateButtonGrid() { var grid = new UniformGrid { Rows = 1, Background = System.Windows.Media.Brushes.White, Children = { CreateButton(nameof(ImageDiffViewModel.Expected)), CreateButton(nameof(ImageDiffViewModel.Actual)), CreateButton(nameof(ImageDiffViewModel.Both)), CreateButton(nameof(ImageDiffViewModel.Diff)), }, }; Grid.SetRow(grid, 1); return grid; static System.Windows.Controls.RadioButton CreateButton(string content) { var button = new System.Windows.Controls.RadioButton { Content = content, }; _ = BindingOperations.SetBinding( button, System.Windows.Controls.Primitives.ToggleButton.IsCheckedProperty, new Binding { Path = new PropertyPath(content), Mode = BindingMode.TwoWay, }); return button; } } private static BitmapSource CreateBitmapSource(Bitmap bitmap) { using var memory = new MemoryStream(); bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png); memory.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); return bitmapImage; } private static Bitmap Diff(Bitmap expected, Bitmap actual) { var diff = new Bitmap(Math.Min(expected.Width, actual.Width), Math.Min(expected.Height, actual.Height)); for (var x = 0; x < diff.Size.Width; x++) { for (var y = 0; y < diff.Size.Height; y++) { var ep = expected.GetPixel(x, y); var ap = actual.GetPixel(x, y); var color = ep.A != ap.A ? System.Drawing.Color.HotPink : System.Drawing.Color.FromArgb( Diff(x => x.R), Diff(x => x.G), Diff(x => x.B)); diff.SetPixel(x, y, color); int Diff(Func<Color, byte> func) { return Math.Abs(func(ep) - func(ap)); } } } return diff; } #pragma warning disable CA1034 // Nested types should not be visible public class ImageDiffViewModel : INotifyPropertyChanged #pragma warning restore CA1034 // Nested types should not be visible { private bool expected; private bool actual; private bool both = true; private bool diff; public event PropertyChangedEventHandler? PropertyChanged; public bool Expected { get => this.expected; set { if (value == this.expected) { return; } this.expected = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.ExpectedVisibility)); } } public bool Actual { get => this.actual; set { if (value == this.actual) { return; } this.actual = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.ActualVisibility)); } } public bool Both { get => this.both; set { if (value == this.both) { return; } this.both = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.Opacity)); this.OnPropertyChanged(nameof(this.ActualVisibility)); this.OnPropertyChanged(nameof(this.ExpectedVisibility)); } } public bool Diff { get => this.diff; set { if (value == this.diff) { return; } this.diff = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.DiffVisibility)); } } public Visibility ExpectedVisibility => this.expected || this.both ? Visibility.Visible : Visibility.Hidden; public Visibility ActualVisibility => this.actual || this.both ? Visibility.Visible : Visibility.Hidden; public Visibility DiffVisibility => this.diff ? Visibility.Visible : Visibility.Hidden; public double Opacity => this.Both ? 0.5 : 1; protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } }
// ---------------------------------------------------------------------------- // <copyright file="ServerSettingsInspector.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2016 Exit Games GmbH // </copyright> // <summary> // This is a custom editor for the ServerSettings scriptable object. // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- using System; using ExitGames.Client.Photon; using UnityEditor; using UnityEngine; [CustomEditor(typeof (ServerSettings))] public class ServerSettingsInspector : Editor { public enum ProtocolChoices { Udp = ConnectionProtocol.Udp, Tcp = ConnectionProtocol.Tcp } // has to be extended when rHTTP becomes available private bool showMustHaveRegion; private bool showAppIdHint; public override void OnInspectorGUI() { ServerSettings settings = (ServerSettings) target; Undo.RecordObject(settings, "Edit PhotonServerSettings"); settings.HostType = (ServerSettings.HostingOption) EditorGUILayout.EnumPopup("Hosting", settings.HostType); EditorGUI.indentLevel = 1; switch (settings.HostType) { case ServerSettings.HostingOption.BestRegion: case ServerSettings.HostingOption.PhotonCloud: // region selection if (settings.HostType == ServerSettings.HostingOption.PhotonCloud) { settings.PreferredRegion = (CloudRegionCode)EditorGUILayout.EnumPopup("Region", settings.PreferredRegion); } else { CloudRegionFlag valRegions = (CloudRegionFlag)EditorGUILayout.EnumMaskField("Enabled Regions", settings.EnabledRegions); if (valRegions != settings.EnabledRegions) { settings.EnabledRegions = valRegions; this.showMustHaveRegion = valRegions == 0; } if (this.showMustHaveRegion) { EditorGUILayout.HelpBox("You should enable at least two regions for 'Best Region' hosting.", MessageType.Warning); } } // appid string valAppId = EditorGUILayout.TextField("AppId", settings.AppID); if (valAppId != settings.AppID) { settings.AppID = valAppId; this.showAppIdHint = !IsAppId(settings.AppID); } if (this.showAppIdHint) { EditorGUILayout.HelpBox("The Photon Cloud needs an AppId (GUID) set.\nYou can find it online in your Dashboard.", MessageType.Warning); } // protocol ProtocolChoices valProtocol = settings.Protocol == ConnectionProtocol.Tcp ? ProtocolChoices.Tcp : ProtocolChoices.Udp; valProtocol = (ProtocolChoices) EditorGUILayout.EnumPopup("Protocol", valProtocol); settings.Protocol = (ConnectionProtocol) valProtocol; #if UNITY_WEBGL EditorGUILayout.HelpBox("WebGL always use Secure WebSockets as protocol.\nThis setting gets ignored in current export.", MessageType.Warning); #endif break; case ServerSettings.HostingOption.SelfHosted: // address and port (depends on protocol below) bool hidePort = false; if (settings.Protocol == ConnectionProtocol.Udp && (settings.ServerPort == 4530 || settings.ServerPort == 0)) { settings.ServerPort = 5055; } else if (settings.Protocol == ConnectionProtocol.Tcp && (settings.ServerPort == 5055 || settings.ServerPort == 0)) { settings.ServerPort = 4530; } #if RHTTP if (settings.Protocol == ConnectionProtocol.RHttp) { settings.ServerPort = 0; hidePort = true; } #endif settings.ServerAddress = EditorGUILayout.TextField("Server Address", settings.ServerAddress); settings.ServerAddress = settings.ServerAddress.Trim(); if (!hidePort) { settings.ServerPort = EditorGUILayout.IntField("Server Port", settings.ServerPort); } // protocol valProtocol = settings.Protocol == ConnectionProtocol.Tcp ? ProtocolChoices.Tcp : ProtocolChoices.Udp; valProtocol = (ProtocolChoices) EditorGUILayout.EnumPopup("Protocol", valProtocol); settings.Protocol = (ConnectionProtocol) valProtocol; #if UNITY_WEBGL EditorGUILayout.HelpBox("WebGL always use Secure WebSockets as protocol.\nThis setting gets ignored in current export.", MessageType.Warning); #endif // appid settings.AppID = EditorGUILayout.TextField("AppId", settings.AppID); break; case ServerSettings.HostingOption.OfflineMode: EditorGUI.indentLevel = 0; EditorGUILayout.HelpBox("In 'Offline Mode', the client does not communicate with a server.\nAll settings are hidden currently.", MessageType.Info); break; case ServerSettings.HostingOption.NotSet: EditorGUI.indentLevel = 0; EditorGUILayout.HelpBox("Hosting is 'Not Set'.\nConnectUsingSettings() will not be able to connect.\nSelect another option or run the PUN Wizard.", MessageType.Info); break; default: DrawDefaultInspector(); break; } EditorGUI.indentLevel = 0; EditorGUILayout.LabelField("Client Settings"); EditorGUI.indentLevel = 1; //EditorGUILayout.LabelField("game version"); settings.JoinLobby = EditorGUILayout.Toggle("Auto-Join Lobby", settings.JoinLobby); settings.EnableLobbyStatistics = EditorGUILayout.Toggle("Enable Lobby Stats", settings.EnableLobbyStatistics); //EditorGUILayout.LabelField("automaticallySyncScene"); //EditorGUILayout.LabelField("autoCleanUpPlayerObjects"); //EditorGUILayout.LabelField("log level"); //EditorGUILayout.LabelField("lobby stats"); //EditorGUILayout.LabelField("sendrate / serialize rate"); //EditorGUILayout.LabelField("quick resends"); //EditorGUILayout.LabelField("max resends"); //EditorGUILayout.LabelField("enable crc checking"); if (PhotonEditor.CheckPunPlus()) { settings.Protocol = ConnectionProtocol.Udp; EditorGUILayout.HelpBox("You seem to use PUN+.\nPUN+ only supports reliable UDP so the protocol is locked.", MessageType.Info); } settings.AppID = settings.AppID.Trim(); // RPC-shortcut list EditorGUI.indentLevel = 0; SerializedObject sObj = new SerializedObject(target); SerializedProperty sRpcs = sObj.FindProperty("RpcList"); EditorGUILayout.PropertyField(sRpcs, true); sObj.ApplyModifiedProperties(); GUILayout.BeginHorizontal(); GUILayout.Space(20); if (GUILayout.Button("Refresh RPCs")) { PhotonEditor.UpdateRpcList(); Repaint(); } if (GUILayout.Button("Clear RPCs")) { PhotonEditor.ClearRpcList(); } if (GUILayout.Button("Log HashCode")) { Debug.Log("RPC-List HashCode: " + RpcListHashCode() + ". Make sure clients that send each other RPCs have the same RPC-List."); } GUILayout.Space(20); GUILayout.EndHorizontal(); //SerializedProperty sp = serializedObject.FindProperty("RpcList"); //EditorGUILayout.PropertyField(sp, true); if (GUI.changed) { EditorUtility.SetDirty(target); // even in Unity 5.3+ it's OK to SetDirty() for non-scene objects. } } private int RpcListHashCode() { // this is a hashcode generated to (more) easily compare this Editor's RPC List with some other int hashCode = PhotonNetwork.PhotonServerSettings.RpcList.Count + 1; foreach (string s in PhotonNetwork.PhotonServerSettings.RpcList) { int h1 = s.GetHashCode(); hashCode = ((h1 << 5) + h1) ^ hashCode; } return hashCode; } /// <summary>Checks if a string is a Guid by attempting to create one.</summary> /// <param name="val">The potential guid to check.</param> /// <returns>True if new Guid(val) did not fail.</returns> public static bool IsAppId(string val) { try { new Guid(val); } catch { return false; } return true; } }
using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using Ocelot.Administration; using Ocelot.Cache; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using TestStack.BDDfy; using Xunit; namespace Ocelot.IntegrationTests { public class AdministrationTests : IDisposable { private HttpClient _httpClient; private readonly HttpClient _httpClientTwo; private HttpResponseMessage _response; private IHost _builder; private IHostBuilder _webHostBuilder; private string _ocelotBaseUrl; private BearerToken _token; private IHostBuilder _webHostBuilderTwo; private IHost _builderTwo; private IHost _identityServerBuilder; private IHost _fooServiceBuilder; private IHost _barServiceBuilder; public AdministrationTests() { _httpClient = new HttpClient(); _httpClientTwo = new HttpClient(); _ocelotBaseUrl = "http://localhost:5000"; _httpClient.BaseAddress = new Uri(_ocelotBaseUrl); } [Fact] public void should_return_response_401_with_call_re_routes_controller() { var configuration = new FileConfiguration(); this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenOcelotIsRunning()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)) .BDDfy(); } [Fact] public void should_return_response_200_with_call_re_routes_controller() { var configuration = new FileConfiguration(); this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenOcelotIsRunning()) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void should_return_response_200_with_call_re_routes_controller_using_base_url_added_in_file_config() { _httpClient = new HttpClient(); _ocelotBaseUrl = "http://localhost:5011"; _httpClient.BaseAddress = new Uri(_ocelotBaseUrl); var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { BaseUrl = _ocelotBaseUrl } }; this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenOcelotIsRunningWithNoWebHostBuilder(_ocelotBaseUrl)) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void should_be_able_to_use_token_from_ocelot_a_on_ocelot_b() { var configuration = new FileConfiguration(); this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenIdentityServerSigningEnvironmentalVariablesAreSet()) .And(x => GivenOcelotIsRunning()) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenAnotherOcelotIsRunning("http://localhost:5017")) .When(x => WhenIGetUrlOnTheSecondOcelot("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void should_return_file_configuration() { var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { RequestIdKey = "RequestId", ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "127.0.0.1", } }, ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/", FileCacheOptions = new FileCacheOptions { TtlSeconds = 10, Region = "Geoff" } }, new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/test", FileCacheOptions = new FileCacheOptions { TtlSeconds = 10, Region = "Dave" } } } }; this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenOcelotIsRunning()) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => ThenTheResponseShouldBe(configuration)) .BDDfy(); } [Fact] public void should_get_file_configuration_edit_and_post_updated_version() { var initialConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { }, ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/" }, new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/test" } }, }; var updatedConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { }, ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "http", DownstreamPathTemplate = "/geoffrey", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/" }, new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "123.123.123", Port = 443, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/blooper/{productId}", UpstreamHttpMethod = new List<string> { "post" }, UpstreamPathTemplate = "/test" } } }; this.Given(x => GivenThereIsAConfiguration(initialConfiguration)) .And(x => GivenOcelotIsRunning()) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .When(x => WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration)) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => ThenTheResponseShouldBe(updatedConfiguration)) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .And(x => ThenTheResponseShouldBe(updatedConfiguration)) .And(_ => ThenTheConfigurationIsSavedCorrectly(updatedConfiguration)) .BDDfy(); } private void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expected) { var ocelotJsonPath = $"{AppContext.BaseDirectory}ocelot.json"; var resultText = File.ReadAllText(ocelotJsonPath); var expectedText = JsonConvert.SerializeObject(expected, Formatting.Indented); resultText.ShouldBe(expectedText); var environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot.Production.json"; resultText = File.ReadAllText(environmentSpecificPath); expectedText = JsonConvert.SerializeObject(expected, Formatting.Indented); resultText.ShouldBe(expectedText); } [Fact] public void should_get_file_configuration_edit_and_post_updated_version_redirecting_reroute() { var fooPort = 47689; var barPort = 47690; var initialConfiguration = new FileConfiguration { ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = fooPort, } }, DownstreamScheme = "http", DownstreamPathTemplate = "/foo", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/foo" } } }; var updatedConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { }, ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = barPort, } }, DownstreamScheme = "http", DownstreamPathTemplate = "/bar", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/foo" } } }; this.Given(x => GivenThereIsAConfiguration(initialConfiguration)) .And(x => GivenThereIsAFooServiceRunningOn($"http://localhost:{fooPort}")) .And(x => GivenThereIsABarServiceRunningOn($"http://localhost:{barPort}")) .And(x => GivenOcelotIsRunning()) .And(x => WhenIGetUrlOnTheApiGateway("/foo")) .Then(x => ThenTheResponseBodyShouldBe("foo")) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration)) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => ThenTheResponseShouldBe(updatedConfiguration)) .And(x => WhenIGetUrlOnTheApiGateway("/foo")) .Then(x => ThenTheResponseBodyShouldBe("bar")) .When(x => WhenIPostOnTheApiGateway("/administration/configuration", initialConfiguration)) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => ThenTheResponseShouldBe(initialConfiguration)) .And(x => WhenIGetUrlOnTheApiGateway("/foo")) .Then(x => ThenTheResponseBodyShouldBe("foo")) .BDDfy(); } [Fact] public void should_clear_region() { var initialConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { }, ReRoutes = new List<FileReRoute>() { new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/", FileCacheOptions = new FileCacheOptions { TtlSeconds = 10 } }, new FileReRoute() { DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 80, } }, DownstreamScheme = "https", DownstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "get" }, UpstreamPathTemplate = "/test", FileCacheOptions = new FileCacheOptions { TtlSeconds = 10 } } } }; var regionToClear = "gettest"; this.Given(x => GivenThereIsAConfiguration(initialConfiguration)) .And(x => GivenOcelotIsRunning()) .And(x => GivenIHaveAnOcelotToken("/administration")) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.NoContent)) .BDDfy(); } [Fact] public void should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area() { var configuration = new FileConfiguration(); var identityServerRootUrl = "http://localhost:5123"; Action<IdentityServerAuthenticationOptions> options = o => { o.Authority = identityServerRootUrl; o.ApiName = "api"; o.RequireHttpsMetadata = false; o.SupportedTokens = SupportedTokens.Both; o.ApiSecret = "secret"; }; this.Given(x => GivenThereIsAConfiguration(configuration)) .And(x => GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api")) .And(x => GivenOcelotIsRunningWithIdentityServerSettings(options)) .And(x => GivenIHaveAToken(identityServerRootUrl)) .And(x => GivenIHaveAddedATokenToMyRequest()) .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } private void GivenIHaveAToken(string url) { var formData = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("client_id", "api"), new KeyValuePair<string, string>("client_secret", "secret"), new KeyValuePair<string, string>("scope", "api"), new KeyValuePair<string, string>("username", "test"), new KeyValuePair<string, string>("password", "test"), new KeyValuePair<string, string>("grant_type", "password") }; var content = new FormUrlEncodedContent(formData); using (var httpClient = new HttpClient()) { var response = httpClient.PostAsync($"{url}/connect/token", content).Result; var responseContent = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); _token = JsonConvert.DeserializeObject<BearerToken>(responseContent); } } private void GivenThereIsAnIdentityServerOn(string url, string apiName) { _identityServerBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureServices(services => { services.AddLogging(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(new List<ApiResource> { new ApiResource { Name = apiName, Description = apiName, Enabled = true, DisplayName = apiName, Scopes = new List<Scope>() { new Scope(apiName), }, }, }) .AddInMemoryClients(new List<Client> { new Client { ClientId = apiName, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, ClientSecrets = new List<Secret> { new Secret("secret".Sha256()) }, AllowedScopes = new List<string> { apiName }, AccessTokenType = AccessTokenType.Jwt, Enabled = true }, }) .AddTestUsers(new List<TestUser> { new TestUser { Username = "test", Password = "test", SubjectId = "1231231" }, }); }) .Configure(app => { app.UseIdentityServer(); } ); }).Build(); _identityServerBuilder.Start(); using (var httpClient = new HttpClient()) { var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result; response.EnsureSuccessStatusCode(); } } private void GivenAnotherOcelotIsRunning(string baseUrl) { _httpClientTwo.BaseAddress = new Uri(baseUrl); _webHostBuilderTwo = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) .ConfigureServices(x => { x.AddMvc(option => option.EnableEndpointRouting = false); x.AddOcelot() .AddAdministration("/administration", "secret"); }) .Configure(app => { app.UseOcelot().Wait(); }); }); _builderTwo = _webHostBuilderTwo.Build(); _builderTwo.Start(); } private void GivenIdentityServerSigningEnvironmentalVariablesAreSet() { Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", "idsrv3test.pfx"); Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "idsrv3test"); } private void WhenIGetUrlOnTheSecondOcelot(string url) { _httpClientTwo.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); _response = _httpClientTwo.GetAsync(url).Result; } private void WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) { var json = JsonConvert.SerializeObject(updatedConfiguration); var content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); _response = _httpClient.PostAsync(url, content).Result; } private void ThenTheResponseShouldBe(List<string> expected) { var content = _response.Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject<Regions>(content); result.Value.ShouldBe(expected); } private void ThenTheResponseBodyShouldBe(string expected) { var content = _response.Content.ReadAsStringAsync().Result; content.ShouldBe(expected); } private void ThenTheResponseShouldBe(FileConfiguration expecteds) { var response = JsonConvert.DeserializeObject<FileConfiguration>(_response.Content.ReadAsStringAsync().Result); response.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey); response.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host); response.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port); for (var i = 0; i < response.ReRoutes.Count; i++) { for (var j = 0; j < response.ReRoutes[i].DownstreamHostAndPorts.Count; j++) { var result = response.ReRoutes[i].DownstreamHostAndPorts[j]; var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j]; result.Host.ShouldBe(expected.Host); result.Port.ShouldBe(expected.Port); } response.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate); response.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme); response.ReRoutes[i].UpstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].UpstreamPathTemplate); response.ReRoutes[i].UpstreamHttpMethod.ShouldBe(expecteds.ReRoutes[i].UpstreamHttpMethod); } } private void GivenIHaveAddedATokenToMyRequest() { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); } private void GivenIHaveAnOcelotToken(string adminPath) { var tokenUrl = $"{adminPath}/connect/token"; var formData = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("client_id", "admin"), new KeyValuePair<string, string>("client_secret", "secret"), new KeyValuePair<string, string>("scope", "admin"), new KeyValuePair<string, string>("grant_type", "client_credentials") }; var content = new FormUrlEncodedContent(formData); var response = _httpClient.PostAsync(tokenUrl, content).Result; var responseContent = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); _token = JsonConvert.DeserializeObject<BearerToken>(responseContent); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = _httpClient.GetAsync(configPath).Result; response.EnsureSuccessStatusCode(); } private void GivenOcelotIsRunningWithIdentityServerSettings(Action<IdentityServerAuthenticationOptions> configOptions) { _webHostBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) .ConfigureServices(x => { x.AddMvc(option => option.EnableEndpointRouting = false); x.AddSingleton(_webHostBuilder); x.AddOcelot() .AddAdministration("/administration", configOptions); }) .Configure(app => { app.UseOcelot().Wait(); }); }); _builder = _webHostBuilder.Build(); _builder.Start(); } private void GivenOcelotIsRunning() { _webHostBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) .ConfigureServices(x => { x.AddMvc(s => s.EnableEndpointRouting = false); x.AddOcelot() .AddAdministration("/administration", "secret"); }) .Configure(app => { app.UseOcelot().Wait(); }); }); _builder = _webHostBuilder.Build(); _builder.Start(); } private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl) { _webHostBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) .ConfigureServices(x => { x.AddMvc(option => option.EnableEndpointRouting = false); x.AddSingleton(_webHostBuilder); x.AddOcelot() .AddAdministration("/administration", "secret"); }) .Configure(app => { app.UseOcelot().Wait(); }); }); _builder = _webHostBuilder.Build(); _builder.Start(); } private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); if (File.Exists(configurationPath)) { File.Delete(configurationPath); } File.WriteAllText(configurationPath, jsonConfiguration); var text = File.ReadAllText(configurationPath); configurationPath = $"{AppContext.BaseDirectory}/ocelot.json"; if (File.Exists(configurationPath)) { File.Delete(configurationPath); } File.WriteAllText(configurationPath, jsonConfiguration); text = File.ReadAllText(configurationPath); } private void WhenIGetUrlOnTheApiGateway(string url) { _response = _httpClient.GetAsync(url).Result; } private void WhenIDeleteOnTheApiGateway(string url) { _response = _httpClient.DeleteAsync(url).Result; } private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) { _response.StatusCode.ShouldBe(expectedHttpStatusCode); } public void Dispose() { Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", ""); Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", ""); _builder?.Dispose(); _httpClient?.Dispose(); _identityServerBuilder?.Dispose(); } private void GivenThereIsAFooServiceRunningOn(string baseUrl) { _fooServiceBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .Configure(app => { app.UsePathBase("/foo"); app.Run(async context => { context.Response.StatusCode = 200; await context.Response.WriteAsync("foo"); }); }); }).Build(); _fooServiceBuilder.Start(); } private void GivenThereIsABarServiceRunningOn(string baseUrl) { _barServiceBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(baseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .Configure(app => { app.UsePathBase("/bar"); app.Run(async context => { context.Response.StatusCode = 200; await context.Response.WriteAsync("bar"); }); }); }).Build(); _barServiceBuilder.Start(); } } }
// // Copyright 2012-2016, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Android.OS; using Android.App; using Android.Widget; using Android.Support.CustomTabs; using Xamarin.Utilities.Android; using Plugin.Threading; #if ! AZURE_MOBILE_SERVICES namespace Xamarin.Auth #else namespace Xamarin.Auth._MobileServices #endif { [Activity ( Label = "Web Authenticator Native Browser", // NoHistory = true, LaunchMode = global::Android.Content.PM.LaunchMode.SingleTop ) ] #if XAMARIN_AUTH_INTERNAL internal partial class WebAuthenticatorNativeBrowserActivity : global::Android.Accounts.AccountAuthenticatorActivity #else public partial class WebAuthenticatorNativeBrowserActivity : global::Android.Accounts.AccountAuthenticatorActivity #endif { internal class State : Java.Lang.Object { public WebAuthenticator Authenticator; } internal static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State>(); State state; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); //-------------------------------------------------------------- // Azure Mobile Services Team uses simplified code // this is for testing purposes of their launch only LaunchCunstomTabsWithUrl = //LaunchCunstomTabsWithUrlDefault LaunchCunstomTabsWithUrlAzureMobileServiceClientTeamCode ; //-------------------------------------------------------------- // // Load the state either from a configuration change or from the intent. // // * state = LastNonConfigurationInstance as State; if (state == null && Intent.HasExtra("StateKey")) { var stateKey = Intent.GetStringExtra("StateKey"); state = StateRepo.Remove(stateKey); } if (state == null) { Finish(); return; } //Title = state.Authenticator.Title; // // Watch for completion // state.Authenticator.Completed += (s, e) => { SetResult(e.IsAuthenticated ? Result.Ok : Result.Canceled); #region ///------------------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// Added IsAuthenticated check #88 /// https://github.com/xamarin/Xamarin.Auth/pull/88 if (e.IsAuthenticated) { if (state.Authenticator.GetAccountResult != null) { var accountResult = state.Authenticator.GetAccountResult(e.Account); Bundle result = new Bundle(); result.PutString(global::Android.Accounts.AccountManager.KeyAccountType, accountResult.AccountType); result.PutString(global::Android.Accounts.AccountManager.KeyAccountName, accountResult.Name); result.PutString(global::Android.Accounts.AccountManager.KeyAuthtoken, accountResult.Token); result.PutString(global::Android.Accounts.AccountManager.KeyAccountAuthenticatorResponse, e.Account.Serialize()); SetAccountAuthenticatorResult(result); } } ///------------------------------------------------------------------------------------------------- #endregion CloseCustomTabs(); }; state.Authenticator.Error += (s, e) => { if (!state.Authenticator.ShowErrors) return; if (e.Exception != null) { this.ShowError("Authentication Error e.Exception = ", e.Exception); } else { this.ShowError("Authentication Error e.Message = ", e.Message); } BeginLoadingInitialUrl(); }; // Build the UI CustomTabsConfiguration.Initialize(this); CustomTabsConfiguration.UICustomization(); LaunchCunstomTabsWithUrl(); return; } public Action LaunchCunstomTabsWithUrl { get; set; } private void LaunchCunstomTabsWithUrlAzureMobileServiceClientTeamCode() { CustomTabsConfiguration .CustomTabActivityHelper .LaunchUrlWithCustomTabsOrFallback ( // Activity/Context this, // CustomTabIntent CustomTabsConfiguration.CustomTabsIntent, CustomTabsConfiguration.PackageForCustomTabs, CustomTabsConfiguration.UriAndroidOS, // Fallback if CustomTabs do not exist CustomTabsConfiguration.WebViewFallback ); return; } public void LaunchCunstomTabsWithUrlDefault() { //....................................................... // Launching CustomTabs and url - minimal if ( CustomTabsConfiguration.CustomTabActivityHelper != null && CustomTabsConfiguration.CustomTabsIntent != null && CustomTabsConfiguration.UriAndroidOS != null ) { CustomTabsConfiguration .CustomTabsIntent .Intent.AddFlags(CustomTabsConfiguration.ActivityFlags); CustomTabsConfiguration .CustomTabActivityHelper .LaunchUrlWithCustomTabsOrFallback ( // Activity/Context this, // CustomTabInten CustomTabsConfiguration.CustomTabsIntent, CustomTabsConfiguration.PackageForCustomTabs, CustomTabsConfiguration.UriAndroidOS, // Fallback if CustomTabs do not exis CustomTabsConfiguration.WebViewFallback ); } else { // plain CustomTabs no customizations CustomTabsIntent i = new CustomTabsIntent.Builder().Build(); i.Intent.AddFlags(CustomTabsConfiguration.ActivityFlags); i.LaunchUrl(this, CustomTabsConfiguration.UriAndroidOS); } //....................................................... // Launching CustomTabs and url - if WarmUp and Prefetching is used /* */ //--------------------------------------------------------------------------------- // // Restore the UI state or start over // /* if (savedInstanceState != null) { //webView.RestoreState(savedInstanceState); } else { if (Intent.GetBooleanExtra("ClearCookies", true)) { WebAuthenticator.ClearCookies(); } BeginLoadingInitialUrl(); } */ return; } private bool customTabsShown = false; protected override void OnPause() { base.OnPause(); customTabsShown = true; return; } #region ///------------------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// Added IsAuthenticated check #88 /// https://github.com/xamarin/Xamarin.Auth/pull/88 protected override void OnResume() { base.OnResume(); if ( state.Authenticator.AllowCancel && // mc++ state.Authenticator.IsAuthenticated() // Azure Mobile Services Client fix customTabsShown // Azure Mobile Services Client fix ) { state.Authenticator.OnCancelled(); } customTabsShown = false; return; } ///------------------------------------------------------------------------------------------------- #endregion protected void CloseCustomTabs() { UIThreadRunInvoker ri = new UIThreadRunInvoker(this); ri.BeginInvokeOnUIThread ( () => { string msg = CustomTabsConfiguration.CustomTabsClosingMessage; if (msg != null) { Toast.MakeText(this, msg, ToastLength.Short).Show(); } } ); #if DEBUG System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine($" CloseCustomTabs"); System.Diagnostics.Debug.WriteLine(sb.ToString()); #endif this.Finish(); //this.CloseCustomTabsProcessKill(); return; } protected void CloseCustomTabsProcessKill() { System.Diagnostics.Debug.WriteLine($" CloseCustomTabs"); ; ActivityManager manager = GetSystemService(global::Android.Content.Context.ActivityService) as ActivityManager; List<ActivityManager.RunningAppProcessInfo> processes = manager.RunningAppProcesses.ToList(); //List<ActivityManager.RunningTaskInfo> tasks = (manager.Get().ToList(); foreach (ActivityManager.RunningAppProcessInfo process in processes) { String name = process.ProcessName; System.Diagnostics.Debug.WriteLine($" process"); System.Diagnostics.Debug.WriteLine($" .Pid = {process.Pid}"); System.Diagnostics.Debug.WriteLine($" .ProcessName = {process.ProcessName}"); if ( name.Contains("com.android.browser") ) { int pid = process.Pid; Process.KillProcess(pid); } } return; } void BeginLoadingInitialUrl() { state.Authenticator.GetInitialUrlAsync().ContinueWith ( t => { if (t.IsFaulted) { if (!state.Authenticator.ShowErrors) return; this.ShowError("Authentication Error t.Exception = ", t.Exception); } else { //TODO: webView.LoadUrl(t.Result.AbsoluteUri); } }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext() ); } public override void OnBackPressed() { if (state.Authenticator.AllowCancel) { state.Authenticator.OnCancelled(); } this.Finish(); return; } public override Java.Lang.Object OnRetainNonConfigurationInstance() { return state; } protected override void OnSaveInstanceState(Bundle outState) { base.OnSaveInstanceState(outState); // TODO: webView.SaveState(outState); } void BeginProgress(string message) { // TODO: webView.Enabled = false; } void EndProgress() { // TODO: webView.Enabled = true; } } }
// 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; using Xunit; namespace Microsoft.VisualBasic.Tests { public static class CollectionsTests { [Fact] public static void Ctor_Empty() { var coll = new Collection(); Assert.Equal(0, coll.Count); } private static Foo CreateValue(int i) => new Foo(i, i.ToString()); private static Collection CreateCollection(int count) { var coll = new Collection(); for (int i = 0; i < 10; i++) { coll.Add(CreateValue(i)); } return coll; } private static Collection CreateKeyedCollection(int count) { var coll = new Collection(); for (int i = 0; i < 10; i++) { coll.Add(CreateValue(i), Key: "Key" + i.ToString()); } return coll; } [Fact] public static void Add() { IList coll = new Collection(); for (int i = 0; i < 10; i++) { Foo value = CreateValue(i); coll.Add(value); Assert.True(coll.Contains(value)); } Assert.Equal(10, coll.Count); for (int i = 0; i < coll.Count; i++) { Foo value = CreateValue(i); Assert.Equal(value, coll[i]); } } [Fact] public static void Add_RelativeIndex() { var coll = new Collection(); var item1 = CreateValue(1); var item2 = CreateValue(2); var item3 = CreateValue(3); coll.Add(item1); coll.Add(item2, Before: 1); coll.Add(item3, After: 1); Assert.Equal(item2, coll[1]); Assert.Equal(item3, coll[2]); Assert.Equal(item1, coll[3]); } [Fact] public static void Add_RelativeKey() { var coll = new Collection(); var item1 = CreateValue(1); var item2 = CreateValue(2); var item3 = CreateValue(3); coll.Add(item1, "Key1"); coll.Add(item2, Key: "Key2", Before: "Key1"); coll.Add(item3, After: "Key2"); Assert.Equal(item2, coll[1]); Assert.Equal(item3, coll[2]); Assert.Equal(item1, coll[3]); } [Fact] public static void Add_Relative_Invalid() { var coll = new Collection(); var item1 = CreateValue(1); Assert.Throws<ArgumentException>(() => coll.Add(item1, Before: 1, After: 1)); // Before and after specified Assert.Throws<InvalidCastException>(() => coll.Add(item1, Before: new object())); // Before not in a string or int Assert.Throws<InvalidCastException>(() => coll.Add(item1, After: new object())); // After not in a string or int Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll.Add(item1, Before: 5)); // Before not in range Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll.Add(item1, After: 5)); // After not in range Assert.Throws<ArgumentException>(() => coll.Add(item1, Before: "Key5")); // Before not found Assert.Throws<ArgumentException>(() => coll.Add(item1, After: "Key5")); // After not found } [Fact] public static void Remove() { IList coll = CreateCollection(10); for (int i = 0; i < 10; i++) { Foo value = CreateValue(i); coll.Remove(value); Assert.False(coll.Contains(value)); } Assert.Equal(0, coll.Count); coll.Remove(new Foo()); // No throw for non-existent object } [Fact] public static void Insert() { IList coll = new Collection(); for (int i = 0; i < 10; i++) { Foo value = CreateValue(i); coll.Insert(i, value); Assert.True(coll.Contains(value)); } Assert.Equal(10, coll.Count); for (int i = 0; i < coll.Count; i++) { var expected = CreateValue(i); Assert.Equal(expected, coll[i]); } } [Fact] public static void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException() { IList coll = CreateCollection(10); Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll.Insert(-1, new Foo())); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll.Insert(coll.Count + 1, new Foo())); // Index > coll.Count Assert.Equal(10, coll.Count); } [Fact] public static void RemoveAt() { IList coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { coll.RemoveAt(0); Assert.False(coll.Contains(CreateValue(i))); } } [Fact] public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { IList coll = CreateCollection(10); var firstItem = coll[0]; coll.RemoveAt(-10); // Indexing bug when accessing through the IList interface on non-empty collection Assert.False(coll.Contains(firstItem)); Assert.Equal(9, coll.Count); coll = new Collection(); Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll.RemoveAt(-1)); // Index < 0 } [Fact] public static void Remove_Key() { var coll = CreateKeyedCollection(10); Assert.True(coll.Contains("Key3")); coll.Remove("Key3"); Assert.False(coll.Contains("Key3")); } [Fact] public static void Remove_InvalidKey_ThrowsArgumentException() { var coll = CreateKeyedCollection(10); Assert.Throws<ArgumentException>(() => coll.Remove("Key10")); } [Fact] public static void Remove_Index() { Collection coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { coll.Remove(1); Assert.False(((IList)coll).Contains(CreateValue(i))); } } [Fact] public static void Remove_InvalidIndex_ThrowsArgumentException() { var coll = CreateCollection(10); Assert.Throws<IndexOutOfRangeException>(() => coll.Remove(20)); } [Fact] public static void Clear() { Collection coll = CreateCollection(10); coll.Clear(); Assert.Equal(0, coll.Count); } [Fact] public static void IndexOf() { IList coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { int ndx = coll.IndexOf(CreateValue(i)); Assert.Equal(i, ndx); } } [Fact] public static void Contains() { IList coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { Assert.True(coll.Contains(CreateValue(i))); } Assert.False(coll.Contains(new Foo())); } [Fact] public static void Contains_ByKey() { var coll = CreateKeyedCollection(10); Assert.True(coll.Contains("Key3")); Assert.False(coll.Contains("Key10")); } [Fact] public static void Item_Get() { Collection coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { Assert.Equal(CreateValue(i), coll[i + 1]); } Assert.Equal(CreateValue(5), coll[(object)6]); } [Fact] public static void Item_Get_InvalidIndex_ThrowsIndexOutOfRangeException() { Collection coll = CreateCollection(10); Assert.Equal(((IList)coll)[-10], coll[1]); // Indexing bug when accessing through the IList interface on non-empty collection Assert.Throws<IndexOutOfRangeException>(() => coll[0]); // Index <= 0 Assert.Throws<IndexOutOfRangeException>(() => coll[coll.Count + 1]); // Index < 0 Assert.Throws<ArgumentException>(() => coll[(object)Guid.Empty]); // Neither string nor int } [Fact] public static void Item_GetByKey() { Collection coll = CreateKeyedCollection(10); for (int i = 0; i < coll.Count; i++) { Assert.Equal(CreateValue(i), coll["Key" + i.ToString()]); } Assert.Equal(CreateValue(5), coll[(object)"Key5"]); Assert.Equal(CreateValue(5), coll[(object)new char[] { 'K', 'e', 'y', '5' }]); coll.Add(CreateValue(11), "X"); Assert.Equal(CreateValue(11), coll[(object)'X']); } [Fact] public static void Item_GetByKey_InvalidIndex_ThrowsIndexOutOfRangeException() { Collection coll = CreateKeyedCollection(10); Assert.Throws<ArgumentException>(() => coll["Key20"]); Assert.Throws<IndexOutOfRangeException>(() => coll[(string)null]); Assert.Throws<IndexOutOfRangeException>(() => coll[(object)null]); } [Fact] public static void Item_Set() { IList coll = CreateCollection(10); for (int i = 0; i < coll.Count; i++) { var value = CreateValue(coll.Count - i); coll[i] = value; Assert.Equal(value, coll[i]); } } [Fact] public static void Item_Set_Invalid() { IList coll = new Collection(); Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll[-1] = new Foo()); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("Index", () => coll[coll.Count + 1] = new Foo()); // Index >= InnerList.Count } [Fact] public static void CopyTo() { Collection coll = CreateCollection(10); // Basic var fooArr = new Foo[10]; ((ICollection)coll).CopyTo(fooArr, 0); Assert.Equal(coll.Count, fooArr.Length); for (int i = 0; i < fooArr.Length; i++) { Assert.Equal(coll[i + 1], fooArr.GetValue(i)); } // With index fooArr = new Foo[coll.Count * 2]; ((ICollection)coll).CopyTo(fooArr, coll.Count); for (int i = coll.Count; i < fooArr.Length; i++) { Assert.Equal(coll[i - coll.Count + 1], fooArr.GetValue(i)); } } [Fact] public static void CopyTo_Invalid() { ICollection coll = CreateCollection(10); var fooArr = new Foo[10]; // Index < 0 Assert.Throws<ArgumentException>(() => coll.CopyTo(fooArr, -1)); // Index + fooArray.Length > coll.Count Assert.Throws<ArgumentException>(() => coll.CopyTo(fooArr, 5)); } [Fact] public static void GetEnumerator() { Collection coll = CreateCollection(10); IEnumerator enumerator = coll.GetEnumerator(); Assert.NotNull(enumerator); int count = 0; while (enumerator.MoveNext()) { Assert.Equal(coll[count + 1], enumerator.Current); count++; } Assert.Equal(coll.Count, count); } [Fact] public static void GetEnumerator_PrePost() { Collection coll = CreateCollection(10); IEnumerator enumerator = coll.GetEnumerator(); // Index <= 0 Assert.Null(enumerator.Current); // Index >= dictionary.Count while (enumerator.MoveNext()) ; Assert.Null(enumerator.Current); Assert.False(enumerator.MoveNext()); // Current throws after resetting enumerator.Reset(); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Null(enumerator.Current); } [Fact] public static void SyncRoot() { ICollection coll = new Collection(); Assert.Equal(coll.SyncRoot, coll); } [Fact] public static void IListProperties() { IList coll = CreateCollection(10); Assert.False(coll.IsFixedSize); Assert.False(coll.IsReadOnly); Assert.False(coll.IsSynchronized); } private class Foo { public Foo() { } public Foo(int intValue, string stringValue) { IntValue = intValue; StringValue = stringValue; } public int IntValue { get; set; } public string StringValue { get; set; } public override bool Equals(object obj) { Foo foo = obj as Foo; if (foo == null) return false; return foo.IntValue == IntValue && foo.StringValue == StringValue; } public override int GetHashCode() => IntValue; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using Microsoft.API; using System.Runtime.InteropServices; using System.IO; using TAFactory.Utilities; namespace TAFactory.IconPack { #region Enumuration //[Flags] public enum IconFlags : int { Icon = 0x000000100, // get icon LinkOverlay = 0x000008000, // put a link overlay on icon Selected = 0x000010000, // show icon in selected state LargeIcon = 0x000000000, // get large icon SmallIcon = 0x000000001, // get small icon OpenIcon = 0x000000002, // get open icon ShellIconSize = 0x000000004, // get shell size icon } #endregion /// <summary> /// Contains helper function to help dealing with System.Drawing.Icon. /// </summary> public static class IconHelper { #region Public Methods /// <summary> /// Returns TAFactory.IconPack.IconInfo object that holds the information about the icon. /// </summary> /// <param name="icon">System.Drawing.Icon to get the information about.</param> /// <returns>TAFactory.IconPack.IconInfo object that holds the information about the icon.</returns> public static IconInfo GetIconInfo(Icon icon) { return new IconInfo(icon); } /// <summary> /// Returns TAFactory.IconPack.IconInfo object that holds the information about the icon. /// </summary> /// <param name="icon">The icon file path.</param> /// <returns>TAFactory.IconPack.IconInfo object that holds the information about the icon.</returns> public static IconInfo GetIconInfo(string fileName) { return new IconInfo(fileName); } /// <summary> /// Extracts an icon from a givin icon file or an executable module (.dll or an .exe file). /// </summary> /// <param name="fileName">The path of the icon file or the executable module.</param> /// <param name="iconIndex">The index of the icon in the executable module.</param> /// <returns>A System.Drawing.Icon extracted from the file at the specified index in case of an executable module.</returns> public static Icon ExtractIcon(string fileName, int iconIndex) { Icon icon = null; //Try to load the file as icon file. try { icon = new Icon(Environment.ExpandEnvironmentVariables(fileName)); } catch { } if (icon != null) //The file was an icon file, return the icon. return icon; //Load the file as an executable module. using (IconExtractor extractor = new IconExtractor(fileName)) { return extractor.GetIconAt(iconIndex); } } /// <summary> /// Extracts all the icons from a givin icon file or an executable module (.dll or an .exe file). /// </summary> /// <param name="fileName">The path of the icon file or the executable module.</param> /// <returns> /// A list of System.Drawing.Icon found in the file. /// If the file was an icon file, it will return a list containing a single icon. /// </returns> public static List<Icon> ExtractAllIcons(string fileName) { Icon icon = null; List<Icon> list = new List<Icon>(); //Try to load the file as icon file. try { icon = new Icon(Environment.ExpandEnvironmentVariables(fileName)); } catch { } if (icon != null) //The file was an icon file. { list.Add(icon); return list; } //Load the file as an executable module. using (IconExtractor extractor = new IconExtractor(fileName)) { for (int i = 0; i < extractor.IconCount; i++) { list.Add(extractor.GetIconAt(i)); } } return list; } /// <summary> /// Splits the group icon into a list of icons (the single icon file can contain a set of icons). /// </summary> /// <param name="icon">The System.Drawing.Icon need to be splitted.</param> /// <returns>List of System.Drawing.Icon.</returns> public static List<Icon> SplitGroupIcon(Icon icon) { IconInfo info = new IconInfo(icon); return info.Images; } /// <summary> /// Gets the System.Drawing.Icon that best fits the current display device. /// </summary> /// <param name="icon">System.Drawing.Icon to be searched.</param> /// <returns>System.Drawing.Icon that best fit the current display device.</returns> public static Icon GetBestFitIcon(Icon icon) { IconInfo info = new IconInfo(icon); int index = info.GetBestFitIconIndex(); return info.Images[index]; } /// <summary> /// Gets the System.Drawing.Icon that best fits the current display device. /// </summary> /// <param name="icon">System.Drawing.Icon to be searched.</param> /// <param name="desiredSize">Specifies the desired size of the icon.</param> /// <returns>System.Drawing.Icon that best fit the current display device.</returns> public static Icon GetBestFitIcon(Icon icon, Size desiredSize) { IconInfo info = new IconInfo(icon); int index = info.GetBestFitIconIndex(desiredSize); return info.Images[index]; } /// <summary> /// Gets the System.Drawing.Icon that best fits the current display device. /// </summary> /// <param name="icon">System.Drawing.Icon to be searched.</param> /// <param name="desiredSize">Specifies the desired size of the icon.</param> /// <param name="isMonochrome">Specifies whether to get the monochrome icon or the colored one.</param> /// <returns>System.Drawing.Icon that best fit the current display device.</returns> public static Icon GetBestFitIcon(Icon icon, Size desiredSize, bool isMonochrome) { IconInfo info = new IconInfo(icon); int index = info.GetBestFitIconIndex(desiredSize, isMonochrome); return info.Images[index]; } /// <summary> /// Extracts an icon (that best fits the current display device) from a givin icon file or an executable module (.dll or an .exe file). /// </summary> /// <param name="fileName">The path of the icon file or the executable module.</param> /// <param name="iconIndex">The index of the icon in the executable module.</param> /// <returns>A System.Drawing.Icon (that best fits the current display device) extracted from the file at the specified index in case of an executable module.</returns> public static Icon ExtractBestFitIcon(string fileName, int iconIndex) { Icon icon = ExtractIcon(fileName, iconIndex); return GetBestFitIcon(icon); } /// <summary> /// Extracts an icon (that best fits the current display device) from a givin icon file or an executable module (.dll or an .exe file). /// </summary> /// <param name="fileName">The path of the icon file or the executable module.</param> /// <param name="iconIndex">The index of the icon in the executable module.</param> /// <param name="desiredSize">Specifies the desired size of the icon.</param> /// <returns>A System.Drawing.Icon (that best fits the current display device) extracted from the file at the specified index in case of an executable module.</returns> public static Icon ExtractBestFitIcon(string fileName, int iconIndex, Size desiredSize) { Icon icon = ExtractIcon(fileName, iconIndex); return GetBestFitIcon(icon, desiredSize); } /// <summary> /// Extracts an icon (that best fits the current display device) from a givin icon file or an executable module (.dll or an .exe file). /// </summary> /// <param name="fileName">The path of the icon file or the executable module.</param> /// <param name="iconIndex">The index of the icon in the executable module.</param> /// <param name="desiredSize">Specifies the desired size of the icon.</param> /// <param name="isMonochrome">Specifies whether to get the monochrome icon or the colored one.</param> /// <returns>A System.Drawing.Icon (that best fits the current display device) extracted from the file at the specified index in case of an executable module.</returns> public static Icon ExtractBestFitIcon(string fileName, int iconIndex, Size desiredSize, bool isMonochrome) { Icon icon = ExtractIcon(fileName, iconIndex); return GetBestFitIcon(icon, desiredSize, isMonochrome); } /// <summary> /// Gets icon associated with the givin file. /// </summary> /// <param name="fileName">The file path (both absolute and relative paths are valid).</param> /// <param name="flags">Specifies which icon to be retrieved (Larg, Small, Selected, Link Overlay and Shell Size).</param> /// <returns>A System.Drawing.Icon associated with the givin file.</returns> public static Icon GetAssociatedIcon(string fileName, IconFlags flags) { flags |= IconFlags.Icon; SHFILEINFO fileInfo = new SHFILEINFO(); IntPtr result = Win32.SHGetFileInfo(fileName, 0, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), (SHGetFileInfoFlags) flags); if (fileInfo.hIcon == IntPtr.Zero) return null; return Icon.FromHandle(fileInfo.hIcon); } /// <summary> /// Gets large icon associated with the givin file. /// </summary> /// <param name="fileName">The file path (both absolute and relative paths are valid).</param> /// <returns>A System.Drawing.Icon associated with the givin file.</returns> public static Icon GetAssociatedLargeIcon(string fileName) { return GetAssociatedIcon(fileName, IconFlags.LargeIcon); } /// <summary> /// Gets small icon associated with the givin file. /// </summary> /// <param name="fileName">The file path (both absolute and relative paths are valid).</param> /// <returns>A System.Drawing.Icon associated with the givin file.</returns> public static Icon GetAssociatedSmallIcon(string fileName) { return GetAssociatedIcon(fileName, IconFlags.SmallIcon); } /// <summary> /// Merges a list of icons into one single icon. /// </summary> /// <param name="icons">The icons to be merged.</param> /// <returns>System.Drawing.Icon that contains all the images of the givin icons.</returns> public static Icon Merge(params Icon[] icons) { List<IconInfo> list = new List<IconInfo>(icons.Length); int numImages = 0; foreach (Icon icon in icons) { if (icon != null) { IconInfo info = new IconInfo(icon); list.Add(info); numImages += info.Images.Count; } } if (list.Count == 0) { throw new ArgumentNullException("icons", "The icons list should contain at least one icon."); } //Write the icon to a stream. MemoryStream outputStream = new MemoryStream(); int imageIndex = 0; int imageOffset = IconInfo.SizeOfIconDir + numImages * IconInfo.SizeOfIconDirEntry; for (int i = 0; i < list.Count; i++) { IconInfo iconInfo = list[i]; //The firs image, we should write the icon header. if (i == 0) { //Get the IconDir and update image count with the new count. IconDir dir = iconInfo.IconDir; dir.Count = (short)numImages; //Write the IconDir header. outputStream.Seek(0, SeekOrigin.Begin); Utility.WriteStructure<IconDir>(outputStream, dir); } //For each image in the current icon, we should write the IconDirEntry and the image raw data. for (int j = 0; j < iconInfo.Images.Count; j++) { //Get the IconDirEntry and update the ImageOffset to the new offset. IconDirEntry entry = iconInfo.IconDirEntries[j]; entry.ImageOffset = imageOffset; //Write the IconDirEntry to the stream. outputStream.Seek(IconInfo.SizeOfIconDir + imageIndex * IconInfo.SizeOfIconDirEntry, SeekOrigin.Begin); Utility.WriteStructure<IconDirEntry>(outputStream, entry); //Write the image raw data. outputStream.Seek(imageOffset, SeekOrigin.Begin); outputStream.Write(iconInfo.RawData[j], 0, entry.BytesInRes); //Update the imageIndex and the imageOffset imageIndex++; imageOffset += entry.BytesInRes; } } //Create the icon from the stream. outputStream.Seek(0, SeekOrigin.Begin); Icon resultIcon = new Icon(outputStream); outputStream.Close(); return resultIcon; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Unvired.Kernel.Login; using Unvired.Kernel.Database; using AndroidProject; using System.Reflection; using System.IO; using System.Xml.Linq; using Unvired.Kernel.UI; using System.Threading.Tasks; using AndroidSample.Utils; namespace AndroidSample { [Activity(Label = "Login", Icon = "@drawable/logo", Theme = "@android:style/Theme.Holo.Light", WindowSoftInputMode = SoftInput.AdjustPan, NoHistory = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] public class LoginPage : Activity { public IDataManager appDataManager = null; ImageView login_type_image; TextView heading_label; TextView urlprefix_label; TextView url_label; TextView final_url; TextView domainLabel; TextView company_label; Spinner url_prefix; EditText url; EditText domainTextField; EditText company_field; EditText username_field; EditText password_field; Button login_button; Button cancel_button; Button options_button; AlertDialog dlgAlert = null; List<string> login_type_collection; static ProgressDialog mDialog; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.LoginPage); // Create your application here login_type_collection = new List<string>(); login_type_collection.Add(Constants.Login_Type_MicrosoftLogin); login_type_image = FindViewById<ImageView>(Resource.Id.LoginTypeImage); heading_label = FindViewById<TextView>(Resource.Id.HeadingLabel); urlprefix_label = FindViewById<TextView>(Resource.Id.URLPrefixLabel); url_prefix = FindViewById<Spinner>(Resource.Id.URLPrefixSpinner); url_label = FindViewById<TextView>(Resource.Id.URLLabel); final_url = FindViewById<TextView>(Resource.Id.FinalURLLabel); domainLabel = FindViewById<TextView>(Resource.Id.DomainLabel); company_label = FindViewById<TextView>(Resource.Id.CompanyLabel); url = FindViewById<EditText>(Resource.Id.URLTextfield); domainTextField = FindViewById<EditText>(Resource.Id.DomainTextField); username_field = FindViewById<EditText>(Resource.Id.UserNameTextField); password_field = FindViewById<EditText>(Resource.Id.PasswordTextfield); company_field = FindViewById<EditText>(Resource.Id.CompanyTextField); login_button = FindViewById<Button>(Resource.Id.LoginButton); cancel_button = FindViewById<Button>(Resource.Id.CancelButton); options_button = FindViewById<Button>(Resource.Id.OptionsButton); if (LoginParameters.LoginMode == LoginParameters.LOGIN_MODE.UNVIRED_ID_LOCAL_AUTH) { url_prefix.Visibility = ViewStates.Gone; url.Visibility = ViewStates.Gone; final_url.Visibility = ViewStates.Gone; domainLabel.Visibility = ViewStates.Gone; domainTextField.Visibility = ViewStates.Gone; company_label.Visibility = ViewStates.Gone; company_field.Visibility = ViewStates.Gone; cancel_button.Visibility = ViewStates.Gone; options_button.Visibility = ViewStates.Gone; urlprefix_label.Visibility = ViewStates.Gone; url_label.Visibility = ViewStates.Gone; } login_button.Click += delegate { DoLogin(); }; cancel_button.Click += delegate { ClearAll(); }; url_prefix.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected); url.TextChanged += delegate { URLChanged(); }; options_button.Click += delegate { methodInvokeAlertDialogWithListView(); }; var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.domains, Android.Resource.Layout.SimpleSpinnerItem); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); url_prefix.Adapter = adapter; domainLabel.Visibility = ViewStates.Gone; domainTextField.Visibility = ViewStates.Gone; } public void DoLogin() { if (Validate()) { LoginParameters.Url = final_url.Text; LoginParameters.Company = company_field.Text; mDialog = new ProgressDialog(this); mDialog.SetMessage("Please wait..."); mDialog.SetCancelable(false); mDialog.Show(); if (LoginParameters.CurrentLoginType == LoginParameters.LOGIN_TYPE.UNVIRED_ID) { if (LoginParameters.LoginMode == LoginParameters.LOGIN_MODE.UNVIRED_ID_LOCAL_AUTH) LoginCustomControl.LoginWithCredentialParameters(" ", username_field.Text, password_field.Text, null, " ", null); else LoginCustomControl.LoginWithCredentialParameters(LoginParameters.Url, username_field.Text, password_field.Text, null, LoginParameters.Company, null); } else if (LoginParameters.CurrentLoginType == LoginParameters.LOGIN_TYPE.ADS) { LoginCustomControl.LoginWithCredentialParameters(LoginParameters.Url, username_field.Text, password_field.Text, domainTextField.Text, LoginParameters.Company, null); } return; } return; } private bool Validate() { if (string.IsNullOrEmpty(username_field.Text)) { Android.Widget.Toast.MakeText(this, "Username cannot be empty", Android.Widget.ToastLength.Short).Show(); return false; } if (string.IsNullOrEmpty(password_field.Text)) { Android.Widget.Toast.MakeText(this, "Password cannot be empty", Android.Widget.ToastLength.Short).Show(); return false; } if (LoginParameters.LoginMode == LoginParameters.LOGIN_MODE.UNVIRED_ID_LOCAL_AUTH) return true; if (string.IsNullOrEmpty(url.Text)) { Android.Widget.Toast.MakeText(this, "URL cannot be empty", Android.Widget.ToastLength.Short).Show(); return false; } if (string.IsNullOrEmpty(company_field.Text)) { Android.Widget.Toast.MakeText(this, "Company cannot be empty", Android.Widget.ToastLength.Short).Show(); return false; } if (LoginParameters.CurrentLoginType == LoginParameters.LOGIN_TYPE.ADS) { if (string.IsNullOrEmpty(domainTextField.Text)) { Android.Widget.Toast.MakeText(this, "Domain cannot be empty", Android.Widget.ToastLength.Short).Show(); return false; } } return true; } private void ClearAll() { username_field.Text = ""; password_field.Text = ""; url.Text = ""; } private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { string finalstring = ""; Spinner spinner = (Spinner)sender; finalstring = spinner.GetItemAtPosition(e.Position).ToString() + "://" + url.Text; final_url.Text = finalstring; } private void URLChanged() { if (final_url.Text.Substring(0, 5).Equals("https")) { final_url.Text = "https://"; } else { final_url.Text = "http://"; } final_url.Text += url.Text; } void methodInvokeAlertDialogWithListView() { dlgAlert = (new AlertDialog.Builder(this)).Create(); dlgAlert.SetTitle("Login Type(s)"); var listView = new ListView(this); listView.Adapter = new AlertListViewAdapter(this, login_type_collection); listView.ItemClick += listViewItemClick; dlgAlert.SetView(listView); dlgAlert.Show(); } void listViewItemClick(object sender, AdapterView.ItemClickEventArgs e) { ChangeLoginMode(); dlgAlert.Cancel(); } private void ChangeLoginMode() { if (login_type_collection != null) { if (LoginParameters.CurrentLoginType == LoginParameters.LOGIN_TYPE.UNVIRED_ID) { login_type_collection.Remove(Constants.Login_Type_MicrosoftLogin); login_type_collection.Add(Constants.Login_Type_UnviredID); heading_label.Text = Constants.Login_Type_MicrosoftLogin; LoginParameters.CurrentLoginType = LoginParameters.LOGIN_TYPE.ADS; login_type_image.SetImageResource(Resource.Drawable.Microsoft); domainLabel.Visibility = ViewStates.Visible; domainTextField.Visibility = ViewStates.Visible; } else if (LoginParameters.CurrentLoginType == LoginParameters.LOGIN_TYPE.ADS) { login_type_collection.Remove(Constants.Login_Type_UnviredID); login_type_collection.Add(Constants.Login_Type_MicrosoftLogin); heading_label.Text = Constants.Login_Type_UnviredID; LoginParameters.CurrentLoginType = LoginParameters.LOGIN_TYPE.UNVIRED_ID; login_type_image.SetImageResource(Resource.Drawable.logo); domainLabel.Visibility = ViewStates.Gone; domainTextField.Visibility = ViewStates.Gone; } } } public static void LoginNotSuccessfull(string message) { if (mDialog != null) { Context c = mDialog.Context; mDialog.Cancel(); Helper.ShowSimpleMessageAlert(c, "Alert", message); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Net; using ExitGames.Client.Photon; using UnityEngine; using Debug = UnityEngine.Debug; #if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE && !UNITY_PS3 && !UNITY_WINRT) using System.Net.Sockets; /// <summary>Uses C# Socket class from System.Net.Sockets (as Unity usually does).</summary> /// <remarks>Incompatible with Windows 8 Store/Phone API.</remarks> public class PingMonoEditor : PhotonPing { private Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); public override bool StartPing(string ip) { base.Init(); try { sock.ReceiveTimeout = 5000; sock.Connect(ip, 5055); PingBytes[PingBytes.Length - 1] = PingId; sock.Send(PingBytes); PingBytes[PingBytes.Length - 1] = (byte)(PingId - 1); } catch (Exception e) { sock = null; Console.WriteLine(e); } return false; } public override bool Done() { if (this.GotResult || sock == null) { return true; } if (sock.Available <= 0) { return false; } int read = sock.Receive(PingBytes, SocketFlags.None); //Debug.Log("Got: " + SupportClass.ByteArrayToString(PingBytes)); bool replyMatch = PingBytes[PingBytes.Length - 1] == PingId && read == PingLength; if (!replyMatch) Debug.Log("ReplyMatch is false! "); this.Successful = read == PingBytes.Length && PingBytes[PingBytes.Length - 1] == PingId; this.GotResult = true; return true; } public override void Dispose() { try { sock.Close(); } catch { } sock = null; } } #endif public class PhotonPingManager { public bool UseNative; public static int Attempts = 5; public static bool IgnoreInitialAttempt = true; public static int MaxMilliseconsPerPing = 800; // enter a value you're sure some server can beat (have a lower rtt) public Region BestRegion { get { Region result = null; int bestRtt = Int32.MaxValue; foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions) { Debug.Log("BestRegion checks region: " + region); if (region.Ping != 0 && region.Ping < bestRtt) { bestRtt = region.Ping; result = region; } } return (Region)result; } } public bool Done { get { return this.PingsRunning == 0; } } private int PingsRunning; /// <remarks> /// Affected by frame-rate of app, as this Coroutine checks the socket for a result once per frame. /// </remarks> public IEnumerator PingSocket(Region region) { region.Ping = Attempts*MaxMilliseconsPerPing; this.PingsRunning++; // TODO: Add try-catch to make sure the PingsRunning are reduced at the end and that the lib does not crash the app PhotonPing ping; //Debug.Log("PhotonHandler.PingImplementation " + PhotonHandler.PingImplementation); if (PhotonHandler.PingImplementation == typeof(PingNativeDynamic)) { Debug.Log("Using constructor for new PingNativeDynamic()"); // it seems on android, the Activator can't find the default Constructor ping = new PingNativeDynamic(); } else if (PhotonHandler.PingImplementation == typeof(PingMono)) { ping = new PingMono(); // using this type explicitly saves it from IL2CPP bytecode stripping } else { ping = (PhotonPing) Activator.CreateInstance(PhotonHandler.PingImplementation); } //Debug.Log("Ping is: " + ping + " type " + ping.GetType()); float rttSum = 0.0f; int replyCount = 0; // PhotonPing.StartPing() requires a plain IP address without port (on all but Windows 8 platforms). // So: remove port and do the DNS-resolving if needed string cleanIpOfRegion = region.HostAndPort; int indexOfColon = cleanIpOfRegion.LastIndexOf(':'); if (indexOfColon > 1) { cleanIpOfRegion = cleanIpOfRegion.Substring(0, indexOfColon); } cleanIpOfRegion = ResolveHost(cleanIpOfRegion); //Debug.Log("Resolved and port-less IP is: " + cleanIpOfRegion); for (int i = 0; i < Attempts; i++) { bool overtime = false; Stopwatch sw = new Stopwatch(); sw.Start(); try { ping.StartPing(cleanIpOfRegion); } catch (Exception e) { Debug.Log("catched: " + e); this.PingsRunning--; break; } while (!ping.Done()) { if (sw.ElapsedMilliseconds >= MaxMilliseconsPerPing) { overtime = true; break; } yield return 0; // keep this loop tight, to avoid adding local lag to rtt. } int rtt = (int)sw.ElapsedMilliseconds; if (IgnoreInitialAttempt && i == 0) { // do nothing. } else if (ping.Successful && !overtime) { rttSum += rtt; replyCount++; region.Ping = (int)((rttSum) / replyCount); //Debug.Log("region " + region.Code + " RTT " + region.Ping + " success: " + ping.Successful + " over: " + overtime); } yield return new WaitForSeconds(0.1f); } this.PingsRunning--; //Debug.Log("this.PingsRunning: " + this.PingsRunning + " this debug: " + ping.DebugString); yield return null; } #if UNITY_WINRT && !UNITY_EDITOR public static string ResolveHost(string hostName) { return hostName; } #else /// <summary> /// Attempts to resolve a hostname into an IP string or returns empty string if that fails. /// </summary> /// <param name="hostName">Hostname to resolve.</param> /// <returns>IP string or empty string if resolution fails</returns> public static string ResolveHost(string hostName) { try { IPAddress[] address = Dns.GetHostAddresses(hostName); if (address.Length == 1) { return address[0].ToString(); } // if we got more addresses, try to pick a IPv4 one for (int index = 0; index < address.Length; index++) { IPAddress ipAddress = address[index]; if (ipAddress != null) { string ipString = ipAddress.ToString(); if (ipString.IndexOf('.') >= 0) { return ipString; } } } } catch (System.Exception e) { Debug.Log("Exception caught! " + e.Source + " Message: " + e.Message); } return String.Empty; } #endif }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using CorDebugInterop; using nanoFramework.Tools.Debugger; using nanoFramework.Tools.VisualStudio.Extension.MetaData; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension { public class CorDebugAssembly : ICorDebugAssembly, ICorDebugModule, ICorDebugModule2, IDisposable { CorDebugAppDomain _appDomain; CorDebugProcess _process; Hashtable _htTokenCLRToPdbx; Hashtable _htTokennanoCLRToPdbx; Pdbx.PdbxFile _pdbxFile; Pdbx.Assembly _pdbxAssembly; IMetaDataImport _iMetaDataImport; uint _idx; string _name; string _path; ulong _dummyBaseAddress; FileStream _fileStream; CorDebugAssembly _primaryAssembly; bool _isFrameworkAssembly; // this list holds the official assemblies name List<string> frameworkAssemblies_v1_0 = new List<string> { "mscorlib", "nanoframework.runtime.events", "nanoframework.runtime.native", "windows.devices.adc", "windows.devices.gpio", "windows.devices.i2c", "windows.devices.pwm", "windows.devices.serialcommunication", "windows.devices.spi", "windows.storage.streams", }; public CorDebugAssembly( CorDebugProcess process, string name, Pdbx.PdbxFile pdbxFile, uint idx ) { _process = process; _appDomain = null; _name = name; _pdbxFile = pdbxFile; _pdbxAssembly = (pdbxFile != null) ? pdbxFile.Assembly : null; _htTokenCLRToPdbx = new Hashtable(); _htTokennanoCLRToPdbx = new Hashtable(); _idx = idx; _primaryAssembly = null; _isFrameworkAssembly = false; if(_pdbxAssembly != null) { if (!string.IsNullOrEmpty(pdbxFile.PdbxPath)) { string pdbxPath = pdbxFile.PdbxPath.ToLower(); // pdbx files are supposed to be in the 'packages' folder if (pdbxPath.Contains(@"\packages\")) { _isFrameworkAssembly = (frameworkAssemblies_v1_0.Contains(name.ToLower())); } } _pdbxAssembly.CorDebugAssembly = this; foreach(Pdbx.Class c in _pdbxAssembly.Classes) { AddTokenToHashtables( c.Token, c ); foreach(Pdbx.Field field in c.Fields) { AddTokenToHashtables( field.Token, field ); } foreach(Pdbx.Method method in c.Methods) { AddTokenToHashtables( method.Token, method ); } } } } public ICorDebugAssembly ICorDebugAssembly { get { return ((ICorDebugAssembly)this); } } public ICorDebugModule ICorDebugModule { get { return ((ICorDebugModule)this); } } private bool IsPrimaryAssembly { get { return _primaryAssembly == null; } } public bool IsFrameworkAssembly { get { return _isFrameworkAssembly; } } private FileStream EnsureFileStream() { if(this.IsPrimaryAssembly) { if(_path != null && _fileStream == null) { _fileStream = File.OpenRead( _path ); _dummyBaseAddress = _process.FakeLoadAssemblyIntoMemory( this ); } return _fileStream; } else { FileStream fileStream = _primaryAssembly.EnsureFileStream(); _dummyBaseAddress = _primaryAssembly._dummyBaseAddress; return fileStream; } } public CorDebugAssembly CreateAssemblyInstance( CorDebugAppDomain appDomain ) { //Ensure the metadata import is created. IMetaDataImport iMetaDataImport = this.MetaDataImport; CorDebugAssembly assm = (CorDebugAssembly)MemberwiseClone(); assm._appDomain = appDomain; assm._primaryAssembly = this; return assm; } internal void ReadMemory( ulong address, uint size, byte[] buffer, out uint read ) { FileStream fileStream = EnsureFileStream(); read = 0; if(fileStream != null) { lock(fileStream) { fileStream.Position = (long)address; read = (uint)fileStream.Read( buffer, 0, (int)size ); } } } public static CorDebugAssembly AssemblyFromIdx( uint idx, ArrayList assemblies ) { foreach(CorDebugAssembly assembly in assemblies) { if(assembly.Idx == idx) return assembly; } return null; } public static CorDebugAssembly AssemblyFromIndex( uint index, ArrayList assemblies ) { return AssemblyFromIdx( nanoCLR_TypeSystem.IdxAssemblyFromIndex( index ), assemblies ); } public string Name { get { return _name; } } public bool HasSymbols { get { return _pdbxAssembly != null; } } private void AddTokenToHashtables( Pdbx.Token token, object o ) { _htTokenCLRToPdbx[token.CLR] = o; _htTokennanoCLRToPdbx[token.nanoCLR] = o; } private string FindAssemblyOnDisk() { if (_path == null && _pdbxAssembly != null) { string[] pathsToTry = new string[] { // Look next to pdbx file Path.Combine( Path.GetDirectoryName( _pdbxFile.PdbxPath ), _pdbxAssembly.FileName ), }; for (int iPath = 0; iPath < pathsToTry.Length; iPath++) { string path = pathsToTry[iPath]; if (File.Exists(path)) { //is this the right file? _path = path; break; } } } return _path; } private IMetaDataImport FindMetadataImport() { Debug.Assert( _iMetaDataImport == null ); IMetaDataDispenser mdd = new CorMetaDataDispenser() as IMetaDataDispenser; object pImport = null; Guid iid = typeof( IMetaDataImport ).GUID; IMetaDataImport metaDataImport = null; try { string path = FindAssemblyOnDisk(); if(path != null) { mdd.OpenScope( path, (int)MetaData.CorOpenFlags.ofRead, ref iid, out pImport ); metaDataImport = pImport as IMetaDataImport; } } catch { } //check the version? return metaDataImport; } public IMetaDataImport MetaDataImport { get { if(_iMetaDataImport == null) { if(HasSymbols) { _iMetaDataImport = FindMetadataImport(); } if(_iMetaDataImport == null) { _pdbxFile = null; _pdbxAssembly = null; _iMetaDataImport = new MetaDataImport( this ); } } return _iMetaDataImport; } } public CorDebugProcess Process { [System.Diagnostics.DebuggerHidden] get { return _process; } } public CorDebugAppDomain AppDomain { [System.Diagnostics.DebuggerHidden] get { return _appDomain; } } public uint Idx { [System.Diagnostics.DebuggerHidden] get { return _idx; } } private CorDebugFunction GetFunctionFromToken( uint tk, Hashtable ht ) { CorDebugFunction function = null; Pdbx.Method method = ht[tk] as Pdbx.Method; if(method != null) { CorDebugClass c = new CorDebugClass( this, method.Class ); function = new CorDebugFunction( c, method ); } Debug.Assert( function != null ); return function; } public CorDebugFunction GetFunctionFromTokenCLR( uint tk ) { return GetFunctionFromToken( tk, _htTokenCLRToPdbx ); } public CorDebugFunction GetFunctionFromTokennanoCLR( uint tk ) { if(HasSymbols) { return GetFunctionFromToken( tk, _htTokennanoCLRToPdbx ); } else { uint index = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken( tk, this ); Debugger.WireProtocol.Commands.Debugging_Resolve_Method.Result resolvedMethod = this.Process.Engine.ResolveMethod(index); Debug.Assert( nanoCLR_TypeSystem.IdxAssemblyFromIndex( resolvedMethod.m_td ) == this.Idx ); uint tkMethod = nanoCLR_TypeSystem.SymbollessSupport.MethodDefTokenFromnanoCLRToken( tk ); uint tkClass = nanoCLR_TypeSystem.nanoCLRTokenFromTypeIndex( resolvedMethod.m_td ); CorDebugClass c = GetClassFromTokennanoCLR( tkClass ); return new CorDebugFunction( c, tkMethod ); } } public Pdbx.ClassMember GetPdbxClassMemberFromTokenCLR( uint tk ) { return _htTokenCLRToPdbx[tk] as Pdbx.ClassMember; } private CorDebugClass GetClassFromToken( uint tk, Hashtable ht ) { CorDebugClass cls = null; Pdbx.Class c = ht[tk] as Pdbx.Class; if(c != null) { cls = new CorDebugClass( this, c ); } return cls; } public CorDebugClass GetClassFromTokenCLR( uint tk ) { return GetClassFromToken( tk, _htTokenCLRToPdbx ); } public CorDebugClass GetClassFromTokennanoCLR( uint tk ) { if(HasSymbols) return GetClassFromToken( tk, _htTokennanoCLRToPdbx ); else return new CorDebugClass( this, nanoCLR_TypeSystem.SymbollessSupport.TypeDefTokenFromnanoCLRToken( tk ) ); } ~CorDebugAssembly() { try { ((IDisposable)this).Dispose(); } catch(Exception) { } } #region IDisposable Members void IDisposable.Dispose() { if(IsPrimaryAssembly) { if(_iMetaDataImport != null && !(_iMetaDataImport is MetaDataImport)) { Marshal.ReleaseComObject( _iMetaDataImport ); } _iMetaDataImport = null; if(_fileStream != null) { ((IDisposable)_fileStream).Dispose(); _fileStream = null; } } GC.SuppressFinalize( this ); } #endregion #region ICorDebugAssembly Members int ICorDebugAssembly.GetProcess( out ICorDebugProcess ppProcess ) { ppProcess = this.Process; return COM_HResults.S_OK; } int ICorDebugAssembly.GetAppDomain( out ICorDebugAppDomain ppAppDomain ) { ppAppDomain = _appDomain; return COM_HResults.S_OK; } int ICorDebugAssembly.EnumerateModules( out ICorDebugModuleEnum ppModules ) { ppModules = new CorDebugEnum( this, typeof( ICorDebugModule ), typeof( ICorDebugModuleEnum ) ); return COM_HResults.S_OK; } int ICorDebugAssembly.GetCodeBase( uint cchName, IntPtr pcchName, IntPtr szName ) { Utility.MarshalString( "", cchName, pcchName, szName ); return COM_HResults.S_OK; } int ICorDebugAssembly.GetName( uint cchName, IntPtr pcchName, IntPtr szName ) { string name = _path != null ? _path : _name; Utility.MarshalString( name, cchName, pcchName, szName ); return COM_HResults.S_OK; } #endregion #region ICorDebugModule Members int ICorDebugModule.GetProcess( out ICorDebugProcess ppProcess ) { ppProcess = this.Process; return COM_HResults.S_OK; } int ICorDebugModule.GetBaseAddress( out ulong pAddress ) { EnsureFileStream(); pAddress = _dummyBaseAddress; return COM_HResults.S_OK; } int ICorDebugModule.GetAssembly( out ICorDebugAssembly ppAssembly ) { ppAssembly = this; return COM_HResults.S_OK; } int ICorDebugModule.GetName( uint cchName, IntPtr pcchName, IntPtr szName ) { return this.ICorDebugAssembly.GetName( cchName, pcchName, szName ); } int ICorDebugModule.EnableJITDebugging( int bTrackJITInfo, int bAllowJitOpts ) { return COM_HResults.S_OK; } int ICorDebugModule.EnableClassLoadCallbacks( int bClassLoadCallbacks ) { return COM_HResults.S_OK; } int ICorDebugModule.GetFunctionFromToken( uint methodDef, out ICorDebugFunction ppFunction ) { ppFunction = GetFunctionFromTokenCLR( methodDef ); return COM_HResults.S_OK; } int ICorDebugModule.GetFunctionFromRVA( ulong rva, out ICorDebugFunction ppFunction ) { ppFunction = null; return COM_HResults.S_OK; } int ICorDebugModule.GetClassFromToken( uint typeDef, out ICorDebugClass ppClass ) { ppClass = GetClassFromTokenCLR( typeDef ); return COM_HResults.S_OK; } int ICorDebugModule.CreateBreakpoint( out ICorDebugModuleBreakpoint ppBreakpoint ) { ppBreakpoint = null; return COM_HResults.E_NOTIMPL; } int ICorDebugModule.GetEditAndContinueSnapshot( out ICorDebugEditAndContinueSnapshot ppEditAndContinueSnapshot ) { ppEditAndContinueSnapshot = null; return COM_HResults.S_OK; } int ICorDebugModule.GetMetaDataInterface( ref Guid riid, out IntPtr ppObj ) { IntPtr pMetaDataImport = Marshal.GetIUnknownForObject( this.MetaDataImport ); Marshal.QueryInterface( pMetaDataImport, ref riid, out ppObj ); int cRef = Marshal.Release( pMetaDataImport ); Debug.Assert( riid == typeof( IMetaDataImport ).GUID || riid == typeof( IMetaDataImport2 ).GUID || riid == typeof( IMetaDataAssemblyImport ).GUID ); Debug.Assert( this.MetaDataImport != null && ppObj != IntPtr.Zero ); return COM_HResults.S_OK; } int ICorDebugModule.GetToken( out uint pToken ) { pToken = _pdbxAssembly.Token.CLR; return COM_HResults.S_OK; } int ICorDebugModule.IsDynamic( out int pDynamic ) { pDynamic = Boolean.FALSE; return COM_HResults.S_OK; } int ICorDebugModule.GetGlobalVariableValue( uint fieldDef, out ICorDebugValue ppValue ) { ppValue = null; return COM_HResults.S_OK; } int ICorDebugModule.GetSize( out uint pcBytes ) { pcBytes = 0x1000; FileStream fileStream = EnsureFileStream(); if(fileStream != null) { pcBytes = (uint)fileStream.Length; } return COM_HResults.S_OK; } int ICorDebugModule.IsInMemory( out int pInMemory ) { pInMemory = Boolean.BoolToInt( !HasSymbols );// Boolean.FALSE; return COM_HResults.S_OK; } #endregion #region ICorDebugModule2 Members int ICorDebugModule2.SetJMCStatus( int bIsJustMyCode, uint cTokens, ref uint pTokens ) { Debug.Assert(cTokens == 0); bool fJMC = Boolean.IntToBool( bIsJustMyCode ); int hres = fJMC ? COM_HResults.E_FAIL : COM_HResults.S_OK; Debug.Assert( Utility.FImplies( fJMC, this.HasSymbols ) ); if (this.HasSymbols) { if (this.Process.Engine.Info_SetJMC(fJMC, ReflectionDefinition.Kind.REFLECTION_ASSEMBLY, nanoCLR_TypeSystem.IndexFromIdxAssemblyIdx(this.Idx))) { if(!this._isFrameworkAssembly) { //now update the debugger JMC state... foreach (Pdbx.Class c in this._pdbxAssembly.Classes) { foreach (Pdbx.Method m in c.Methods) { m.IsJMC = fJMC; } } } hres = COM_HResults.S_OK; } } return hres; } int ICorDebugModule2.ApplyChanges( uint cbMetadata, byte[] pbMetadata, uint cbIL, byte[] pbIL ) { return COM_HResults.S_OK; } int ICorDebugModule2.SetJITCompilerFlags( uint dwFlags ) { return COM_HResults.S_OK; } int ICorDebugModule2.GetJITCompilerFlags( out uint pdwFlags ) { pdwFlags = (uint)CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION; return COM_HResults.S_OK; } int ICorDebugModule2.ResolveAssembly( uint tkAssemblyRef, out ICorDebugAssembly ppAssembly ) { ppAssembly = null; return COM_HResults.S_OK; } #endregion } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2013Blue; internal class VS2013BlueDockPaneStrip : DockPaneStripBase { private class TabVS2013Light : Tab { public TabVS2013Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override Tab CreateTab(IDockContent content) { return new TabVS2013Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; private bool m_suspendDrag = false; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = ThemeVS2012Light.Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = ThemeVS2012Light.Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2012LightAutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2013BlueDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } public override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2013Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2013Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2013Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2013Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2013Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2013Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2013Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2013Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2013Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2013Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2013Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2013Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2013Light tab = (TabVS2013Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2013Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2013Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2013Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2013Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color mouseHoverText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.TextColor; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, mouseHoverText, DocumentTextFormat); g.DrawImage(Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); // suspend drag if mouse is down on active close button. this.m_suspendDrag = ActiveCloseHitTest(e.Location); } protected override void OnMouseMove(MouseEventArgs e) { if (!this.m_suspendDrag) base.OnMouseMove(e); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabBounds(Tabs[index]); if (tabRect.Contains(ActiveClose) && ActiveCloseHitTest(mousePos)) TryCloseTab(index); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2013Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override bool MouseDownActivateTest(MouseEventArgs e) { bool result = base.MouseDownActivateTest(e); if (result && (e.Button == MouseButtons.Left) && (Appearance == DockPane.AppearanceStyle.Document)) { // don't activate if mouse is downed on active close button result = !ActiveCloseHitTest(e.Location); } return result; } private bool ActiveCloseHitTest(Point ptMouse) { bool result = false; if (!ActiveClose.IsEmpty) { var mouseRect = new Rectangle(ptMouse, new Size(1, 1)); result = ActiveClose.IntersectsWith(mouseRect); } return result; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline(tab, true, false); RectangleF rectangle = path.GetBounds(); return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2013Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
// 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.Variance.expr.gettype01.gettype01 { // <Area>variance</Area> // <Title> Expression based tests</Title> // <Description> getType tests</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); iVariance<Animal> v2 = v1; dynamic v3 = (iVariance<Animal>)v1; if (typeof(Variance<Tiger>).ToString() != v2.GetType().ToString()) return 1; if (typeof(Variance<Tiger>).ToString() != v3.GetType().ToString()) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype02.gettype02 { // <Area>variance</Area> // <Title> Expression based tests</Title> // <Description> getType tests</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<in T> { void Boo(T t); } public class Variance<T> : iVariance<T> { public void Boo(T t) { } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Animal>(); iVariance<Tiger> v2 = v1; dynamic v3 = (iVariance<Tiger>)v1; if (typeof(Variance<Animal>).ToString() != v2.GetType().ToString()) return 1; if (typeof(Variance<Animal>).ToString() != v3.GetType().ToString()) return 1; return 0; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype03.gettype03 { // <Area>variance</Area> // <Title> Expression based tests</Title> // <Description> getType tests</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); Foo<Tiger> f2 = f1; dynamic f3 = (Foo<Tiger>)f1; if (typeof(Foo<Animal>).ToString() != f2.GetType().ToString()) return 1; if (typeof(Foo<Animal>).ToString() != f3.GetType().ToString()) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype04.gettype04 { // <Area>variance</Area> // <Title> Expression based tests</Title> // <Description> getType tests</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate T Foo<out T>(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Tiger>)(() => { return new Tiger(); } ); Foo<Animal> f2 = f1; dynamic f3 = (Foo<Animal>)f1; if (typeof(Foo<Tiger>).ToString() != f2.GetType().ToString()) return 1; if (typeof(Foo<Tiger>).ToString() != f3.GetType().ToString()) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is01.is01 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a covariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); iVariance<Animal> v2 = v1; dynamic v3 = (iVariance<Animal>)v1; if (!(v2 is iVariance<Animal>)) return 1; if (!(v3 is iVariance<Animal>)) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is02.is02 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a covariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Variance<Tiger> v1 = new Variance<Tiger>(); iVariance<Animal> v2 = v1; dynamic v3 = (iVariance<Animal>)v1; if (!(v2 is iVariance<Animal>)) return 1; if (!(v3 is iVariance<Animal>)) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is03.is03 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with contravariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); Foo<Tiger> f2 = f1; dynamic f3 = (Foo<Tiger>)f1; if (!(f2 is Foo<Tiger>)) return 1; if (!(f3 is Foo<Tiger>)) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is04.is04 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with contravariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { private delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Foo<Animal> f1 = (Animal a) => { } ; Foo<Tiger> f2 = f1; dynamic f3 = (Foo<Tiger>)f1; if (!(f2 is Foo<Animal>)) return 1; if (!(f3 is Foo<Animal>)) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is05.is05 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a covariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); iVariance<Animal> v2 = v1; if (v1 is iVariance<Animal>) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is06.is06 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a covariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<out T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); iVariance<Animal> v2 = v1; if (v1 is iVariance<Tiger>) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is07.is07 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with contravariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); Foo<Tiger> f2 = f1; if (f1 is Foo<Tiger>) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is08.is08 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with contravariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { public delegate void Foo<in T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); Foo<Tiger> f2 = f1; if (f1 is Foo<Animal>) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is09.is09 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a invariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); if (v1 is iVariance<Animal>) return 1; else return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is10.is10 { // <Area>variance</Area> // <Title> expressions - Is Keyword</Title> // <Description> using the is keyword on a invariant public interface </Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public interface iVariance<T> { T Boo(); } public class Variance<T> : iVariance<T> where T : new() { public T Boo() { return new T(); } } public class Animal { } public class Tiger : Animal { } public class C { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v1 = new Variance<Tiger>(); if (v1 is iVariance<Tiger>) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is11.is11 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with contravariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { private delegate void Foo<T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); if (f1 is Foo<Tiger>) return 1; else return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is12.is12 { // <Area>variance</Area> // <Title> expressions - is keyword</Title> // <Description> is keyword with invariant delegates</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success> </Expects> // <Code> public class Animal { } public class Tiger : Animal { } public class C { private delegate void Foo<T>(T t); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic f1 = (Foo<Animal>)((Animal a) => { } ); if (f1 is Foo<Animal>) return 0; else return 1; } } //</Code> }
// // Copyright (C) 2010 Jackson Harper ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Manos.IO; using Mono.Unix.Native; #if !DISABLE_POSIX #endif namespace Manos.Tool { public class ServerCommand { private ManosApp app; private string application_assembly; private int? port; private int? securePort; public ServerCommand(Environment env) : this(env, new List<string>()) { } public ServerCommand(Environment env, IList<string> args) { Environment = env; Arguments = args; } public Environment Environment { get; private set; } public IList<string> Arguments { get; set; } public string ApplicationAssembly { get { if (application_assembly == null) return Path.GetFileName(Directory.GetCurrentDirectory()) + ".dll"; return application_assembly; } set { if (value == null) throw new ArgumentNullException("value"); application_assembly = value; } } public int Port { get { if (port == null) return 8080; return (int) port; } set { if (port <= 0) throw new ArgumentException("port", "port must be greater than zero."); port = value; } } public int? SecurePort { get { return securePort; } set { if (securePort <= 0) throw new ArgumentException("port", "port must be greater than zero."); securePort = value; } } public string User { get; set; } public string IPAddress { get; set; } public string CertificateFile { get; set; } public string KeyFile { get; set; } public string Browse { get; set; } public string DocumentRoot { get; set; } public void Run() { // Setup the document root if (DocumentRoot != null) { Directory.SetCurrentDirectory(Path.Combine(Directory.GetCurrentDirectory(), DocumentRoot)); } // Load the config. ManosConfig.Load(); app = Loader.LoadLibrary<ManosApp>(ApplicationAssembly, Arguments); Console.WriteLine("Running {0} on port {1}.", app, Port); if (User != null) SetServerUser(User); IPAddress listenAddress = IO.IPAddress.Any; if (IPAddress != null) listenAddress = IO.IPAddress.Parse(IPAddress); AppHost.ListenAt(new IPEndPoint(listenAddress, Port)); if (SecurePort != null) { AppHost.InitializeTLS("NORMAL"); AppHost.SecureListenAt(new IPEndPoint(listenAddress, SecurePort.Value), CertificateFile, KeyFile); Console.WriteLine("Running {0} on secure port {1}.", app, SecurePort); } if (Browse != null) { string hostname = IPAddress == null ? "http://localhost" : "http://" + IPAddress; if (Port != 80) hostname += ":" + Port; if (Browse == "") { Browse = hostname; } if (Browse.StartsWith("/")) { Browse = hostname + Browse; } if (!Browse.StartsWith("http://") && !Browse.StartsWith("https://")) Browse = "http://" + Browse; AppHost.AddTimeout(TimeSpan.FromMilliseconds(10), RepeatBehavior.Single, Browse, DoBrowse); } AppHost.Start(app); } private static void DoBrowse(ManosApp app, object user_data) { var BrowseTo = user_data as string; Console.WriteLine("Launching {0}", BrowseTo); Process.Start(BrowseTo); } public void SetServerUser(string user) { if (user == null) throw new ArgumentNullException("user"); PlatformID pid = System.Environment.OSVersion.Platform; if (pid != PlatformID.Unix /* && pid != PlatformID.MacOSX */) { // TODO: Not sure if this works on OSX yet. // // Throw an exception here, we don't want to silently fail // otherwise people might be unknowingly running as root // throw new InvalidOperationException("User can not be set on Windows platforms."); } AppHost.AddTimeout(TimeSpan.Zero, RepeatBehavior.Single, user, DoSetUser); } private void DoSetUser(ManosApp app, object user_data) { #if DISABLE_POSIX throw new InvalidOperationException ("Attempt to set user on a non-posix build."); #else var user = user_data as string; Console.WriteLine("setting user to: '{0}'", user); if (user == null) { AppHost.Stop(); throw new InvalidOperationException(String.Format("Attempting to set user to null.")); } Passwd pwd = Syscall.getpwnam(user); if (pwd == null) { AppHost.Stop(); throw new InvalidOperationException(String.Format("Unable to find user '{0}'.", user)); } int error = Syscall.seteuid(pwd.pw_uid); if (error != 0) { AppHost.Stop(); throw new InvalidOperationException(String.Format("Unable to switch to user '{0}' error: '{1}'.", user, error)); } #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. // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System { [Pure] internal static class ThrowHelper { internal static void ThrowArrayTypeMismatchException() { throw new ArrayTypeMismatchException(); } internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType)); } internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } internal static void ThrowArgumentException_DestinationTooShort() { throw new ArgumentException(SR.Argument_DestinationTooShort); } internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) { throw GetWrongKeyTypeArgumentException(key, targetType); } internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) { throw GetWrongValueTypeArgumentException(value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) { return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)); } internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) { throw GetAddingDuplicateWithKeyArgumentException(key); } internal static void ThrowKeyNotFoundException() { throw new System.Collections.Generic.KeyNotFoundException(); } internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw GetArgumentException(resource, argument); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } internal static void ThrowArgumentNullException(ExceptionResource resource) { throw new ArgumentNullException(GetResourceString(resource)); } internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource) { throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, paramNumber, resource); } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw GetInvalidOperationException(resource); } internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(GetResourceString(resource)); } internal static void ThrowSecurityException(ExceptionResource resource) { throw new System.Security.SecurityException(GetResourceString(resource)); } internal static void ThrowRankException(ExceptionResource resource) { throw new RankException(GetResourceString(resource)); } internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) { throw new UnauthorizedAccessException(GetResourceString(resource)); } internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) { throw new ObjectDisposedException(objectName, GetResourceString(resource)); } internal static void ThrowObjectDisposedException(ExceptionResource resource) { throw new ObjectDisposedException(null, GetResourceString(resource)); } internal static void ThrowNotSupportedException() { throw new NotSupportedException(); } internal static void ThrowAggregateException(List<Exception> exceptions) { throw new AggregateException(exceptions); } internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); } internal static void ThrowInvalidOperationException_EnumCurrent(int index) { throw GetInvalidOperationException_EnumCurrent(index); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) { throw GetArraySegmentCtorValidationFailedException(array, offset, count); } private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) { if (array == null) return GetArgumentNullException(ExceptionArgument.array); if (offset < 0) return GetArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) return GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Debug.Assert(array.Length - offset < count); return GetArgumentException(ExceptionResource.Argument_InvalidOffLen); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) { return new InvalidOperationException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) { return new ArgumentException(GetResourceString(resource), GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource)); } private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index) { return GetInvalidOperationException( index < 0 ? ExceptionResource.InvalidOperation_EnumNotStarted : ExceptionResource.InvalidOperation_EnumEnded); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } // This function will convert an ExceptionArgument enum value to the argument name string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentName(ExceptionArgument argument) { Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), "The enum value is not defined, please check the ExceptionArgument Enum."); return argument.ToString(); } // This function will convert an ExceptionResource enum value to the resource string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource) { Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), "The enum value is not defined, please check the ExceptionResource Enum."); return SR.GetResourceString(resource.ToString()); } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj, dictionary, dictionaryCreationThreshold, array, info, key, collection, list, match, converter, queue, stack, capacity, index, startIndex, value, count, arrayIndex, name, mode, item, options, view, sourceBytesToCopy, action, comparison, offset, newSize, elementType, length, length1, length2, length3, lengths, len, lowerBounds, sourceArray, destinationArray, sourceIndex, destinationIndex, indices, index1, index2, index3, other, comparer, endIndex, keys, creationOptions, timeout, tasks, scheduler, continuationFunction, millisecondsTimeout, millisecondsDelay, function, exceptions, exception, cancellationToken, delay, asyncResult, endMethod, endFunction, beginMethod, continuationOptions, continuationAction, valueFactory, addValueFactory, updateValueFactory, concurrencyLevel, text, callBack, type, stateMachine, pHandle, values, task, s, input, ownedMemory } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable, Argument_InvalidType, Argument_InvalidArgumentForComparison, Argument_InvalidRegistryKeyPermissionCheck, ArgumentOutOfRange_NeedNonNegNum, Arg_ArrayPlusOffTooSmall, Arg_NonZeroLowerBound, Arg_RankMultiDimNotSupported, Arg_RegKeyDelHive, Arg_RegKeyStrLenBug, Arg_RegSetStrArrNull, Arg_RegSetMismatchedKind, Arg_RegSubKeyAbsent, Arg_RegSubKeyValueAbsent, Argument_AddingDuplicate, Serialization_InvalidOnDeser, Serialization_MissingKeys, Serialization_NullKey, Argument_InvalidArrayType, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, ArgumentOutOfRange_SmallCapacity, ArgumentOutOfRange_Index, Argument_InvalidOffLen, Argument_ItemNotExist, ArgumentOutOfRange_Count, ArgumentOutOfRange_InvalidThreshold, ArgumentOutOfRange_ListInsert, NotSupported_ReadOnlyCollection, InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue, InvalidOperation_EnumOpCantHappen, InvalidOperation_EnumFailedVersion, InvalidOperation_EmptyStack, ArgumentOutOfRange_BiggerThanCollection, InvalidOperation_EnumNotStarted, InvalidOperation_EnumEnded, NotSupported_SortedListNestedWrite, InvalidOperation_NoValue, InvalidOperation_RegRemoveSubKey, Security_RegistryPermission, UnauthorizedAccess_RegistryNoWrite, ObjectDisposed_RegKeyClosed, NotSupported_InComparableType, Argument_InvalidRegistryOptionsCheck, Argument_InvalidRegistryViewCheck, InvalidOperation_NullArray, Arg_MustBeType, Arg_NeedAtLeast1Rank, ArgumentOutOfRange_HugeArrayNotSupported, Arg_RanksAndBounds, Arg_RankIndices, Arg_Need1DArray, Arg_Need2DArray, Arg_Need3DArray, NotSupported_FixedSizeCollection, ArgumentException_OtherNotArrayOfCorrectLength, Rank_MultiDimNotSupported, InvalidOperation_IComparerFailed, ArgumentOutOfRange_EndIndexStartIndex, Arg_LowerBoundsMustMatch, Arg_BogusIComparer, Task_WaitMulti_NullTask, Task_ThrowIfDisposed, Task_Start_TaskCompleted, Task_Start_Promise, Task_Start_ContinuationTask, Task_Start_AlreadyStarted, Task_RunSynchronously_TaskCompleted, Task_RunSynchronously_Continuation, Task_RunSynchronously_Promise, Task_RunSynchronously_AlreadyStarted, Task_MultiTaskContinuation_NullTask, Task_MultiTaskContinuation_EmptyTaskList, Task_Dispose_NotCompleted, Task_Delay_InvalidMillisecondsDelay, Task_Delay_InvalidDelay, Task_ctor_LRandSR, Task_ContinueWith_NotOnAnything, Task_ContinueWith_ESandLR, TaskT_TransitionToFinal_AlreadyCompleted, TaskCompletionSourceT_TrySetException_NullException, TaskCompletionSourceT_TrySetException_NoExceptions, Memory_ThrowIfDisposed, Memory_OutstandingReferences, InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ConcurrentDictionary_ConcurrencyLevelMustBePositive, ConcurrentDictionary_CapacityMustNotBeNegative, ConcurrentDictionary_TypeOfValueIncorrect, ConcurrentDictionary_TypeOfKeyIncorrect, ConcurrentDictionary_SourceContainsDuplicateKeys, ConcurrentDictionary_KeyAlreadyExisted, ConcurrentDictionary_ItemKeyIsNull, ConcurrentDictionary_IndexIsNegative, ConcurrentDictionary_ArrayNotLargeEnough, ConcurrentDictionary_ArrayIncorrectType, ConcurrentCollection_SyncRoot_NotSupported, ArgumentOutOfRange_Enum, InvalidOperation_HandleIsNotInitialized, AsyncMethodBuilder_InstanceNotInitialized, ArgumentNull_SafeHandle, } }
// // MetaPixel.cs // // Author: // Stephane Delcroix <[email protected]> // Stephen Shaw <[email protected]> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2008 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Generic; using Gtk; using FSpot; using FSpot.Extensions; using FSpot.Widgets; using FSpot.Filters; using FSpot.UI.Dialog; using Hyena; using Mono.Unix; namespace MetaPixelExtension { public class MetaPixel: ICommand { [Glade.Widget] Gtk.Dialog metapixel_dialog; [Glade.Widget] Gtk.HBox tagentry_box; [Glade.Widget] Gtk.SpinButton icon_x_size; [Glade.Widget] Gtk.SpinButton icon_y_size; [Glade.Widget] Gtk.RadioButton tags_radio; [Glade.Widget] Gtk.RadioButton current_radio; FSpot.Widgets.TagEntry miniatures_tags; string minidir_tmp; public void Run (object o, EventArgs e) { Log.Information ("Executing MetaPixel extension"); if (App.Instance.Organizer.SelectedPhotos ().Length == 0) { InfoDialog (Catalog.GetString ("No selection available"), Catalog.GetString ("This tool requires an active selection. Please select one or more pictures and try again"), Gtk.MessageType.Error); return; } else { //Check for MetaPixel executable string output = ""; try { System.Diagnostics.Process mp_check = new System.Diagnostics.Process (); mp_check.StartInfo.RedirectStandardOutput = true; mp_check.StartInfo.UseShellExecute = false; mp_check.StartInfo.FileName = "metapixel"; mp_check.StartInfo.Arguments = "--version"; mp_check.Start (); mp_check.WaitForExit (); StreamReader sroutput = mp_check.StandardOutput; output = sroutput.ReadLine (); } catch (System.Exception) { } if (!System.Text.RegularExpressions.Regex.IsMatch (output, "^metapixel")) { InfoDialog (Catalog.GetString ("Metapixel not available"), Catalog.GetString ("The metapixel executable was not found in path. Please check that you have it installed and that you have permissions to execute it"), Gtk.MessageType.Error); return; } ShowDialog (); } } public void ShowDialog () { Glade.XML xml = new Glade.XML (null, "MetaPixel.glade", "metapixel_dialog", "f-spot"); xml.Autoconnect (this); metapixel_dialog.Modal = false; metapixel_dialog.TransientFor = null; miniatures_tags = new FSpot.Widgets.TagEntry (App.Instance.Database.Tags, false); miniatures_tags.UpdateFromTagNames (new string []{}); tagentry_box.Add (miniatures_tags); metapixel_dialog.Response += on_dialog_response; current_radio.Active = true; tags_radio.Toggled += HandleTagsRadioToggled; HandleTagsRadioToggled (null, null); metapixel_dialog.ShowAll (); } void on_dialog_response (object obj, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { create_mosaics (); } metapixel_dialog.Destroy (); } void create_mosaics () { //Prepare the query Db db = App.Instance.Database; FSpot.PhotoQuery mini_query = new FSpot.PhotoQuery (db.Photos); Photo [] photos; if (tags_radio.Active) { //Build tag array List<Tag> taglist = new List<Tag> (); foreach (string tag_name in miniatures_tags.GetTypedTagNames ()) { Tag t = db.Tags.GetTagByName (tag_name); if (t != null) taglist.Add(t); } mini_query.Terms = FSpot.OrTerm.FromTags (taglist.ToArray ()); photos = mini_query.Photos; } else { photos = App.Instance.Organizer.Query.Photos; } if (photos.Length == 0) { //There is no photo for the selected tags! :( InfoDialog (Catalog.GetString ("No photos for the selection"), Catalog.GetString ("The tags selected provided no pictures. Please select different tags"), Gtk.MessageType.Error); return; } //Create minis ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog (Catalog.GetString ("Creating miniatures"), ProgressDialog.CancelButtonType.Stop, photos.Length, metapixel_dialog); minidir_tmp = System.IO.Path.GetTempFileName (); System.IO.File.Delete (minidir_tmp); System.IO.Directory.CreateDirectory (minidir_tmp); minidir_tmp += "/"; //Call MetaPixel to create the minis foreach (Photo p in photos) { if (progress_dialog.Update (String.Format (Catalog.GetString ("Preparing photo \"{0}\""), p.Name))) { progress_dialog.Destroy (); DeleteTmp (); return; } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) { Log.WarningFormat (String.Format ("Couldn't access photo {0} while creating miniatures", p.DefaultVersion.Uri.LocalPath)); continue; } //FIXME Check if the picture's format is supproted (jpg, gif) FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri); filters.Convert (freq); //We use photo id for minis, instead of photo names, to avoid duplicates string minifile = minidir_tmp + p.Id.ToString() + System.IO.Path.GetExtension (p.DefaultVersion.Uri.ToString ()); string prepare_command = String.Format ("--prepare -w {0} -h {1} {2} {3} {4}tables.mxt", icon_x_size.Text, //Minis width icon_y_size.Text, //Minis height GLib.Shell.Quote (freq.Current.LocalPath), //Source image GLib.Shell.Quote (minifile), //Dest image minidir_tmp); //Table file Log.Debug ("Executing: metapixel " + prepare_command); System.Diagnostics.Process mp_prep = System.Diagnostics.Process.Start ("metapixel", prepare_command); mp_prep.WaitForExit (); if (!System.IO.File.Exists (minifile)) { Log.DebugFormat ("No mini? No party! {0}", minifile); continue; } } //Finished preparing! if (progress_dialog != null) progress_dialog.Destroy (); progress_dialog = null; progress_dialog = new ProgressDialog (Catalog.GetString ("Creating photomosaics"), ProgressDialog.CancelButtonType.Stop, App.Instance.Organizer.SelectedPhotos ().Length, metapixel_dialog); //Now create the mosaics! uint error_count = 0; foreach (Photo p in App.Instance.Organizer.SelectedPhotos ()) { if (progress_dialog.Update (String.Format (Catalog.GetString ("Processing \"{0}\""), p.Name))) { progress_dialog.Destroy (); DeleteTmp (); return; } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) { Log.WarningFormat (String.Format ("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath)); error_count ++; continue; } //FIXME Check if the picture's format is supproted (jpg, gif) FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri); filters.Convert (freq); string name = GetVersionName (p); System.Uri mosaic = GetUriForVersionName (p, name); string mosaic_command = String.Format ("--metapixel -l {0} {1} {2}", minidir_tmp, GLib.Shell.Quote (freq.Current.LocalPath), GLib.Shell.Quote (mosaic.LocalPath)); Log.Debug ("Executing: metapixel " + mosaic_command); System.Diagnostics.Process mp_exe = System.Diagnostics.Process.Start ("metapixel", mosaic_command); mp_exe.WaitForExit (); if (!GLib.FileFactory.NewForUri (mosaic).Exists) { Log.Warning ("Error in processing image " + p.Name); error_count ++; continue; } p.DefaultVersionId = p.AddVersion (mosaic, name, true); p.Changes.DataChanged = true; Core.Database.Photos.Commit (p); } //Finished creating mosaics if (progress_dialog != null) progress_dialog.Destroy (); string final_message = "Your mosaics have been generated as new versions of the pictures you selected"; if (error_count > 0) final_message += String.Format (".\n{0} images out of {1} had errors", error_count, App.Instance.Organizer.SelectedPhotos ().Length); InfoDialog (Catalog.GetString ("PhotoMosaics generated!"), Catalog.GetString (final_message), (error_count == 0 ? Gtk.MessageType.Info : Gtk.MessageType.Warning)); DeleteTmp (); } private void HandleTagsRadioToggled (object o, EventArgs e) { miniatures_tags.Sensitive = tags_radio.Active; } private static string GetVersionName (Photo p) { return GetVersionName (p, 1); } private static string GetVersionName (Photo p, int i) { string name = Catalog.GetPluralString ("PhotoMosaic", "PhotoMosaic ({0})", i); name = String.Format (name, i); if (p.VersionNameExists (name)) return GetVersionName (p, i + 1); return name; } private System.Uri GetUriForVersionName (Photo p, string version_name) { string name_without_ext = System.IO.Path.GetFileNameWithoutExtension (p.Name); return new System.Uri (System.IO.Path.Combine (DirectoryPath (p), name_without_ext + " (" + version_name + ")" + ".jpg")); } private static string DirectoryPath (Photo p) { System.Uri uri = p.VersionUri (Photo.OriginalVersionId); return uri.Scheme + "://" + uri.Host + System.IO.Path.GetDirectoryName (uri.AbsolutePath); } private void DeleteTmp () { //Clean temp workdir DirectoryInfo dir = new DirectoryInfo(minidir_tmp); FileInfo[] tmpfiles = dir.GetFiles(); foreach (FileInfo f in tmpfiles) { if (System.IO.File.Exists (minidir_tmp + f.Name)) { System.IO.File.Delete (minidir_tmp + f.Name); } } if (System.IO.Directory.Exists (minidir_tmp)) { System.IO.Directory.Delete(minidir_tmp); } } private void InfoDialog (string title, string msg, Gtk.MessageType type) { HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, type, ButtonsType.Ok, title, msg); md.Run (); md.Destroy (); } } }
// 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; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> internal sealed partial class UnixFileStream : FileStreamBase { /// <summary>The file descriptor wrapped in a file handle.</summary> private readonly SafeFileHandle _fileHandle; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>File mode.</summary> private readonly FileMode _mode; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>Advanced options requested when opening the file.</summary> private readonly FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private readonly long _appendStart = -1; /// <summary>Whether asynchronous read/write/flush operations should be performed using async I/O.</summary> private readonly bool _useAsyncIO; /// <summary>The length of the _buffer.</summary> private readonly int _bufferLength; /// <summary>Lazily-initialized buffer data from Write waiting to be written to the underlying handle, or data read from the underlying handle and waiting to be Read.</summary> private byte[] _buffer; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file descriptor's actual position, /// and should only ever be out of sync if another stream with access to this same file descriptor manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="path">The path to the file.</param> /// <param name="mode">How the file should be opened.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="options">Additional options for working with the file.</param> internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) : base(parent) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _path = path; _access = access; _mode = mode; _options = options; _bufferLength = bufferSize; _useAsyncIO = (options & FileOptions.Asynchronous) != 0; // Translate the arguments into arguments for an open call Interop.libc.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored Interop.libc.Permissions openPermissions = Interop.libc.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized. _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions); _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. try { Interop.libc.LockOperations lockOperation = (share == FileShare.None) ? Interop.libc.LockOperations.LOCK_EX : Interop.libc.LockOperations.LOCK_SH; SysCall<Interop.libc.LockOperations, int>((fd, op, _) => Interop.libc.flock(fd, op), lockOperation | Interop.libc.LockOperations.LOCK_NB); } catch { _fileHandle.Dispose(); throw; } // Perform additional configurations on the stream based on the provided FileOptions PostOpenConfigureStreamFromOptions(); // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(0, SeekOrigin.End); } } /// <summary>Performs additional configuration of the opened stream based on provided options.</summary> partial void PostOpenConfigureStreamFromOptions(); /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> /// <param name="handle">The handle to the file.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param> internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent) : base(parent) { // Make sure the handle is open if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, "handle"); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum); if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, "handle"); _fileHandle = handle; _access = access; _exposedHandle = true; _bufferLength = bufferSize; _useAsyncIO = useAsyncIO; if (CanSeek) { SeekCore(0, SeekOrigin.Current); } } /// <summary>Gets the array used for buffering reading and writing. If the array hasn't been allocated, this will lazily allocate it.</summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); return _buffer ?? (_buffer = new byte[_bufferLength]); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.libc.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.libc.OpenFlags flags = default(Interop.libc.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.libc.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.libc.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.libc.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.libc.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.libc.OpenFlags.O_WRONLY; break; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. switch (options) { case FileOptions.Asynchronous: // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true case FileOptions.DeleteOnClose: // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose case FileOptions.Encrypted: // Encrypted does not have an equivalent on Unix and is ignored. case FileOptions.RandomAccess: // Implemented after open if posix_fadvise is available case FileOptions.SequentialScan: // Implemented after open if posix_fadvise is available break; case FileOptions.WriteThrough: flags |= Interop.libc.OpenFlags.O_SYNC; break; } return flags; } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek { get { if (_fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = SysCall<int, int>((fd, _, __) => Interop.libc.lseek(fd, 0, Interop.libc.SeekWhence.SEEK_CUR), throwOnError: false) >= 0; } return _canSeek.Value; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public override bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } // Get the length of the file as reported by the OS long length = SysCall<int, int>((fd, _, __) => { Interop.libcoreclr.fileinfo fileinfo; int result = Interop.libcoreclr.GetFileInformationFromFd(fd, out fileinfo); return result >= 0 ? fileinfo.size : result; }); // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } } /// <summary>Gets the path that was passed to the constructor.</summary> public override String Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets the SafeFileHandle for the file descriptor encapsulated in this stream.</summary> public override SafeFileHandle SafeFileHandle { get { _parent.Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } _parent.Seek(value, SeekOrigin.Begin); } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void VerifyBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && _parent.CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { // Flush and close the file try { if (_fileHandle != null && !_fileHandle.IsClosed) { FlushWriteBuffer(); // Unix doesn't directly support DeleteOnClose but we can mimick it. if ((_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed. Interop.libc.unlink(_path); // ignore any error } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Finalize the stream.</summary> ~UnixFileStream() { Dispose(false); } /// <summary>Clears buffers for this stream and causes any buffered data to be written to the file.</summary> public override void Flush() { _parent.Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public override void Flush(Boolean flushToDisk) { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } FlushInternalBuffer(); if (flushToDisk && _parent.CanWrite) { FlushOSBuffer(); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { SysCall<int, int>((fd, _, __) => Interop.libc.fsync(fd)); } /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && _parent.CanSeek) { FlushReadBuffer(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { WriteCore(GetBuffer(), 0, _writePos); _writePos = 0; } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { VerifyBufferInvariants(); int rewind = _readPos - _readLength; if (rewind != 0) { SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (_parent.CanWrite) { return Task.Factory.StartNew( state => ((UnixFileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } if (!_parent.CanWrite) { throw __Error.GetWriteNotSupported(); } FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(value, SeekOrigin.Begin); } SysCall<long, int>((fd, length, _) => Interop.libc.ftruncate(fd, length), value); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(origPos, SeekOrigin.Begin); } else { SeekCore(0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> public override int Read([In, Out] byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!_parent.CanSeek || (count >= _bufferLength)) { // Read directly into the user's buffer int bytesRead = ReadCore(array, offset, count); _readPos = _readLength = 0; // reset after the read just in case read experiences an exception return bytesRead; } else { // Read into our buffer. _readLength = numBytesAvailable = ReadCore(GetBuffer(), 0, _bufferLength); _readPos = 0; if (numBytesAvailable == 0) { return 0; } } } // Now that we know there's data in the buffer, read from it into // the user's buffer. int bytesToRead = Math.Min(numBytesAvailable, count); Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesToRead); _readPos += bytesToRead; return bytesToRead; } /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadCore(byte[] array, int offset, int count) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = array) { bytesRead = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.ReadAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Reads a byte from the stream and advances the position within the stream /// by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { _readLength = ReadCore(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (_readLength == 0 && !_parent.CanRead) { throw __Error.GetReadNotSupported(); } VerifyBufferInvariants(); } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForWriting(); // If no data is being written, nothing more to do. if (count == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining > 0) { int bytesToCopy = Math.Min(spaceRemaining, count); Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy); _writePos += bytesToCopy; // If we've successfully copied all of the user's data, we're done. if (count == bytesToCopy) { return; } // Otherwise, keep track of how much more data needs to be handled. offset += bytesToCopy; count -= bytesToCopy; } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (count >= _bufferLength) { WriteCore(array, offset, count); } else { Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count); _writePos = count; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private unsafe void WriteCore(byte[] array, int offset, int count) { VerifyOSHandlePosition(); fixed (byte* bufPtr = array) { while (count > 0) { int bytesWritten = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); _filePosition += bytesWritten; count -= bytesWritten; offset += bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.WriteAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) // avoids an array allocation in the base implementation { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) { FlushWriteBuffer(); } // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!_parent.CanWrite) throw __Error.GetWriteNotSupported(); FlushReadBuffer(); } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, "origin"); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(long offset, SeekOrigin origin) { Debug.Assert(!_fileHandle.IsClosed && CanSeek); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = SysCall((fd, off, or) => Interop.libc.lseek(fd, off, or), offset, (Interop.libc.SeekWhence)(int)origin); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <typeparam name="TArg1">Specifies the type of an argument to the system call.</typeparam> /// <typeparam name="TArg2">Specifies the type of another argument to the system call.</typeparam> /// <param name="sysCall">A delegate that invokes the system call.</param> /// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param> /// <param name="arg2">The second argument to be passed to the system call.</param> /// <param name="throwOnError">true to throw an exception if a non-interuption error occurs; otherwise, false.</param> /// <returns>The return value of the system call.</returns> /// <remarks> /// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/> /// so as to avoid delegate and closure allocations at the call sites. /// </remarks> private long SysCall<TArg1, TArg2>( Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1 = default(TArg1), TArg2 arg2 = default(TArg2), bool throwOnError = true) { SafeFileHandle handle = _fileHandle; Debug.Assert(sysCall != null); Debug.Assert(handle != null); bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. handle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)handle.DangerousGetHandle(); Debug.Assert(fd >= 0); // System calls may fail due to EINTR (signal interruption). We need to retry in those cases. while (true) { long result = sysCall(fd, arg1, arg2); if (result < 0) { int errno = Marshal.GetLastWin32Error(); if (errno == Interop.Errors.EINTR) { continue; } else if (throwOnError) { throw Interop.GetExceptionForIoErrno(errno, _path, isDirectory: false); } } return result; } } finally { if (gotRefOnHandle) { handle.DangerousRelease(); } else { throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Android.App; using Android.Content.PM; using Android.OS; using Android.Support.V4.App; using Android.Support.V4.Widget; using Android.Text.Format; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; using Toggl.Joey.UI.Components; using Toggl.Joey.UI.Fragments; using Toggl.Joey.UI.Views; using Toggl.Phoebe; using Toggl.Phoebe.Data; using Toggl.Phoebe.Net; using XPlatUtils; using ActionBarDrawerToggle = Android.Support.V7.App.ActionBarDrawerToggle; using Fragment = Android.Support.V4.App.Fragment; using Toolbar = Android.Support.V7.Widget.Toolbar; namespace Toggl.Joey.UI.Activities { [Activity ( ScreenOrientation = ScreenOrientation.Portrait, Name = "toggl.joey.ui.activities.MainDrawerActivity", Label = "@string/EntryName", Exported = true, #if DEBUG // The actual entry-point is defined in manifest via activity-alias, this here is just to // make adb launch the activity automatically when developing. #endif Theme = "@style/Theme.Toggl.App")] public class MainDrawerActivity : BaseActivity { private const string PageStackExtra = "com.toggl.timer.page_stack"; private const string LastSyncArgument = "com.toggl.timer.last_sync"; private const string LastSyncResultArgument = "com.toggl.timer.last_sync_result"; private readonly TimerComponent barTimer = new TimerComponent (); private readonly Lazy<LogTimeEntriesListFragment> trackingFragment = new Lazy<LogTimeEntriesListFragment> (); private readonly Lazy<SettingsListFragment> settingsFragment = new Lazy<SettingsListFragment> (); private readonly Lazy<ReportsPagerFragment> reportFragment = new Lazy<ReportsPagerFragment> (); private readonly Lazy<FeedbackFragment> feedbackFragment = new Lazy<FeedbackFragment> (); private readonly List<int> pageStack = new List<int> (); private readonly Handler handler = new Handler (); private DrawerListAdapter drawerAdapter; private ImageButton syncRetryButton; private TextView syncStatusText; private long lastSyncInMillis; private int syncStatus; private ToolbarModes toolbarMode; private Subscription<SyncStartedMessage> drawerSyncStarted; private Subscription<SyncFinishedMessage> drawerSyncFinished; private static readonly int syncing = 0; private static readonly int syncSuccessful = 1; private static readonly int syncHadErrors = 2; private static readonly int syncFatalError = 3; private ListView DrawerListView { get; set; } private TextView DrawerUserName { get; set; } private ProfileImageView DrawerImage { get; set; } private View DrawerUserView { get; set; } private DrawerLayout DrawerLayout { get; set; } protected ActionBarDrawerToggle DrawerToggle { get; private set; } private FrameLayout DrawerSyncView { get; set; } private Toolbar MainToolbar { get; set; } protected override void OnCreateActivity (Bundle state) { base.OnCreateActivity (state); SetContentView (Resource.Layout.MainDrawerActivity); MainToolbar = FindViewById<Toolbar> (Resource.Id.MainToolbar); DrawerListView = FindViewById<ListView> (Resource.Id.DrawerListView); DrawerUserView = LayoutInflater.Inflate (Resource.Layout.MainDrawerListHeader, null); DrawerUserName = DrawerUserView.FindViewById<TextView> (Resource.Id.TitleTextView); DrawerImage = DrawerUserView.FindViewById<ProfileImageView> (Resource.Id.IconProfileImageView); DrawerListView.AddHeaderView (DrawerUserView); DrawerListView.Adapter = drawerAdapter = new DrawerListAdapter (); DrawerListView.ItemClick += OnDrawerListViewItemClick; var authManager = ServiceContainer.Resolve<AuthManager> (); authManager.PropertyChanged += OnUserChangedEvent; DrawerLayout = FindViewById<DrawerLayout> (Resource.Id.DrawerLayout); DrawerToggle = new ActionBarDrawerToggle (this, DrawerLayout, MainToolbar, Resource.String.EntryName, Resource.String.EntryName); DrawerLayout.SetDrawerShadow (Resource.Drawable.drawershadow, (int)GravityFlags.Start); DrawerLayout.SetDrawerListener (DrawerToggle); Timer.OnCreate (this); var lp = new Android.Support.V7.App.ActionBar.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, (int)GravityFlags.Right); MainToolbar.SetNavigationIcon (Resource.Drawable.ic_menu_black_24dp); SetSupportActionBar (MainToolbar); SupportActionBar.SetTitle (Resource.String.MainDrawerTimer); SupportActionBar.SetCustomView (Timer.Root, lp); SupportActionBar.SetDisplayShowCustomEnabled (true); var bus = ServiceContainer.Resolve<MessageBus> (); drawerSyncStarted = bus.Subscribe<SyncStartedMessage> (SyncStarted); drawerSyncFinished = bus.Subscribe<SyncFinishedMessage> (SyncFinished); DrawerSyncView = FindViewById<FrameLayout> (Resource.Id.DrawerSyncStatus); syncRetryButton = DrawerSyncView.FindViewById<ImageButton> (Resource.Id.SyncRetryButton); syncRetryButton.Click += OnSyncRetryClick; syncStatusText = DrawerSyncView.FindViewById<TextView> (Resource.Id.SyncStatusText); if (state == null) { OpenPage (DrawerListAdapter.TimerPageId); } else { // Restore page stack pageStack.Clear (); var arr = state.GetIntArray (PageStackExtra); if (arr != null) { pageStack.AddRange (arr); } } // Make sure that the user will see newest data when they start the activity ServiceContainer.Resolve<ISyncManager> ().Run (); } public ToolbarModes ToolbarMode { get { return toolbarMode; } set { toolbarMode = value; AdjustToolbar(); } } private void AdjustToolbar() { switch (toolbarMode) { case MainDrawerActivity.ToolbarModes.Timer: SupportActionBar.SetDisplayShowTitleEnabled (false); Timer.Hide = false; break; case MainDrawerActivity.ToolbarModes.Normal: Timer.Hide = true; SupportActionBar.SetDisplayShowTitleEnabled (true); break; } } private void OnUserChangedEvent (object sender, PropertyChangedEventArgs args) { var userData = ServiceContainer.Resolve<AuthManager> ().User; if (userData == null) { return; } DrawerUserName.Text = userData.Name; DrawerImage.ImageUrl = userData.ImageUrl; } protected override void OnSaveInstanceState (Bundle outState) { outState.PutIntArray (PageStackExtra, pageStack.ToArray ()); outState.PutLong (LastSyncArgument, lastSyncInMillis); outState.PutInt (LastSyncResultArgument, syncStatus); base.OnSaveInstanceState (outState); } protected override void OnPostCreate (Bundle savedInstanceState) { if (savedInstanceState != null) { lastSyncInMillis = savedInstanceState.GetLong (LastSyncArgument); syncStatus = savedInstanceState.GetInt (LastSyncResultArgument); UpdateSyncStatus (); } base.OnPostCreate (savedInstanceState); } public override void OnConfigurationChanged (Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged (newConfig); DrawerToggle.OnConfigurationChanged (newConfig); } public override bool OnOptionsItemSelected (IMenuItem item) { return DrawerToggle.OnOptionsItemSelected (item) || base.OnOptionsItemSelected (item); } protected override void OnStart () { base.OnStart (); Timer.OnStart (); } protected override void OnStop () { base.OnStop (); Timer.OnStop (); } protected override void OnDestroy () { Timer.OnDestroy (this); var bus = ServiceContainer.Resolve<MessageBus> (); if (drawerSyncStarted != null) { bus.Unsubscribe (drawerSyncStarted); drawerSyncStarted = null; } if (drawerSyncFinished != null) { bus.Unsubscribe (drawerSyncFinished); drawerSyncFinished = null; } base.OnDestroy (); } public override void OnBackPressed () { if (pageStack.Count > 0) { pageStack.RemoveAt (pageStack.Count - 1); var pageId = pageStack.Count > 0 ? pageStack [pageStack.Count - 1] : DrawerListAdapter.TimerPageId; OpenPage (pageId); } else { base.OnBackPressed (); } } private void SetMenuSelection (int pos) { int parentPos = drawerAdapter.GetParentPosition (pos -1); DrawerListView.ClearChoices (); if (parentPos > -1) { DrawerListView.ChoiceMode = (ChoiceMode)ListView.ChoiceModeMultiple; DrawerListView.SetItemChecked (parentPos, true); DrawerListView.SetItemChecked (pos, true); } else { DrawerListView.ChoiceMode = (ChoiceMode)ListView.ChoiceModeSingle; DrawerListView.SetItemChecked (pos, true); } } private void OpenPage (int id) { if (id == DrawerListAdapter.SettingsPageId) { OpenFragment (settingsFragment.Value); SupportActionBar.SetTitle (Resource.String.MainDrawerSettings); } else if (id == DrawerListAdapter.ReportsPageId) { drawerAdapter.ExpandCollapse (DrawerListAdapter.ReportsPageId); if (reportFragment.Value.ZoomLevel == ZoomLevel.Week) { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsWeek); id = DrawerListAdapter.ReportsWeekPageId; } else if (reportFragment.Value.ZoomLevel == ZoomLevel.Month) { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsMonth); id = DrawerListAdapter.ReportsMonthPageId; } else { SupportActionBar.SetTitle (Resource.String.MainDrawerReportsYear); id = DrawerListAdapter.ReportsYearPageId; } OpenFragment (reportFragment.Value); } else if (id == DrawerListAdapter.ReportsWeekPageId) { drawerAdapter.ExpandCollapse (DrawerListAdapter.ReportsPageId); SupportActionBar.SetTitle (Resource.String.MainDrawerReportsWeek); reportFragment.Value.ZoomLevel = ZoomLevel.Week; OpenFragment (reportFragment.Value); } else if (id == DrawerListAdapter.ReportsMonthPageId) { drawerAdapter.ExpandCollapse (DrawerListAdapter.ReportsPageId); SupportActionBar.SetTitle (Resource.String.MainDrawerReportsMonth); reportFragment.Value.ZoomLevel = ZoomLevel.Month; OpenFragment (reportFragment.Value); } else if (id == DrawerListAdapter.ReportsYearPageId) { drawerAdapter.ExpandCollapse (DrawerListAdapter.ReportsPageId); SupportActionBar.SetTitle (Resource.String.MainDrawerReportsYear); reportFragment.Value.ZoomLevel = ZoomLevel.Year; OpenFragment (reportFragment.Value); } else if (id == DrawerListAdapter.FeedbackPageId) { SupportActionBar.SetTitle (Resource.String.MainDrawerFeedback); drawerAdapter.ExpandCollapse (DrawerListAdapter.FeedbackPageId); OpenFragment (feedbackFragment.Value); } else { SupportActionBar.SetTitle (Resource.String.MainDrawerTimer); OpenFragment (trackingFragment.Value); drawerAdapter.ExpandCollapse (DrawerListAdapter.TimerPageId); } SetMenuSelection (drawerAdapter.GetItemPosition (id)); pageStack.Remove (id); pageStack.Add (id); // Make sure we don't store the timer page as the first page (this is implied) if (pageStack.Count == 1 && id == DrawerListAdapter.TimerPageId) { pageStack.Clear (); } } private void OpenFragment (Fragment fragment) { var old = FragmentManager.FindFragmentById (Resource.Id.ContentFrameLayout); if (old == null) { FragmentManager.BeginTransaction () .Add (Resource.Id.ContentFrameLayout, fragment) .Commit (); } else if (old != fragment) { // The detach/attach is a workaround for https://code.google.com/p/android/issues/detail?id=42601 FragmentManager.BeginTransaction () .Detach (old) .Replace (Resource.Id.ContentFrameLayout, fragment) .Attach (fragment) .Commit (); } } private void OnDrawerListViewItemClick (object sender, ListView.ItemClickEventArgs e) { // If tap outside options just close drawer if (e.Id == -1) { DrawerLayout.CloseDrawers (); return; } // Configure timer component for selected page: if (e.Id != DrawerListAdapter.TimerPageId) { ToolbarMode = MainDrawerActivity.ToolbarModes.Normal; } else { ToolbarMode = MainDrawerActivity.ToolbarModes.Timer; } if (e.Id == DrawerListAdapter.TimerPageId) { OpenPage (DrawerListAdapter.TimerPageId); } else if (e.Id == DrawerListAdapter.LogoutPageId) { var authManager = ServiceContainer.Resolve<AuthManager> (); authManager.Forget (); StartAuthActivity (); } else if (e.Id == DrawerListAdapter.ReportsPageId) { OpenPage (DrawerListAdapter.ReportsPageId); } else if (e.Id == DrawerListAdapter.ReportsWeekPageId) { OpenPage (DrawerListAdapter.ReportsWeekPageId); } else if (e.Id == DrawerListAdapter.ReportsMonthPageId) { OpenPage (DrawerListAdapter.ReportsMonthPageId); } else if (e.Id == DrawerListAdapter.ReportsYearPageId) { OpenPage (DrawerListAdapter.ReportsYearPageId); } else if (e.Id == DrawerListAdapter.SettingsPageId) { OpenPage (DrawerListAdapter.SettingsPageId); } else if (e.Id == DrawerListAdapter.FeedbackPageId) { OpenPage (DrawerListAdapter.FeedbackPageId); } DrawerLayout.CloseDrawers (); } protected void SyncStarted (SyncStartedMessage msg) { syncRetryButton.Enabled = false; syncStatus = syncing; syncStatusText.SetText (Resource.String.CurrentlySyncingStatusText); } private void SyncFinished (SyncFinishedMessage msg) { syncRetryButton.Enabled = true; if (msg.FatalError != null) { syncStatus = syncFatalError; } else if (msg.HadErrors) { syncStatus = syncHadErrors; } else { syncStatus = syncSuccessful; } lastSyncInMillis = Toggl.Phoebe.Time.Now.Ticks / TimeSpan.TicksPerMillisecond; UpdateSyncStatus (); } private void OnSyncRetryClick (object sender, EventArgs e) { var syncManager = ServiceContainer.Resolve<ISyncManager> (); syncManager.Run (); } private void UpdateSyncStatus () { if (syncStatus == syncing) { syncStatusText.SetText (Resource.String.CurrentlySyncingStatusText); } else if (syncStatus == syncHadErrors) { syncStatusText.SetText (Resource.String.LastSyncHadErrors); } else if (syncStatus == syncFatalError) { syncStatusText.SetText (Resource.String.LastSyncFatalError); } else { syncStatusText.Text = String.Format (Resources.GetString (Resource.String.LastSyncStatusText), ResolveLastSyncTime ()); } handler.RemoveCallbacks (UpdateSyncStatus); handler.PostDelayed (UpdateSyncStatus, DateUtils.MinuteInMillis); } private String ResolveLastSyncTime () { var NowInMillis = Toggl.Phoebe.Time.Now.Ticks / TimeSpan.TicksPerMillisecond; if (NowInMillis - lastSyncInMillis < DateUtils.MinuteInMillis) { return Resources.GetString (Resource.String.LastSyncJustNow); } return DateUtils.GetRelativeTimeSpanString (lastSyncInMillis, NowInMillis, 0L); } public TimerComponent Timer { get { return barTimer; } } public enum ToolbarModes { Normal, Timer } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using ALinq.Mapping; using ALinq.SqlClient; namespace ALinq.Oracle { class OracleFactory : SqlFactory { internal OracleFactory(ITypeSystemProvider typeProvider, MetaModel model) : base(typeProvider, model) { } internal override SqlExpression DATALENGTH(SqlExpression expr) { return this.FunctionCall(typeof(int), "LENGTH", new[] { expr }, expr.SourceExpression); } internal override SqlExpression String_Length(SqlExpression expr) { return this.FunctionCall(typeof(int), "LENGTH", new[] { expr }, expr.SourceExpression); } internal override SqlExpression DateTime_Add(SqlMethodCall mc) { var arg = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(10000000, mc.SourceExpression)); var div = Binary(SqlNodeType.Div, arg, ValueFromObject(24 * 60 * 60, mc.SourceExpression)); mc.Arguments[0] = div; return DateTime_AddDays(mc); } internal override SqlExpression DateTime_Subtract(SqlMethodCall mc) { var arg = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(10000000, mc.SourceExpression)); var div = Binary(SqlNodeType.Div, arg, ValueFromObject(24 * 60 * 60, mc.SourceExpression)); mc.Arguments[0] = div; return DateTime_SubtractDays(mc); } internal override SqlExpression DateTime_SubtractDays(SqlMethodCall mc) { var s = mc.SourceExpression; var args = new[] { mc.Object, VariableFromName("-", s), mc.Arguments[0] }; var func = FunctionCall(typeof(DateTime), string.Empty, args, s); func.Comma = false; return func; } internal override SqlExpression DateTime_AddDays(SqlMethodCall mc) { var s = mc.SourceExpression; var args = new[] { mc.Object, VariableFromName("+", s), mc.Arguments[0] }; var func = FunctionCall(typeof(DateTime), string.Empty, args, s); func.Comma = false; return func; } internal override SqlExpression DateTime_AddMonths(SqlMethodCall mc) { var args = new[] { mc.Object, mc.Arguments[0] }; return FunctionCall(mc.ClrType, "ADD_MONTHS", args, mc.SourceExpression); } internal override SqlExpression DateTime_AddYears(SqlMethodCall mc) { var mul = Binary(SqlNodeType.Mul, mc.Arguments[0], ValueFromObject(12, mc.SourceExpression)); mc.Arguments[0] = mul; return DateTime_AddMonths(mc); } internal override SqlExpression DateTime_AddHours(SqlMethodCall mc) { var div = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(24, mc.SourceExpression)); mc.Arguments[0] = div; return DateTime_AddDays(mc); } internal override SqlExpression DateTime_AddMinutes(SqlMethodCall mc) { var div = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(24 * 60, mc.SourceExpression)); mc.Arguments[0] = div; return DateTime_AddDays(mc); } internal override SqlExpression DateTime_AddSeconds(SqlMethodCall mc) { var div = Binary(SqlNodeType.Div, mc.Arguments[0], ValueFromObject(24 * 60 * 60, mc.SourceExpression)); mc.Arguments[0] = div; return DateTime_AddDays(mc); } internal override SqlExpression DateTime_ToString(SqlMethodCall mc) { var args = new[] { mc.Object, mc.Arguments[0] }; return FunctionCall(mc.ClrType, "TO_CHAR", args, mc.SourceExpression); } internal override SqlExpression DateTime_Date(SqlMember m, SqlExpression expr) { var s = expr.SourceExpression; var func = new SqlFunctionCall(typeof(string), TypeProvider.From(typeof(string)), "TO_CHAR", new[] { expr, ValueFromObject("YYYY-MM-DD", s) }, s); //return func; return new SqlFunctionCall(typeof(DateTime), TypeProvider.From(typeof(DateTime)), "TO_DATE", new[] { func, ValueFromObject("YYYY-MM-DD", s) }, s); } internal override SqlExpression Math_Truncate(SqlMethodCall mc) { var args = new[] { mc.Arguments[0], ValueFromObject(0, false, mc.SourceExpression), ValueFromObject(1, false, mc.SourceExpression) }; return FunctionCall(mc.Method.ReturnType, "TRUNC", mc.Arguments, mc.SourceExpression); } internal override SqlExpression Math_Cosh(SqlMethodCall mc, Expression sourceExpression) { return FunctionCall(typeof(double), "COSH", new[] { mc.Arguments[0] }, sourceExpression); } internal override SqlExpression Math_Sinh(SqlMethodCall mc, Expression sourceExpression) { return FunctionCall(typeof(double), "SINH", new[] { mc.Arguments[0] }, sourceExpression); } internal override SqlExpression String_Substring(SqlMethodCall mc) { SqlExpression[] args; if (mc.Arguments.Count != 1) { if (mc.Arguments.Count == 2) { args = new[] { mc.Object, this.Add(mc.Arguments[0], 1), mc.Arguments[1] }; return this.FunctionCall(typeof(string), "SUBSTR", args, mc.SourceExpression); } throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc);//GetMethodSupportException(mc); } args = new[] { mc.Object, this.Add(mc.Arguments[0], 1), this.CLRLENGTH(mc.Object) }; return this.FunctionCall(typeof(string), "SUBSTR", args, mc.SourceExpression); } internal override SqlExpression String_GetChar(SqlMethodCall mc, Expression sourceExpression) { if (mc.Arguments.Count != 1) { throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc); } var args = new[] { mc.Object, Add(mc.Arguments[0], 1), ValueFromObject(1, false, sourceExpression) }; return FunctionCall(typeof(char), "SUBSTR", args, sourceExpression); } internal override SqlExpression String_IndexOf(SqlMethodCall mc, Expression sourceExpression) { if (mc.Arguments.Count == 1) { if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } var when = new SqlWhen(Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)), ValueFromObject(0, sourceExpression)); SqlExpression expression9 = Subtract(FunctionCall(typeof(int), "INSTR", new[] { mc.Arguments[0], mc.Object }, sourceExpression), 1); return SearchedCase(new[] { when }, expression9, sourceExpression); } if (mc.Arguments.Count == 2) { if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } if (mc.Arguments[1].ClrType == typeof(StringComparison)) { throw SqlClient.Error.IndexOfWithStringComparisonArgNotSupported(); } SqlExpression expression10 = Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)); SqlWhen when2 = new SqlWhen(AndAccumulate(expression10, Binary(SqlNodeType.LE, Add(mc.Arguments[1], 1), CLRLENGTH(mc.Object))), mc.Arguments[1]); SqlExpression expression11 = Subtract(FunctionCall(typeof(int), "INSTR", new[] { mc.Arguments[0], mc.Object, Add(mc.Arguments[1], 1) }, sourceExpression), 1); return SearchedCase(new[] { when2 }, expression11, sourceExpression); } if (mc.Arguments.Count != 3) { SqlClient.Error.MethodHasNoSupportConversionToSql(mc); } if ((mc.Arguments[0] is SqlValue) && (((SqlValue)mc.Arguments[0]).Value == null)) { throw Error.ArgumentNull("value"); } if (mc.Arguments[2].ClrType == typeof(StringComparison)) { throw SqlClient.Error.IndexOfWithStringComparisonArgNotSupported(); } SqlExpression left = Binary(SqlNodeType.EQ, CLRLENGTH(mc.Arguments[0]), ValueFromObject(0, sourceExpression)); var when3 = new SqlWhen(AndAccumulate(left, Binary(SqlNodeType.LE, Add(mc.Arguments[1], 1), CLRLENGTH(mc.Object))), mc.Arguments[1]); var expression13 = FunctionCall(typeof(string), "SUBSTR", new[] { mc.Object, ValueFromObject(1, false, sourceExpression), Add(new[] { mc.Arguments[1], mc.Arguments[2] }) }, sourceExpression); var @else = Subtract(FunctionCall(typeof(int), "INSTR", new[] { mc.Arguments[0], expression13, Add(mc.Arguments[1], 1) }, sourceExpression), 1); return SearchedCase(new[] { when3 }, @else, sourceExpression); } internal override SqlExpression UNICODE(Type clrType, SqlUnary uo) { return FunctionCall(clrType, TypeProvider.From(typeof(int)), "ASCII", new[] { uo.Operand }, uo.SourceExpression); } internal override MethodSupport GetConvertMethodSupport(SqlMethodCall mc) { if ((mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(Convert))) && (mc.Arguments.Count == 1)) { switch (mc.Method.Name) { case "ToBoolean": case "ToDecimal": //case "ToByte": case "ToChar": case "ToDouble": case "ToInt16": case "ToInt32": case "ToInt64": case "ToSingle": case "ToString": return MethodSupport.Method; case "ToDateTime": if ((mc.Arguments[0].ClrType != typeof(string)) && (mc.Arguments[0].ClrType != typeof(DateTime))) { return MethodSupport.MethodGroup; } return MethodSupport.Method; } } return MethodSupport.None; } internal override SqlExpression TranslateConvertStaticMethod(SqlMethodCall mc) { if (mc.Arguments.Count != 1) { return null; } var expr = mc.Arguments[0]; Type type; switch (mc.Method.Name) { case "ToBoolean": type = typeof(bool); break; case "ToDecimal": type = typeof(decimal); break; case "ToByte": type = typeof(byte); break; case "ToChar": type = typeof(char); if (expr.SqlType.IsChar) { TypeProvider.From(type, 1); } break; case "ToDateTime": { var nonNullableType = TypeSystem.GetNonNullableType(expr.ClrType); if ((nonNullableType != typeof(string)) && (nonNullableType != typeof(DateTime))) { throw SqlClient.Error.ConvertToDateTimeOnlyForDateTimeOrString(); } type = typeof(DateTime); break; } case "ToDouble": type = typeof(double); break; case "ToInt16": type = typeof(short); break; case "ToInt32": type = typeof(int); break; case "ToInt64": type = typeof(long); break; case "ToSingle": type = typeof(float); break; case "ToString": type = typeof(string); break; case "ToSByte": type = typeof(sbyte); break; default: throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc); } if ((TypeProvider.From(type) != expr.SqlType) || ((expr.ClrType == typeof(bool)) && (type == typeof(int)))) { if (type != typeof(DateTime)) return ConvertTo(type, TypeProvider.From(typeof(decimal)), expr); return ConvertTo(type, expr); } if ((type != expr.ClrType) && (TypeSystem.GetNonNullableType(type) == TypeSystem.GetNonNullableType(expr.ClrType))) { return new SqlLift(type, expr, expr.SourceExpression); } return expr; } internal override SqlExpression DATEPART(string partName, SqlExpression expr) { var args = new[] { expr }; var s = expr.SourceExpression; SqlExpression arg; IProviderType sqlType = null; Type clrType = typeof(int); sqlType = TypeProvider.From(typeof(string)); switch (partName.ToUpper()) { case "HOUR": arg = ValueFromObject("HH24", true, s); break; case "MINUTE": arg = ValueFromObject("MI", true, s); break; case "SECOND": arg = ValueFromObject("SS", true, s); break; case "DAY": args = new[] { VariableFromName("DAY FROM", s), expr }; return new SqlFunctionCall(clrType, sqlType, "EXTRACT", args, s) { Comma = false }; case "MONTH": args = new[] { VariableFromName("MONTH FROM", s), expr }; return new SqlFunctionCall(clrType, sqlType, "EXTRACT", args, s) { Comma = false }; case "YEAR": args = new[] { VariableFromName("YEAR FROM", s), expr }; return new SqlFunctionCall(clrType, sqlType, "EXTRACT", args, s) { Comma = false }; case "DAYOFWEEK": clrType = typeof(DayOfWeek); sqlType = TypeProvider.From(typeof(int)); arg = ValueFromObject("D", true, s); var func = new SqlFunctionCall(clrType, sqlType, "TO_CHAR", new[] { expr, arg }, s); return new SqlBinary(SqlNodeType.Sub, clrType, sqlType, func, ValueFromObject(1, s)); case "DAYOFYEAR": arg = ValueFromObject("DDD", true, s); break; case "TIMEOFDAY": arg = ValueFromObject("DDD", true, s); break; default: throw SqlClient.Error.MethodHasNoSupportConversionToSql(partName); } return new SqlFunctionCall(clrType, sqlType, "TO_CHAR", new[] { expr, arg }, s); } internal override SqlExpression DateTime_DayOfWeek(SqlMember m, SqlExpression expr) { return this.DATEPART(m.Member.Name, expr); } internal override SqlNode DateTime_TimeOfDay(SqlMember member, SqlExpression expr) { var h = DATEPART("HOUR", expr); var m = DATEPART("MINUTE", expr); var s = DATEPART("SECOND", expr); h = Multiply(ConvertToBigint(h), 0x861c46800L); m = Multiply(ConvertToBigint(m), 0x23c34600L); s = Multiply(ConvertToBigint(s), 0x989680L); return ConvertTo(typeof(TimeSpan), Add(new[] { h, m, s })); } internal override SqlExpression MakeCoalesce(SqlExpression left, SqlExpression right, Type type, Expression sourceExpression) { return FunctionCall(type, "NVL", new[] { left, right }, sourceExpression); } internal override SqlExpression Math_Log(SqlMethodCall mc) { Debug.Assert(mc.Method.Name == "Log"); if (mc.Arguments.Count == 1) { //mc.Arguments.Add(sql.Value(typeof(int),)) var value = ValueFromObject(Math.E, mc.SourceExpression); mc.Arguments.Insert(0, value); } return CreateFunctionCallStatic2(typeof(double), "LOG", mc.Arguments, mc.SourceExpression); } internal override SqlExpression Math_Log10(SqlMethodCall mc) { Debug.Assert(mc.Arguments.Count == 1); var value = ValueFromObject(10, mc.SourceExpression); mc.Arguments.Insert(0, value); return CreateFunctionCallStatic2(mc.ClrType, "LOG", mc.Arguments, mc.SourceExpression); } internal override MethodSupport GetSqlMethodsMethodSupport(SqlMethodCall mc) { if (mc.Method.Name.StartsWith("DateDiff")) return MethodSupport.None; return base.GetSqlMethodsMethodSupport(mc); } internal override MethodSupport GetDateTimeMethodSupport(SqlMethodCall mc) { if (!mc.Method.IsStatic && (mc.Method.DeclaringType == typeof(DateTime))) { switch (mc.Method.Name) { case "Subtract": return MethodSupport.Method; break; } } return base.GetDateTimeMethodSupport(mc); } } }
// // assembly: System // namespace: System.Text.RegularExpressions // file: interval.cs // // author: Dan Lewis ([email protected]) // (c) 2002 // // 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; namespace System.Text.RegularExpressions { struct Interval : IComparable { public int low; public int high; public bool contiguous; public static Interval Empty { get { Interval i; i.low = 0; i.high = i.low - 1; i.contiguous = true; return i; } } public static Interval Entire { get { return new Interval (Int32.MinValue, Int32.MaxValue); } } public Interval (int low, int high) { if (low > high) { int t = low; low = high; high = t; } this.low = low; this.high = high; this.contiguous = true; } public bool IsDiscontiguous { get { return !contiguous; } } public bool IsSingleton { get { return contiguous && low == high; } } public bool IsRange { get { return !IsSingleton && !IsEmpty; } } public bool IsEmpty { get { return low > high; } } public int Size { get { if (IsEmpty) return 0; return high - low + 1; } } public bool IsDisjoint (Interval i) { if (IsEmpty || i.IsEmpty) return true; return !(low <= i.high && i.low <= high); } public bool IsAdjacent (Interval i) { if (IsEmpty || i.IsEmpty) return false; return low == i.high + 1 || high == i.low - 1; } public bool Contains (Interval i) { if (!IsEmpty && i.IsEmpty) return true; if (IsEmpty) return false; return low <= i.low && i.high <= high; } public bool Contains (int i) { return low <= i && i <= high; } public bool Intersects (Interval i) { if (IsEmpty || i.IsEmpty) return false; return ((Contains (i.low) && !Contains (i.high)) || (Contains (i.high) && !Contains (i.low))); } public void Merge (Interval i) { if (i.IsEmpty) return; if (IsEmpty) { this.low = i.low; this.high = i.high; } if (i.low < low) low = i.low; if (i.high > high) high = i.high; } public void Intersect (Interval i) { if (IsDisjoint (i)) { low = 0; high = low - 1; return; } if (i.low > low) low = i.low; if (i.high > high) high = i.high; } public int CompareTo (object o) { return low - ((Interval)o).low; } public new string ToString () { if (IsEmpty) return "(EMPTY)"; else if (!contiguous) return "{" + low + ", " + high + "}"; else if (IsSingleton) return "(" + low + ")"; else return "(" + low + ", " + high + ")"; } } class IntervalCollection : ICollection, IEnumerable { public IntervalCollection () { intervals = new ArrayList (); } public Interval this[int i] { get { return (Interval)intervals[i]; } set { intervals[i] = value; } } public void Add (Interval i) { intervals.Add (i); } public void Clear () { intervals.Clear (); } public void Sort () { intervals.Sort (); } public void Normalize () { intervals.Sort (); int j = 0; while (j < intervals.Count - 1) { Interval a = (Interval)intervals[j]; Interval b = (Interval)intervals[j + 1]; if (!a.IsDisjoint (b) || a.IsAdjacent (b)) { a.Merge (b); intervals[j] = a; intervals.RemoveAt (j + 1); } else ++ j; } } public delegate double CostDelegate (Interval i); public IntervalCollection GetMetaCollection (CostDelegate cost_del) { IntervalCollection meta = new IntervalCollection (); Normalize (); Optimize (0, Count - 1, meta, cost_del); meta.intervals.Sort (); return meta; } private void Optimize (int begin, int end, IntervalCollection meta, CostDelegate cost_del) { Interval set; set.contiguous = false; int best_set_begin = -1; int best_set_end = -1; double best_set_cost = 0; for (int i = begin; i <= end; ++ i) { set.low = this[i].low; double cost = 0.0; for (int j = i; j <= end; ++ j) { set.high = this[j].high; cost += cost_del (this[j]); double set_cost = cost_del (set); if (set_cost < cost && cost > best_set_cost) { best_set_begin = i; best_set_end = j; best_set_cost = cost; } } } if (best_set_begin < 0) { // didn't find an optimal set: add original members for (int i = begin; i <= end; ++ i) meta.Add (this[i]); } else { // found set: add it ... set.low = this[best_set_begin].low; set.high = this[best_set_end].high; meta.Add (set); // ... and optimize to the left and right if (best_set_begin > begin) Optimize (begin, best_set_begin - 1, meta, cost_del); if (best_set_end < end) Optimize (best_set_end + 1, end, meta, cost_del); } } // ICollection implementation public int Count { get { return intervals.Count; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return intervals; } } public void CopyTo (Array array, int index) { foreach (Interval i in intervals) { if (index > array.Length) break; array.SetValue (i, index ++); } } // IEnumerator implementation public IEnumerator GetEnumerator () { return new Enumerator (intervals); } private class Enumerator : IEnumerator { public Enumerator (IList list) { this.list = list; Reset (); } public object Current { get { if (ptr >= list.Count) throw new InvalidOperationException (); return list[ptr]; } } public bool MoveNext () { if (ptr > list.Count) throw new InvalidOperationException (); return ++ ptr < list.Count; } public void Reset () { ptr = -1; } private IList list; private int ptr; } // private fields private ArrayList intervals; } }
using System; using System.Threading.Tasks; using Journalist.EventStore.Connection; using Journalist.EventStore.Journal; using Journalist.EventStore.Notifications; using Journalist.EventStore.Notifications.Channels; using Journalist.EventStore.Notifications.Listeners; using Journalist.EventStore.Notifications.Types; using Journalist.EventStore.UnitTests.Infrastructure.TestData; using Moq; using Ploeh.AutoFixture.Xunit2; using Xunit; namespace Journalist.EventStore.UnitTests.Notifications.Listeners { public class NotificationListenerSubscriptionTest { [Theory, NotificationListenerSubscriptionData] public void Start_NotifyListener( [Frozen] Mock<INotificationListener> listenerMock, IEventStoreConnection connection, NotificationListenerSubscription subscription) { subscription.Start(connection); listenerMock.Verify(self => self.OnSubscriptionStarted(subscription), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public void Stop_WhenSubscriptionHasNotBeenStarted_Throws( [Frozen] Mock<INotificationListener> listenerMock, NotificationListenerSubscription subscription, INotification notification) { Assert.Throws<InvalidOperationException>(() => subscription.Stop()); } [Theory, NotificationListenerSubscriptionData] public void Stop_NotifyListener( [Frozen] Mock<INotificationListener> listenerMock, IEventStoreConnection connection, NotificationListenerSubscription subscription, INotification notification) { subscription.Start(connection); subscription.Stop(); listenerMock.Verify(self => self.OnSubscriptionStopped(), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public async Task HandleNotificationAsync_WhenSubscriptionStarted_PropagatesNotificationToTheListener( [Frozen] Mock<INotificationListener> listenerMock, IEventStoreConnection connection, NotificationListenerSubscription subscription, EventStreamUpdated notification) { subscription.Start(connection); await subscription.HandleNotificationAsync(notification); listenerMock.Verify( self => self.On(notification), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public async Task HandleNotificationAsync_WhenNotificationNotAddressedToConsumer_PropagatesNotificationToTheListener( [Frozen] Mock<INotificationListener> listenerMock, IEventStoreConnection connection, NotificationListenerSubscription subscription, EventStreamUpdated notification, EventStreamReaderId consumerId) { subscription.Start(connection); await subscription.HandleNotificationAsync(notification.SendTo(listenerMock.Object)); listenerMock.Verify( self => self.On(notification), Times.Never()); } [Theory, NotificationListenerSubscriptionData] public async Task HandleNotificationAsync_WhenNotificationAddressedToConsumer_PropagatesNotificationToTheListener( [Frozen] Mock<INotificationListener> listenerMock, [Frozen] EventStreamReaderId consumerId, IEventStoreConnection connection, NotificationListenerSubscription subscription, EventStreamUpdated notification) { var addressedNotification = (EventStreamUpdated)notification.SendTo(listenerMock.Object); subscription.Start(connection); await subscription.HandleNotificationAsync(addressedNotification); listenerMock.Verify( self => self.On(addressedNotification), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public async Task HandleNotificationAsync_WhenSubscriptionDidNotStart_NotPropagatesNotificationToTheListener( [Frozen] Mock<INotificationListener> listenerMock, NotificationListenerSubscription subscription, EventStreamUpdated notification) { await subscription.HandleNotificationAsync(notification); listenerMock.Verify( self => self.On(notification), Times.Never()); } [Theory, NotificationListenerSubscriptionData] public async Task HandleNotificationAsync__WhenSubscriptionStoped_PropagateNotificationToTheListener( [Frozen] Mock<INotificationListener> listenerMock, IEventStoreConnection connection, NotificationListenerSubscription subscription, EventStreamUpdated notification) { subscription.Start(connection); await subscription.HandleNotificationAsync(notification); subscription.Stop(); await subscription.HandleNotificationAsync(notification); listenerMock.Verify( self => self.On(notification), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public void CreateSubscriptionConsumerAsync_WhenSubscriptionWasStarted_UseConnection( [Frozen] EventStreamReaderId consumerId, Mock<IEventStoreConnection> connectionMock, NotificationListenerSubscription subscription, string streamName) { subscription.Start(connectionMock.Object); subscription.CreateSubscriptionConsumerAsync(streamName); connectionMock.Verify(self => self.CreateStreamConsumerAsync( It.IsAny<Action<IEventStreamConsumerConfiguration>>())); } [Theory, NotificationListenerSubscriptionData] public async Task CreateSubscriptionConsumerAsync_WhenSubscriptionWasNotStarted_Throws( [Frozen] EventStreamReaderId consumerId, NotificationListenerSubscription subscription, string streamName) { await Assert.ThrowsAsync<InvalidOperationException>( () => subscription.CreateSubscriptionConsumerAsync(streamName)); } [Theory, NotificationListenerSubscriptionData] public async Task DefferNotificationAsync_SendAddressedNotification( [Frozen] Mock<INotificationsChannel> channelMock, [Frozen] Mock<INotification> receivedNotificationMock, INotification deferredNotification, IEventStoreConnection connection, INotificationListener listener, NotificationListenerSubscription subscription) { receivedNotificationMock .Setup(self => self.SendTo(listener)) .Returns(deferredNotification); subscription.Start(connection); await subscription.RetryNotificationProcessingAsync(receivedNotificationMock.Object); channelMock .Verify(self => self.SendAsync( deferredNotification, It.IsAny<TimeSpan>()), Times.Once()); } [Theory, NotificationListenerSubscriptionData] public async Task DefferNotificationAsync_WhenAllAttemptsFailed_SendNotificationToFailedAsync( [Frozen] Mock<INotificationsChannel> channelMock, [Frozen] Mock<INotification> receivedNotificationMock, INotification deferredNotification, IEventStoreConnection connection, INotificationListener listener, NotificationListenerSubscription subscription) { receivedNotificationMock .Setup(self => self.DeliveryCount) .Returns(100); subscription.Start(connection); await subscription.RetryNotificationProcessingAsync(receivedNotificationMock.Object); channelMock .Verify(self => self.SendToFailedNotificationsAsync( deferredNotification), Times.Once()); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Reflection; using System.Diagnostics.Contracts; //using System.Runtime.CompilerServices; namespace System.Collections.Generic { // Summary: // Represents a collection of objects that can be individually accessed by index. // // Type parameters: // T: // The type of elements in the list. [ContractClass(typeof(IListContract<>))] public interface IList<T> : ICollection<T> { // Summary: // Gets or sets the element at the specified index. // // Parameters: // index: // The zero-based index of the element to get or set. // // Returns: // The element at the specified index. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The property is set and the System.Collections.Generic.IList<T> is read-only. T this[int index] { get; set; } // Summary: // Determines the index of a specific item in the System.Collections.Generic.IList<T>. // // Parameters: // item: // The object to locate in the System.Collections.Generic.IList<T>. // // Returns: // The index of item if found in the list; otherwise, -1. [Pure] int IndexOf(T item); // // Summary: // Inserts an item to the System.Collections.Generic.IList<T> at the specified // index. // // Parameters: // index: // The zero-based index at which item should be inserted. // // item: // The object to insert into the System.Collections.Generic.IList<T>. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void Insert(int index, T item); // // Summary: // Removes the System.Collections.Generic.IList<T> item at the specified index. // // Parameters: // index: // The zero-based index of the item to remove. // // Exceptions: // System.ArgumentOutOfRangeException: // index is not a valid index in the System.Collections.Generic.IList<T>. // // System.NotSupportedException: // The System.Collections.Generic.IList<T> is read-only. void RemoveAt(int index); } [ContractClassFor(typeof(IList<>))] abstract class IListContract<T> : IList<T> { #region IList<T> Members T IList<T>.this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); return default(T); } set { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); } } [Pure] int IList<T>.IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < this.Count); throw new NotImplementedException(); } void IList<T>.Insert(int index, T item) { Contract.Requires(index >= 0); Contract.Requires(index <= this.Count); } void IList<T>.RemoveAt(int index) { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); Contract.Ensures(this.Count == Contract.OldValue(this.Count) - 1); } #endregion #region ICollection<T> Members public int Count { get { throw new NotImplementedException(); } } bool ICollection<T>.IsReadOnly { get { throw new NotImplementedException(); } } void ICollection<T>.Add(T item) { // Contract.Ensures(Count == Contract.OldValue(Count) + 1); // cannot be seen by our tools as there is no IList<T>.Add throw new NotImplementedException(); } void ICollection<T>.Clear() { throw new NotImplementedException(); } bool ICollection<T>.Contains(T item) { throw new NotImplementedException(); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } bool ICollection<T>.Remove(T item) { throw new NotImplementedException(); } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members public object[] Model { get { throw new NotImplementedException(); } } #endregion } }
using System.Linq; using hw.DebugFormatter; using hw.UnitTest; using NUnit.Framework; using ReniUI.Formatting; namespace ReniUI.Test { [UnitTest] [TestFixture] [FormattingSimple] public sealed class Formatting : DependenceProvider { [Test] [UnitTest] public void HalfList() { const string text = @"System: ( ssssss"; const string expectedText = text; text.SimpleTest(expectedText, 12, 1); } [Test] [UnitTest] public void LabeledList() { const string text = @"llll:(aaaaa;llll:bbbbb;ccccc)"; const string expectedText = @"llll: ( aaaaa; llll: bbbbb; ccccc )"; text.SimpleTest(expectedText, 12, 1); } [Test] [UnitTest] public void FlatList2() { const string text = @"aaaaa;ccccc"; const string expectedText = @"aaaaa; ccccc"; text.SimpleTest(expectedText ); } [Test] [UnitTest] public void ListEndsWithListToken() { const string text = @"(aaaaa;bbbbb;ccccc;)"; const string expectedText = @"( aaaaa; bbbbb; ccccc; )"; var compiler = CompilerBrowser.FromText(text); var newSource = compiler.Reformat ( new ReniUI.Formatting.Configuration {MaxLineLength = 20, EmptyLineLimit = 1}.Create() ); Tracer.Assert(newSource == expectedText, "\n\"" + newSource + "\""); } [Test] [UnitTest] public void ListSeparatorAtEnd() { const string text = @"aaaaa;"; const string expectedText = @"aaaaa;"; var compiler = CompilerBrowser.FromText(text); var newSource = compiler.FlatFormat(false); Tracer.Assert(newSource == expectedText, "\n\"" + newSource + "\""); } [Test] [UnitTest] public void ListLineBreakTest2() { const string text = @"aaaaa;bbbbb"; const string expectedText = @"aaaaa; bbbbb"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListLineBreakTest3() { const string text = @"aaaaa;bbbbb;ccccc"; const string expectedText = @"aaaaa; bbbbb; ccccc"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListTest1() { const string text = @"aaaaa"; const string expectedText = @"aaaaa"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListTest2() { const string text = @"aaaaa;bbbbb"; const string expectedText = @"aaaaa; bbbbb"; text.SimpleTest(expectedText, 20, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTest1() { const string text = @"lllll:bbbbb"; const string expectedText = @"lllll: bbbbb"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTest2() { const string text = @"aaaaa;llll:bbbbb"; const string expectedText = @"aaaaa; llll: bbbbb"; text.SimpleTest(expectedText, 15, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTest3() { const string text = @"aaaaa;llll:bbbbb;ccccc"; const string expectedText = @"aaaaa; llll: bbbbb; ccccc"; text.SimpleTest(expectedText, 20, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTestA2() { const string text = @"aaaaa;llll:bbbbb"; const string expectedText = @"aaaaa; llll: bbbbb"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTestA3() { const string text = @"aaaaa;llll:bbbbb;ccccc"; const string expectedText = @"aaaaa; llll: bbbbb; ccccc"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTestA4() { const string text = @"aaaaa;aaaaa;llll:bbbbb;ccccc;ddddd"; const string expectedText = @"aaaaa; aaaaa; llll: bbbbb; ccccc; ddddd"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListWithDeclarationLineBreakTestAA4() { const string text = @"aaaaa;aaaaa;llll:bbbbb;mmmmm:22222;ccccc;ddddd"; const string expectedText = @"aaaaa; aaaaa; llll: bbbbb; mmmmm: 22222; ccccc; ddddd"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void ListWithDeclarationTest1() { const string text = @"lllll:bbbbb"; const string expectedText = @"lllll: bbbbb"; text.SimpleTest(expectedText, emptyLineLimit: 1); } [Test] [UnitTest] public void ListWithDeclarationTest2() { const string text = @"aaaaa;llll:bbbbb"; const string expectedText = @"aaaaa; llll: bbbbb"; text.SimpleTest(expectedText, emptyLineLimit: 1); } [Test] [UnitTest] public void ListWithDeclarationTest3() { const string text = @"aaaaa;llll:bbbbb;ccccc"; const string expectedText = @"aaaaa; llll: bbbbb; ccccc"; text.SimpleTest(expectedText, emptyLineLimit: 1); } [Test] [UnitTest] public void MultilineBreakTest() { const string text = @"(ccccc,aaaaa bbbbb, )"; var expectedText = @"( ccccc, aaaaa bbbbb, )".Replace("\r\n", "\n"); text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void MultilineBreakTest1() { const string text = @"(ccccc,aaaaa bbbbb)"; var expectedText = @"( ccccc, aaaaa bbbbb )".Replace("\r\n", "\n"); text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void Reformat() { const string text = @"systemdata:{1 type instance(); Memory:((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) );}; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print "; var expectedText = @"systemdata: { 1 type instance(); Memory: ((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then(^ body(), repeat(^)); }; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print" .Replace("\r\n", "\n"); text.SimpleTest(expectedText, 100, 0); } [Test] [UnitTest] public void Reformat1_120() { const string text = @"systemdata:{1 type instance(); Memory:((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) );}; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print "; var expectedText = @"systemdata: { 1 type instance(); Memory: ((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) ); }; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print"; text.SimpleTest(expectedText, 120, 1); } [Test] [UnitTest] public void Reformat1_120Temp() { const string text = @"(aaaaa ( ))"; var expectedText = @"( aaaaa ( ) )".Replace("\r\n", "\n"); text.SimpleTest(expectedText, 120, 1); } [Test] [UnitTest] public void Reformat2() { const string text = @"systemdata: { Memory:((0 type *(125)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; }; "; const string expectedText = @"systemdata: { Memory: ((0 type *(125)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; };"; text.SimpleTest(expectedText, 60, 0); } [Test] [UnitTest] public void ReformatWithComments() { const string Text = @" X1_fork: object ( X1_FullDump: ( function ( string('(') * X1_L X1_dump(arg) * ',' * X1_R X1_dump(arg) * ')'; ) ); X1_dump:= ( function ( arg = 0 then string('...') else X1_FullDump(integer(arg - 1)) ) ) ); "; var compiler = CompilerBrowser.FromText(Text); var newSource = compiler.Reformat ( new ReniUI.Formatting.Configuration {EmptyLineLimit = 1}.Create ()); var lineCount = newSource.Count(item => item == '\n'); Tracer.Assert(lineCount == 22, "\n\"" + newSource + "\""); } [Test] [UnitTest] public void SimpleLineCommentFromSourcePart() { const string Text = @"(1,3,4,6)"; var compiler = CompilerBrowser.FromText(Text); var span = compiler.Source.All; var trimmed = compiler.Reformat(targetPart: span); Tracer.Assert(trimmed == "(1, 3, 4, 6)", trimmed); } [Test] [UnitTest] public void SingleElementList() { const string text = @"(aaaaaddddd)"; const string expectedText = @"( aaaaaddddd )"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void SingleElementListFlat() { const string text = @"(aaaaaddddd)"; const string expectedText = @"(aaaaaddddd)"; text.SimpleTest(expectedText, 14, 1); } [Test] [UnitTest] public void StraightList() { const string text = @"(aaaaa;ccccc)"; const string expectedText = @"( aaaaa; ccccc )"; text.SimpleTest(expectedText, 10, 1); } [Test] [UnitTest] public void TwoLevelParenthesis() { const string text = @"aaaaa;llll:bbbbb;(cccccsssss)"; const string expectedText = @"aaaaa; llll: bbbbb; ( cccccsssss )"; text.SimpleTest(expectedText, 12, 1); } [Test] [UnitTest] public void UseLineBreakBeforeParenthesis() { const string Text = @"a:{ 1234512345, 12345}"; var expectedText = @"a: { 1234512345, 12345 }" .Replace("\r\n", "\n"); var compiler = CompilerBrowser.FromText(Text); var newSource = compiler.Reformat ( new ReniUI.Formatting.Configuration {MaxLineLength = 10, EmptyLineLimit = 0}.Create() ) .Replace("\r\n", "\n"); var lineCount = newSource.Count(item => item == '\n'); Tracer.Assert(newSource == expectedText, "\n\"" + newSource + "\""); } [Test] [UnitTest] public void UseSpaceWhenLineBreakIsRemoved() { const string text = @"(12345,12345,12345,12345,12345)"; var expectedText = @"( 12345, 12345, 12345, 12345, 12345 )" .Replace("\r\n", "\n"); var compiler = CompilerBrowser.FromText(text); var newSource = compiler.Reformat ( new ReniUI.Formatting.Configuration {EmptyLineLimit = 0, MaxLineLength = 20}.Create() ) .Replace("\r\n", "\n"); Tracer.Assert(newSource == expectedText, "\n\"" + newSource + "\""); } } }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using Komires.MataliPhysics; using Komires.MataliRender; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class DemoMesh { Demo demo; int meshVertexBuffer; int meshIndexBuffer; DemoTexture meshTexture; CullFaceMode meshCullMode; int vertexCount; int indexCount; bool dynamic; bool scaleNormals; VertexPositionNormalTexture[] meshVertices; ushort[] meshIndices16Bit; int[] meshIndices32Bit; DrawElementsType meshIndicesType; public int VertexBuffer { get { return meshVertexBuffer; } } public int IndexBuffer { get { return meshIndexBuffer; } } public DemoTexture DemoTexture { get { return meshTexture; } } public CullFaceMode CullMode { get { return meshCullMode; } } public int VertexCount { get { return vertexCount; } } public int IndexCount { get { return indexCount; } } public bool Dynamic { get { return dynamic; } } public bool ScaleNormals { get { return scaleNormals; } set { scaleNormals = value; } } public VertexPositionNormalTexture[] Vertices { get { return meshVertices; } } public ushort[] Indices16Bit { get { return meshIndices16Bit; } } public int[] Indices32Bit { get { return meshIndices32Bit; } } public RenderMeshDeferredPNT Render; Vector3 ambient; Vector3 diffuse; Vector3 emission; Vector3 specular; Vector3 lightDirection; Vector3 lightDiffuse; Vector3 lightSpecular; public DemoMesh(Demo demo) { this.demo = demo; Render = new RenderMeshDeferredPNT(); meshVertexBuffer = -1; meshIndexBuffer = -1; meshVertices = null; meshIndices16Bit = null; meshIndices32Bit = null; meshIndicesType = 0; meshCullMode = CullFaceMode.Back; dynamic = false; scaleNormals = false; SetTexture(null); } public DemoMesh(Demo demo, Shape shape, DemoTexture texture, Vector2 textureScale, bool indices, bool indices16Bit, bool flipTriangles, bool flipNormals, bool smoothNormals, CullFaceMode cullMode, bool dynamic, bool scaleNormals) { this.demo = demo; Render = new RenderMeshDeferredPNT(); meshVertexBuffer = -1; meshIndexBuffer = -1; meshVertices = null; meshIndices16Bit = null; meshIndices32Bit = null; meshIndicesType = 0; this.dynamic = dynamic; this.scaleNormals = scaleNormals; SetCullMode(cullMode); SetTexture(texture); if (indices) { meshVertices = new VertexPositionNormalTexture[shape.VertexCount]; shape.GetMeshVertices(textureScale.X, textureScale.Y, flipNormals, smoothNormals, meshVertices); CreateVertexBuffer(meshVertices, dynamic); if (indices16Bit) { meshIndices16Bit = new ushort[shape.IndexCount]; shape.GetMesh16BitIndices(flipTriangles, meshIndices16Bit); CreateIndexBuffer(meshIndices16Bit, false); } else { meshIndices32Bit = new int[shape.IndexCount]; shape.GetMesh32BitIndices(flipTriangles, meshIndices32Bit); CreateIndexBuffer(meshIndices32Bit, false); } } else { meshVertices = new VertexPositionNormalTexture[shape.TriangleVertexCount]; shape.GetMesh(textureScale.X, textureScale.Y, flipTriangles, flipNormals, smoothNormals, meshVertices); CreateVertexBuffer(meshVertices, dynamic); } } public DemoMesh(Demo demo, TriangleMesh triangleMesh, DemoTexture texture, Vector2 textureScale, bool indices, bool indices16Bit, bool flipTriangles, bool flipNormals, bool smoothNormals, CullFaceMode cullMode, bool dynamic, bool scaleNormals) { this.demo = demo; Render = new RenderMeshDeferredPNT(); meshVertexBuffer = -1; meshIndexBuffer = -1; meshVertices = null; meshIndices16Bit = null; meshIndices32Bit = null; meshIndicesType = 0; this.dynamic = dynamic; this.scaleNormals = scaleNormals; SetCullMode(cullMode); SetTexture(texture); if (indices) { triangleMesh.GetMeshVertices(flipNormals, smoothNormals, out meshVertices); CreateVertexBuffer(meshVertices, dynamic); if (indices16Bit) { triangleMesh.GetMesh16BitIndices(flipTriangles, out meshIndices16Bit); CreateIndexBuffer(meshIndices16Bit, false); } else { triangleMesh.GetMesh32BitIndices(flipTriangles, out meshIndices32Bit); CreateIndexBuffer(meshIndices32Bit, false); } } else { triangleMesh.GetMesh(textureScale, flipTriangles, flipNormals, smoothNormals, out meshVertices); CreateVertexBuffer(meshVertices, dynamic); } } public void CreateVertexBuffer(VertexPositionNormalTexture[] vertices, bool dynamic) { if (vertices.Length == 0) return; if (demo.EnableVertexBuffer) { GL.GenBuffers(1, out meshVertexBuffer); GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); if (dynamic) GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexPositionNormalTexture.SizeInBytes * vertices.Length), vertices, BufferUsageHint.DynamicDraw); else GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexPositionNormalTexture.SizeInBytes * vertices.Length), vertices, BufferUsageHint.StaticDraw); } meshVertices = vertices; vertexCount = vertices.Length; } public void CreateIndexBuffer(ushort[] indices, bool dynamic) { if (indices.Length == 0) return; if (demo.EnableVertexBuffer) { GL.GenBuffers(1, out meshIndexBuffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); if (dynamic) GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(ushort) * indices.Length), indices, BufferUsageHint.DynamicDraw); else GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(ushort) * indices.Length), indices, BufferUsageHint.StaticDraw); } meshIndices16Bit = indices; indexCount = indices.Length; meshIndicesType = DrawElementsType.UnsignedShort; } public void CreateIndexBuffer(int[] indices, bool dynamic) { if (indices.Length == 0) return; if (demo.EnableVertexBuffer) { GL.GenBuffers(1, out meshIndexBuffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); if (dynamic) GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(int) * indices.Length), indices, BufferUsageHint.DynamicDraw); else GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(int) * indices.Length), indices, BufferUsageHint.StaticDraw); } meshIndices32Bit = indices; indexCount = indices.Length; meshIndicesType = DrawElementsType.UnsignedInt; } public void SetVertices(VertexPositionNormalTexture[] vertices) { if (demo.EnableVertexBuffer) { GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexPositionNormalTexture.SizeInBytes * vertices.Length), IntPtr.Zero, BufferUsageHint.DynamicDraw); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexPositionNormalTexture.SizeInBytes * vertices.Length), vertices, BufferUsageHint.DynamicDraw); } meshVertices = vertices; vertexCount = vertices.Length; } public void SetIndices(ushort[] indices) { if (demo.EnableVertexBuffer) { GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(ushort)), IntPtr.Zero, BufferUsageHint.DynamicDraw); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(ushort)), indices, BufferUsageHint.DynamicDraw); } meshIndices16Bit = indices; indexCount = indices.Length; } public void SetIndices(int[] indices) { if (demo.EnableVertexBuffer) { GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(int)), IntPtr.Zero, BufferUsageHint.DynamicDraw); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(int)), indices, BufferUsageHint.DynamicDraw); } meshIndices32Bit = indices; indexCount = indices.Length; } public void SetTexture(DemoTexture texture) { meshTexture = texture; } public void SetCullMode(CullFaceMode cullMode) { meshCullMode = cullMode; } public void Draw(IRender render) { render.Apply(); if (demo.EnableVertexBuffer) { if (meshVertexBuffer != -1) { if (meshIndexBuffer != -1) { GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes); GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes)); GL.DrawElements(PrimitiveType.Triangles, indexCount, meshIndicesType, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero); GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.TextureCoordArray); } else { GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes); GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes)); GL.DrawArrays(PrimitiveType.Triangles, 0, vertexCount); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero); GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.TextureCoordArray); } } } else { VertexPositionNormalTexture v1, v2, v3; if (meshIndices16Bit != null) { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < indexCount; i += 3) { v1 = meshVertices[meshIndices16Bit[i]]; v2 = meshVertices[meshIndices16Bit[i + 1]]; v3 = meshVertices[meshIndices16Bit[i + 2]]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } else if (meshIndices32Bit != null) { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < indexCount; i += 3) { v1 = meshVertices[meshIndices32Bit[i]]; v2 = meshVertices[meshIndices32Bit[i + 1]]; v3 = meshVertices[meshIndices32Bit[i + 2]]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } else { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < vertexCount; i += 3) { v1 = meshVertices[i]; v2 = meshVertices[i + 1]; v3 = meshVertices[i + 2]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } } } public void Draw(ref Matrix4 world, ref Matrix4 view, ref Matrix4 projection, PhysicsLight light, PhysicsMaterial material, PhysicsCamera camera, bool sleep, bool wireframe) { Render.SetWorld(ref world); Render.SetView(ref view); Render.SetProjection(ref projection); Render.EnableScaleNormals = scaleNormals; light.GetDirection(ref lightDirection); light.GetDiffuse(ref lightDiffuse); light.GetSpecular(ref lightSpecular); if (meshCullMode == CullFaceMode.FrontAndBack) GL.Disable(EnableCap.CullFace); GL.CullFace(meshCullMode); DemoTexture currentTexture = meshTexture; if (material.UserDataStr != null) currentTexture = demo.Textures[material.UserDataStr]; material.GetAmbient(ref ambient); material.GetDiffuse(ref diffuse); material.GetEmission(ref emission); material.GetSpecular(ref specular); if (sleep) { diffuse.X = 0.7f; diffuse.Y = 1.0f; diffuse.Z = 1.0f; } Render.SetAmbient(ref ambient); Render.SetSpecular(ref specular); Render.SetEmission(ref emission); Render.SpecularPower = material.SpecularPower; Render.Alpha = material.TransparencyFactor; Render.EnableTwoSidedNormals = material.TwoSidedNormals; if (!wireframe) { Render.SetDiffuse(ref diffuse); if (currentTexture != null) { Render.EnableTexture = true; Render.Texture = currentTexture.Handle; } else { Render.EnableTexture = false; } } else { GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line); diffuse.X *= 4.0f; diffuse.Y *= 4.0f; diffuse.Z *= 4.0f; Render.SetDiffuse(ref diffuse); Render.EnableTexture = false; } Render.Apply(); if (demo.EnableVertexBuffer) { if (meshVertexBuffer != -1) { if (meshIndexBuffer != -1) { GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, meshIndexBuffer); GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes); GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes)); GL.DrawElements(PrimitiveType.Triangles, indexCount, meshIndicesType, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero); GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.TextureCoordArray); } else { GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.BindBuffer(BufferTarget.ArrayBuffer, meshVertexBuffer); GL.VertexPointer(3, VertexPointerType.Float, VertexPositionNormalTexture.SizeInBytes, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)Vector3.SizeInBytes); GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPositionNormalTexture.SizeInBytes, (IntPtr)(Vector3.SizeInBytes + Vector3.SizeInBytes)); GL.DrawArrays(PrimitiveType.Triangles, 0, vertexCount); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero); GL.NormalPointer(NormalPointerType.Float, 0, IntPtr.Zero); GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, IntPtr.Zero); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.TextureCoordArray); } } } else { VertexPositionNormalTexture v1, v2, v3; if (meshIndices16Bit != null) { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < indexCount; i += 3) { v1 = meshVertices[meshIndices16Bit[i]]; v2 = meshVertices[meshIndices16Bit[i + 1]]; v3 = meshVertices[meshIndices16Bit[i + 2]]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } else if (meshIndices32Bit != null) { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < indexCount; i += 3) { v1 = meshVertices[meshIndices32Bit[i]]; v2 = meshVertices[meshIndices32Bit[i + 1]]; v3 = meshVertices[meshIndices32Bit[i + 2]]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } else { GL.Begin(PrimitiveType.Triangles); for (int i = 0; i < vertexCount; i += 3) { v1 = meshVertices[i]; v2 = meshVertices[i + 1]; v3 = meshVertices[i + 2]; GL.TexCoord2(v1.TextureCoordinate); GL.Normal3(v1.Normal); GL.Vertex3(v1.Position); GL.TexCoord2(v2.TextureCoordinate); GL.Normal3(v2.Normal); GL.Vertex3(v2.Position); GL.TexCoord2(v3.TextureCoordinate); GL.Normal3(v3.Normal); GL.Vertex3(v3.Position); } GL.End(); } } if (meshCullMode == CullFaceMode.FrontAndBack) GL.Enable(EnableCap.CullFace); if (wireframe) GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); } } }
using UnityEngine; using System; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Linq; using System.IO; /// <summary> /// This class holds the map data used to generate /// game objects. This contains prefabs, not the live /// game obejcts, and the same prefab can appear many times /// in the map; don't try to alter these objects. /// /// The map class does not use Location structures because /// it can only deal with x,y co-ordiantes, but the Location /// structure should specify which map you are on. /// </summary> public sealed class Map { private readonly MapLegend mapLegend; private readonly string[] mapText; private ILookup<string, Location> lazyDoorLocations; public readonly int mapIndex; public readonly string name; public readonly int width; public readonly int height; public readonly float cameraSize; private Map(int mapIndex, string name, float cameraSize, string[] mapText, MapLegend mapLegend) { this.mapIndex = mapIndex; this.name = name; this.mapText = mapText; this.mapLegend = mapLegend; this.width = mapText.Max(l => l.Length); this.height = mapText.Length; this.cameraSize = cameraSize; } /// <summary> /// This indexer retrives the prefabs for a given cell; /// if x or y is out of range, this returns an empty collection. /// </summary> public Cell this[int x, int y] { get { if (x >= 0 && x < width && y >= 0 && y < height) { if (x < mapText[y].Length) { char ch = mapText[y][x]; Cell cell; if (mapLegend.TryGetValue(ch, out cell)) { return cell; } } } return Cell.empty; } } /// <summary> /// Yields each location that contains the door name indicated. /// </summary> public IEnumerable<Location> FindDoors(string doorName) { ILookup<string, Location> doorLocs = Lazy.Init(ref lazyDoorLocations, delegate { return (from y in Enumerable.Range(0, height) from x in Enumerable.Range(0, width) let name = this[x, y].doorName where name != null let loc = new Location(x, y, this) select new { name, loc }). ToLookup(pair => pair.name, pair => pair.loc); }); return doorLocs[doorName]; } /// <summary> /// Load() reads the map data from the reader given, and selects /// suitable prefabs by name from the set of prefabs offered (which /// must include all prefabs that could be used). /// /// To ensure maps are not loaded twice, the MapController calls this; /// everyone else calls methods on the MapController. /// </summary> public static Map Load(int mapIndex, string name, TextReader reader, IEnumerable<GameObject> prefabs) { var mapLegendByName = new Dictionary<char, string>(); var buffer = new List<string>(); float cameraSize = 3f; string line; while ((line = reader.ReadLine()) != null) { if (line == "-") break; buffer.Add(line); } while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.Length > 0) { int firstSpace = line.IndexOf(' '); if (firstSpace == 1) mapLegendByName.Add(line[0], line.Substring(1).Trim()); else if (firstSpace < 0 && line.Length == 1) mapLegendByName.Add(line[0], ""); else if (firstSpace > 1) { string optionName = line.Substring(0, firstSpace); string optionValue = line.Substring(firstSpace + 1); if (optionName.Equals("CameraSize", StringComparison.InvariantCultureIgnoreCase)) cameraSize = float.Parse(optionValue); else throw new FormatException(string.Format("'{0}' is not a valid map option.", optionName)); } else throw new FormatException(string.Format("Map legend line '{0}' is malformed", line)); } } return new Map(mapIndex, name, cameraSize, buffer.ToArray(), new MapLegend(mapLegendByName, prefabs)); } /// <summary> /// This class holds onto the list of prefabs for each map character; /// it mainly exists to save typing, by having a short name! /// </summary> private sealed class MapLegend : Dictionary<char, Cell> { public MapLegend(Dictionary<char, string> byName, NamedObjectDictionary namedPrefabs) { foreach (var pair in byName) { Add(pair.Key, namedPrefabs.GetCell(pair.Value)); } } public MapLegend(Dictionary<char, string> byName, IEnumerable<GameObject> prefabs) : this(byName, new NamedObjectDictionary(prefabs)) { } } /// <summary> /// This class is a dictionary that holds objects by name, and provides /// a convenient method to extract them in bunches. /// </summary> private sealed class NamedObjectDictionary : Dictionary<string, GameObject> { public NamedObjectDictionary(IEnumerable<GameObject> objects) { foreach (GameObject obj in objects) Add(obj.name, obj); } public Cell GetCell(string text) { GameObject[] prefabs = new GameObject[0]; string doorName = null; string[] parts = text.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length > 0) { string[] objNames = parts[0].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); prefabs = objNames.Select(n => ResolvePrefab(n.Trim())).ToArray(); if (parts.Length == 2) { doorName = parts[1].Trim(); } else if (parts.Length > 2) { throw new FormatException("'{0}' is not valid because it contains too many ':' characters."); } } return new Cell(new ReadOnlyCollection<GameObject>(prefabs), doorName); } public GameObject ResolvePrefab(string name) { GameObject prefab; if (TryGetValue(name, out prefab)) { return prefab; } string msg = string.Format("The prefab named '{0}' was not found.", name); throw new KeyNotFoundException(msg); } } /// <summary> /// This class holds the data for one cell in the map. The same cell object /// will be used for many places in the same map. /// </summary> public sealed class Cell { public static readonly Cell empty = new Cell(new ReadOnlyCollection<GameObject>(new GameObject[0])); public readonly ReadOnlyCollection<GameObject> prefabs; public readonly string doorName; public Cell(ReadOnlyCollection<GameObject> prefabs) : this(prefabs, null) { } public Cell(ReadOnlyCollection<GameObject> prefabs, string doorName) { this.prefabs = prefabs; this.doorName = doorName; } public override string ToString() { string text = string.Join( ",", (from pf in prefabs select pf.name).ToArray()); if (doorName != null) text += string.Format(" [{0}]", doorName); return text; } /// <summary> /// This creates the terrain object for the cell, setting its /// parent and position as indicated. This method returns null only /// if this cell is empty. /// </summary> public GameObject InstantiateTerrain(Location location, GameObject container) { if (prefabs.Count == 0) { return null; } GameObject terrain = GameObject.Instantiate(prefabs[0]); terrain.name = prefabs[0].name; terrain.transform.SetParent(container.transform, false); terrain.transform.localPosition = location.ToLocalPosition(); return terrain; } /// <summary> /// Instantiates the non-terrain entities, if any. If this cell is empty /// or contains terrain only, this will return an empty array. /// </summary> public GameObject[] InstantiateEntities(Location location, GameObject container) { if (prefabs.Count < 2) { return new GameObject[0]; } GameObject[] created = new GameObject[prefabs.Count - 1]; for (int i = 1; i < prefabs.Count; ++i) { GameObject go = GameObject.Instantiate(prefabs[i]); go.name = prefabs[i].name; go.transform.SetParent(container.transform, false); go.transform.localPosition = location.ToLocalPosition(); created[i - 1] = go; } return created; } } }
// 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.Linq; using System.Text; using Xunit; using System.Threading; using System.Diagnostics.Tracing; using SdtEventSources; namespace BasicEventSourceTests { public class TestsWriteEventToListener { [Fact] [ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_ArgsBasicTypes() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { var sources = EventSource.GetSources(); Assert.True(sources.Contains(log)); Assert.NotNull(EventSource.GenerateManifest(typeof(SimpleEventSource), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); Assert.Null(EventSource.GenerateManifest(typeof(EventSourceTest), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); log.Event0(); Assert.Equal(1, LoudListener.LastEvent.EventId); Assert.Equal(0, LoudListener.LastEvent.Payload.Count); #region Validate "int" arguments log.EventI(10); Assert.Equal(2, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.LastEvent.Payload[0]); log.EventII(10, 11); Assert.Equal(3, LoudListener.LastEvent.EventId); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.LastEvent.Payload[1]); log.EventIII(10, 11, 12); Assert.Equal(4, LoudListener.LastEvent.EventId); Assert.Equal(3, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.LastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.LastEvent.Payload[2]); #endregion #region Validate "long" arguments log.EventL(10); Assert.Equal(5, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.LastEvent.Payload[0]); log.EventLL(10, 11); Assert.Equal(6, LoudListener.LastEvent.EventId); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.LastEvent.Payload[1]); log.EventLLL(10, 11, 12); Assert.Equal(7, LoudListener.LastEvent.EventId); Assert.Equal(3, LoudListener.LastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.LastEvent.Payload[1]); Assert.Equal(12, (long)LoudListener.LastEvent.Payload[2]); #endregion #region Validate "string" arguments log.EventS("10"); Assert.Equal(8, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); log.EventSS("10", "11"); Assert.Equal(9, LoudListener.LastEvent.EventId); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.LastEvent.Payload[1]); log.EventSSS("10", "11", "12"); Assert.Equal(10, LoudListener.LastEvent.EventId); Assert.Equal(3, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.LastEvent.Payload[1]); Assert.Equal("12", (string)LoudListener.LastEvent.Payload[2]); #endregion #region Validate byte array arguments byte[] arr = new byte[20]; log.EventWithByteArray(arr); Assert.Equal(52, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(arr.Length, ((byte[])LoudListener.LastEvent.Payload[0]).Length); #endregion #region Validate mixed type arguments log.EventSI("10", 11); Assert.Equal(11, LoudListener.LastEvent.EventId); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.LastEvent.Payload[1]); log.EventSL("10", 11); Assert.Equal(12, LoudListener.LastEvent.EventId); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.LastEvent.Payload[1]); log.EventSII("10", 11, 12); Assert.Equal(13, LoudListener.LastEvent.EventId); Assert.Equal(3, LoudListener.LastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.LastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.LastEvent.Payload[2]); #endregion #region Validate enums/flags log.EventEnum(MyColor.Blue); Assert.Equal(19, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(MyColor.Blue, (MyColor)LoudListener.LastEvent.Payload[0]); log.EventEnum1(MyColor.Green); Assert.Equal(20, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(MyColor.Green, (MyColor)LoudListener.LastEvent.Payload[0]); log.EventFlags(MyFlags.Flag1); Assert.Equal(21, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.LastEvent.Payload[0]); log.EventFlags1(MyFlags.Flag1); Assert.Equal(22, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.LastEvent.Payload[0]); #endregion #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. #region Validate DateTime DateTime now = DateTime.Now; log.EventDateTime(now); Assert.Equal(24, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal((DateTime)LoudListener.LastEvent.Payload[0], now); #endregion #endif // USE_ETW } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } [Fact] [ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_ArgsCornerCases() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { // coverage for EventSource.SendCommand() var options = new Dictionary<string, string>() { { "arg", "val" } }; EventSource.SendCommand(log, EventCommand.SendManifest, options); Guid guid = Guid.NewGuid(); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. log.EventWithManyTypeArgs("Hello", 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid); Assert.Equal(25, LoudListener.LastEvent.EventId); Assert.Equal(12, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(0, (long)LoudListener.LastEvent.Payload[1]); Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[2]); Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[3]); Assert.Equal('a', (char)LoudListener.LastEvent.Payload[4]); Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[5]); Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[6]); Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[7]); Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[8]); Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[9]); Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[10]); Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[11]); #endif // USE_ETW log.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6"); Assert.Equal(26, LoudListener.LastEvent.EventId); Assert.Equal(7, LoudListener.LastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("s6", (string)LoudListener.LastEvent.Payload[6]); log.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"); Assert.Equal(27, LoudListener.LastEvent.EventId); Assert.Equal(9, LoudListener.LastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("s8", (string)LoudListener.LastEvent.Payload[8]); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. log.EventWithWeirdArgs(IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/); Assert.Equal(30, LoudListener.LastEvent.EventId); Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count); Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]); Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]); Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]); // Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]); #endif // USE_ETW } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } [Fact] public void Test_WriteEvent_InvalidCalls() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new InvalidCallsToWriteEventEventSource()) { using (var el = new LoudListener()) { log.WriteTooManyArgs("Hello"); Assert.Equal(2, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); // Faked count (compat) Assert.Equal("Hello", LoudListener.LastEvent.Payload[0]); log.WriteTooFewArgs(10, 100); Assert.Equal(1, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); // Real # of args passed to WriteEvent Assert.Equal(10, LoudListener.LastEvent.Payload[0]); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } [Fact] public void Test_WriteEvent_ToChannel_Coverage() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var el = new LoudListener()) using (var log = new SimpleEventSource()) { el.EnableEvents(log, EventLevel.Verbose); log.WriteIntToAdmin(10); } TestUtilities.CheckNoEventSourcesRunning("Stop"); } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. [Fact] public void Test_WriteEvent_TransferEvents() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { Guid actid = Guid.NewGuid(); log.LogTaskScheduled(actid, "Hello from a test"); Assert.Equal(17, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello from a test", (string)LoudListener.LastEvent.Payload[0]); actid = Guid.NewGuid(); log.LogTaskScheduledBad(actid, "Hello again"); Assert.Equal(23, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello again", (string)LoudListener.LastEvent.Payload[0]); actid = Guid.NewGuid(); Guid guid = Guid.NewGuid(); log.EventWithXferManyTypeArgs(actid, 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid); Assert.Equal(29, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(11, LoudListener.LastEvent.Payload.Count); Assert.Equal(0, (long)LoudListener.LastEvent.Payload[0]); Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[1]); Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[2]); Assert.Equal('a', (char)LoudListener.LastEvent.Payload[3]); Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[4]); Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[5]); Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[6]); Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[7]); Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[8]); Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[9]); Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[10]); actid = Guid.NewGuid(); log.EventWithXferWeirdArgs(actid, IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/); Assert.Equal(31, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count); Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]); Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]); Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]); // Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]); actid = Guid.NewGuid(); Assert.Throws<EventSourceException>(() => log.LogTransferNoOpcode(actid)); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } #endif // USE_ETW [Fact] [ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_ZeroKwds() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { // match any kwds == 0 el.EnableEvents(log, 0, 0); // Fire an event without a kwd: EventWithEscapingMessage // 1. Validate that the event fires when ETW event method called unconditionally log.EventWithEscapingMessage("Hello world!", 10); Assert.NotNull(LoudListener.LastEvent); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello world!", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(10, (int)LoudListener.LastEvent.Payload[1]); // reset LastEvent LoudListener.LastEvent = null; // 2. Validate that the event fires when ETW event method call is guarded by IsEnabled if (log.IsEnabled(EventLevel.Informational, 0)) log.EventWithEscapingMessage("Goodbye skies!", 100); Assert.NotNull(LoudListener.LastEvent); Assert.Equal(2, LoudListener.LastEvent.Payload.Count); Assert.Equal("Goodbye skies!", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(100, (int)LoudListener.LastEvent.Payload[1]); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } #if FEATURE_ETLEVENTS [Fact] public void Test_EventSourceCreatedEvents_BeforeListener() { TestUtilities.CheckNoEventSourcesRunning("Start"); EventSource log = null; EventSource log2 = null; EventListenerListener el = null; try { string esName = "EventSourceName_HopefullyUnique"; string esName2 = "EventSourceName_HopefullyUnique2"; bool esNameHit = false; bool esName2Hit = false; log = new EventSource(esName); log2 = new EventSource(esName2); using (var listener = new EventListenerListener()) { List<EventSource> eventSourceNotificationsReceived = new List<EventSource>(); listener.EventSourceCreated += (s, a) => { if (a.EventSource.Name.Equals(esName)) { esNameHit = true; } if (a.EventSource.Name.Equals(esName2)) { esName2Hit = true; } }; Thread.Sleep(1000); Assert.Equal(true, esNameHit); Assert.Equal(true, esName2Hit); } } finally { if (log != null) { log.Dispose(); } if (log2 != null) { log2.Dispose(); } if (el != null) { el.Dispose(); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } [Fact] public void Test_EventSourceCreatedEvents_AfterListener() { TestUtilities.CheckNoEventSourcesRunning("Start"); EventSource log = null; EventSource log2 = null; EventListenerListener el = null; try { using (var listener = new EventListenerListener()) { string esName = "EventSourceName_HopefullyUnique"; string esName2 = "EventSourceName_HopefullyUnique2"; bool esNameHit = false; bool esName2Hit = false; List<EventSource> eventSourceNotificationsReceived = new List<EventSource>(); listener.EventSourceCreated += (s, a) => { if (a.EventSource.Name.Equals(esName)) { esNameHit = true; } if (a.EventSource.Name.Equals(esName2)) { esName2Hit = true; } }; log = new EventSource(esName); log2 = new EventSource(esName2); Thread.Sleep(1000); Assert.Equal(true, esNameHit); Assert.Equal(true, esName2Hit); } } finally { if (log != null) { log.Dispose(); } if (log2 != null) { log2.Dispose(); } if (el != null) { el.Dispose(); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } #endif } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.DependencyModel.Resolution; using Orleans.Runtime; #if NETCOREAPP using System.Runtime.Loader; #endif namespace Orleans.CodeGeneration { /// <summary> /// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve /// </summary> internal class AssemblyResolver { /// <summary> /// Needs to be public so can be serialized across the app domain. /// </summary> public Dictionary<string, string> ReferenceAssemblyPaths { get; } = new Dictionary<string, string>(); private readonly bool installDefaultResolveHandler; private readonly ICompilationAssemblyResolver assemblyResolver; private readonly DependencyContext dependencyContext; private readonly DependencyContext resolverRependencyContext; #if NETCOREAPP private readonly AssemblyLoadContext loadContext; #endif public AssemblyResolver(string path, List<string> referencedAssemblies, bool installDefaultResolveHandler = true) { this.installDefaultResolveHandler = installDefaultResolveHandler; if (Path.GetFileName(path) == "Orleans.Core.dll") this.Assembly = typeof(RuntimeVersion).Assembly; else this.Assembly = Assembly.LoadFrom(path); this.dependencyContext = DependencyContext.Load(this.Assembly); this.resolverRependencyContext = DependencyContext.Load(typeof(AssemblyResolver).Assembly); var codegenPath = Path.GetDirectoryName(new Uri(typeof(AssemblyResolver).Assembly.CodeBase).LocalPath); this.assemblyResolver = new CompositeCompilationAssemblyResolver( new ICompilationAssemblyResolver[] { new AppBaseCompilationAssemblyResolver(codegenPath), new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)), new ReferenceAssemblyPathResolver(), new PackageCompilationAssemblyResolver() }); #if NETCOREAPP this.loadContext = AssemblyLoadContext.GetLoadContext(this.Assembly); if (this.loadContext == AssemblyLoadContext.Default) { if (this.installDefaultResolveHandler) { AssemblyLoadContext.Default.Resolving += this.AssemblyLoadContextResolving; } } else { this.loadContext.Resolving += this.AssemblyLoadContextResolving; } #else if (this.installDefaultResolveHandler) { AppDomain.CurrentDomain.AssemblyResolve += this.ResolveAssembly; } #endif foreach (var assemblyPath in referencedAssemblies) { var libName = Path.GetFileNameWithoutExtension(assemblyPath); if (!string.IsNullOrWhiteSpace(libName)) this.ReferenceAssemblyPaths[libName] = assemblyPath; var asmName = AssemblyName.GetAssemblyName(assemblyPath); this.ReferenceAssemblyPaths[asmName.FullName] = assemblyPath; } } public Assembly Assembly { get; } public void Dispose() { #if NETCOREAPP if (this.loadContext == AssemblyLoadContext.Default) { if (this.installDefaultResolveHandler) { AssemblyLoadContext.Default.Resolving -= this.AssemblyLoadContextResolving; } } else { this.loadContext.Resolving -= this.AssemblyLoadContextResolving; } #else if (this.installDefaultResolveHandler) { AppDomain.CurrentDomain.AssemblyResolve -= this.ResolveAssembly; } #endif } /// <summary> /// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The event data.</param> /// <returns>The assembly that resolves the type, assembly, or resource; /// or null if the assembly cannot be resolved. /// </returns> public Assembly ResolveAssembly(object sender, ResolveEventArgs args) { var context = default(AssemblyLoadContext); #if NETCOREAPP context = AssemblyLoadContext.GetLoadContext(args.RequestingAssembly); #endif return this.AssemblyLoadContextResolving(context, new AssemblyName(args.Name)); } public Assembly AssemblyLoadContextResolving(AssemblyLoadContext context, AssemblyName name) { // Attempt to resolve the library from one of the dependency contexts. var library = this.resolverRependencyContext?.RuntimeLibraries?.FirstOrDefault(NamesMatch) ?? this.dependencyContext?.RuntimeLibraries?.FirstOrDefault(NamesMatch); if (library != null) { var wrapper = new CompilationLibrary( library.Type, library.Name, library.Version, library.Hash, library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths), library.Dependencies, library.Serviceable); var assemblies = new List<string>(); if (this.assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies)) { foreach (var asm in assemblies) { var assembly = TryLoadAssemblyFromPath(asm); if (assembly != null) return assembly; } } } if (this.ReferenceAssemblyPaths.TryGetValue(name.FullName, out var pathByFullName)) { var assembly = TryLoadAssemblyFromPath(pathByFullName); if (assembly != null) return assembly; } if (this.ReferenceAssemblyPaths.TryGetValue(name.Name, out var pathByName)) { // // Only try to load it if the resolved path is different than from before // if (String.Compare(pathByFullName, pathByName, StringComparison.OrdinalIgnoreCase) != 0) { var assembly = TryLoadAssemblyFromPath(pathByName); if (assembly != null) return assembly; } } return null; bool NamesMatch(RuntimeLibrary runtime) { return string.Equals(runtime.Name, name.Name, StringComparison.OrdinalIgnoreCase); } } private Assembly TryLoadAssemblyFromPath(string path) { try { #if NETCOREAPP return this.loadContext.LoadFromAssemblyPath(path); #else return Assembly.LoadFrom(path); #endif } catch { return null; } } #if !NETCOREAPP internal class AssemblyLoadContext { } #endif } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using ReaderException = com.google.zxing.ReaderException; using BitSource = com.google.zxing.common.BitSource; using CharacterSetECI = com.google.zxing.common.CharacterSetECI; using DecoderResult = com.google.zxing.common.DecoderResult; namespace com.google.zxing.qrcode.decoder { /// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes /// in one QR Code. This class decodes the bits back into text.</p> /// /// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author> sealed class DecodedBitStreamParser { /// <summary> See ISO 18004:2006, 6.4.4 Table 5</summary> //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly char[] ALPHANUMERIC_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'}; private const System.String SHIFT_JIS = "SJIS"; private const System.String EUC_JP = "EUC_JP"; private static bool ASSUME_SHIFT_JIS; private const System.String UTF8 = "UTF-8"; // Redivivus.in Java to c# Porting update // 30/01/2010 // Commented & Added private const System.String ISO88591 = "ISO-8859-1"; private DecodedBitStreamParser() { } internal static DecoderResult decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel) { BitSource bits = new BitSource(bytes); System.Text.StringBuilder result = new System.Text.StringBuilder(50); CharacterSetECI currentCharacterSetECI = null; bool fc1InEffect = false; System.Collections.ArrayList byteSegments = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(1)); Mode mode; do { // While still another segment to read... if (bits.available() < 4) { // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here mode = Mode.TERMINATOR; } else { try { mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits } catch (System.ArgumentException) { throw ReaderException.Instance; } } if (!mode.Equals(Mode.TERMINATOR)) { if (mode.Equals(Mode.FNC1_FIRST_POSITION) || mode.Equals(Mode.FNC1_SECOND_POSITION)) { // We do little with FNC1 except alter the parsed result a bit according to the spec fc1InEffect = true; } else if (mode.Equals(Mode.STRUCTURED_APPEND)) { // not really supported; all we do is ignore it // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue bits.readBits(16); } else if (mode.Equals(Mode.ECI)) { // Count doesn't apply to ECI int value_Renamed = parseECIValue(bits); currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value_Renamed); if (currentCharacterSetECI == null) { throw ReaderException.Instance; } } else { // How many characters will follow, encoded in this mode? int count = bits.readBits(mode.getCharacterCountBits(version)); if (mode.Equals(Mode.NUMERIC)) { decodeNumericSegment(bits, result, count); } else if (mode.Equals(Mode.ALPHANUMERIC)) { decodeAlphanumericSegment(bits, result, count, fc1InEffect); } else if (mode.Equals(Mode.BYTE)) { decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments); } else if (mode.Equals(Mode.KANJI)) { decodeKanjiSegment(bits, result, count); } else { throw ReaderException.Instance; } } } } while (!mode.Equals(Mode.TERMINATOR)); return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, ecLevel); } private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count) { // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards sbyte[] buffer = new sbyte[2 * count]; int offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character int twoBytes = bits.readBits(13); int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = (sbyte) (assembledTwoBytes >> 8); buffer[offset + 1] = (sbyte) assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: try { //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" result.Append(System.Text.Encoding.GetEncoding(SHIFT_JIS).GetString(SupportClass.ToByteArray(buffer))); } catch (System.IO.IOException) { throw ReaderException.Instance; } } private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.ArrayList byteSegments) { sbyte[] readBytes = new sbyte[count]; if (count << 3 > bits.available()) { throw ReaderException.Instance; } for (int i = 0; i < count; i++) { readBytes[i] = (sbyte) bits.readBits(8); } System.String encoding; if (currentCharacterSetECI == null) { // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. encoding = guessEncoding(readBytes); } else { encoding = currentCharacterSetECI.EncodingName; } try { //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes))); } catch (System.IO.IOException) { throw ReaderException.Instance; } byteSegments.Add(SupportClass.ToByteArray(readBytes)); } private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count, bool fc1InEffect) { // Read two characters at a time int start = result.Length; while (count > 1) { int nextTwoCharsBits = bits.readBits(11); result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); count -= 2; } if (count == 1) { // special case: one character left result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]); } // See section 6.4.8.1, 6.4.8.2 if (fc1InEffect) { // We need to massage the result a bit if in an FNC1 mode: for (int i = start; i < result.Length; i++) { if (result[i] == '%') { if (i < result.Length - 1 && result[i + 1] == '%') { // %% is rendered as % result.Remove(i + 1, 1); } else { // In alpha mode, % should be converted to FNC1 separator 0x1D result[i] = (char) 0x1D; } } } } } private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count) { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits int threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw ReaderException.Instance; } result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); count -= 3; } if (count == 2) { // Two digits left over to read, encoded in 7 bits int twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw ReaderException.Instance; } result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); } else if (count == 1) { // One digit left over to read int digitBits = bits.readBits(4); if (digitBits >= 10) { throw ReaderException.Instance; } result.Append(ALPHANUMERIC_CHARS[digitBits]); } } private static System.String guessEncoding(sbyte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.Length > 3 && bytes[0] == (sbyte) SupportClass.Identity(0xEF) && bytes[1] == (sbyte) SupportClass.Identity(0xBB) && bytes[2] == (sbyte) SupportClass.Identity(0xBF)) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; bool sawLatin1Supplement = false; bool lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value_Renamed = bytes[i] & 0xFF; if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value_Renamed >= 0x7F && value_Renamed <= 0x9F) { canBeISO88591 = false; } if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0)) { canBeShiftJIS = false; } if (((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF))) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.Length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return SHIFT_JIS; } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return ISO88591; } // Otherwise, we take a wild guess with UTF-8 return UTF8; } private static int parseECIValue(BitSource bits) { int firstByte = bits.readBits(8); if ((firstByte & 0x80) == 0) { // just one byte return firstByte & 0x7F; } else if ((firstByte & 0xC0) == 0x80) { // two bytes int secondByte = bits.readBits(8); return ((firstByte & 0x3F) << 8) | secondByte; } else if ((firstByte & 0xE0) == 0xC0) { // three bytes int secondThirdBytes = bits.readBits(16); return ((firstByte & 0x1F) << 16) | secondThirdBytes; } throw new System.ArgumentException("Bad ECI bits starting with byte " + firstByte); } static DecodedBitStreamParser() { { // Redivivus.in Java to c# Porting update // 30/01/2010 // Commented & Added //System.String platformDefault = System_Renamed.getProperty("file.encoding"); //ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || EUC_JP.ToUpper().Equals(platformDefault.ToUpper()); ASSUME_SHIFT_JIS = false; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using log4net.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using OpenSim.Grid.Communications.OGS1; using OpenSim.Grid.Framework; using OpenSim.Grid.AgentDomain.Modules; //using OpenSim.Grid.UserServer.Modules; namespace OpenSim.Grid.AgentDomain { /// <summary> /// Grid user server main class /// </summary> public class OpenAD_Main : BaseOpenSimServer, IGridServiceCore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected UserConfig Cfg; protected UserDataBaseService m_userDataBaseService; public UserManager m_userManager; protected UserServerAvatarAppearanceModule m_avatarAppearanceModule; protected UserServerFriendsModule m_friendsModule; public UserLoginService m_loginService; public UserLoginAuthService m_loginAuthService; public MessageServersConnector m_messagesService; protected GridInfoServiceModule m_gridInfoService; protected AgentDomainCommandModule m_consoleCommandModule; protected AgentDomainEventDispatchModule m_eventDispatcher; protected AvatarCreationModule m_appearanceModule; public static void Main(string[] args) { XmlConfigurator.Configure(); m_log.Info("Launching AgentDomain..."); OpenAD_Main userserver = new OpenAD_Main(); userserver.Startup(); userserver.Work(); } public OpenAD_Main() { m_console = new LocalConsole("AgentDomain/Service"); MainConsole.Instance = m_console; } public void Work() { m_console.Output("Enter help for a list of commands\n"); while (true) { m_console.Prompt(); } } protected override void StartupSpecific() { IInterServiceInventoryServices inventoryService = StartupCoreComponents(); m_stats = StatsManager.StartCollectingUserStats(); //setup services/modules StartupUserServerModules(); StartOtherComponents(inventoryService); //PostInitialise the modules PostInitialiseModules(); //register http handlers and start http server m_log.Info("[STARTUP]: Starting HTTP process"); RegisterHttpHandlers(); m_httpServer.Start(); base.StartupSpecific(); } protected virtual IInterServiceInventoryServices StartupCoreComponents() { Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), "AgentDomain_Config.xml"))); m_httpServer = new BaseHttpServer(Cfg.HttpPort); RegisterInterface<CommandConsole>(m_console); RegisterInterface<UserConfig>(Cfg); //Should be in modules? IInterServiceInventoryServices inventoryService = new OGS1InterServiceInventoryService(Cfg.InventoryUrl); // IRegionProfileRouter regionProfileService = new RegionProfileServiceProxy(); RegisterInterface<IInterServiceInventoryServices>(inventoryService); // RegisterInterface<IRegionProfileRouter>(regionProfileService); return inventoryService; } /// <summary> /// Start up the user manager /// </summary> /// <param name="inventoryService"></param> protected virtual void StartupUserServerModules() { m_log.Info("[STARTUP]: Establishing data connection"); //we only need core components so we can request them from here IInterServiceInventoryServices inventoryService; TryGet<IInterServiceInventoryServices>(out inventoryService); CommunicationsManager commsManager = new AgentDomainCommsManager(inventoryService); //setup database access service, for now this has to be created before the other modules. m_userDataBaseService = new UserDataBaseService(commsManager); m_userDataBaseService.Initialise(this); //TODO: change these modules so they fetch the databaseService class in the PostInitialise method m_userManager = new UserManager(m_userDataBaseService); m_userManager.Initialise(this); m_avatarAppearanceModule = new UserServerAvatarAppearanceModule(m_userDataBaseService); m_avatarAppearanceModule.Initialise(this); m_friendsModule = new UserServerFriendsModule(m_userDataBaseService); m_friendsModule.Initialise(this); m_consoleCommandModule = new AgentDomainCommandModule(); m_consoleCommandModule.Initialise(this); m_messagesService = new MessageServersConnector(); m_messagesService.Initialise(this); m_gridInfoService = new GridInfoServiceModule(); m_gridInfoService.Initialise(this); } protected virtual void StartOtherComponents(IInterServiceInventoryServices inventoryService) { m_appearanceModule = new AvatarCreationModule(m_userDataBaseService, Cfg, inventoryService); m_appearanceModule.Initialise(this); StartupLoginService(inventoryService); // // Get the minimum defaultLevel to access to the grid // m_loginService.setloginlevel((int)Cfg.DefaultUserLevel); RegisterInterface<UserLoginService>(m_loginService); //TODO: should be done in the login service m_eventDispatcher = new AgentDomainEventDispatchModule(m_userManager, m_messagesService, m_loginService); m_eventDispatcher.Initialise(this); } /// <summary> /// Start up the login service /// </summary> /// <param name="inventoryService"></param> protected virtual void StartupLoginService(IInterServiceInventoryServices inventoryService) { m_loginService = new UserLoginService(m_userDataBaseService, m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile), Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy()); if (Cfg.EnableHGLogin) m_loginAuthService = new UserLoginAuthService(m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile), Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy()); } // ?? protected virtual void PostInitialiseModules() { m_consoleCommandModule.PostInitialise(); //it will register its Console command handlers in here m_userDataBaseService.PostInitialise(); m_messagesService.PostInitialise(); m_eventDispatcher.PostInitialise(); //it will register event handlers in here m_gridInfoService.PostInitialise(); m_userManager.PostInitialise(); m_avatarAppearanceModule.PostInitialise(); m_friendsModule.PostInitialise(); m_avatarAppearanceModule.PostInitialise(); } protected virtual void RegisterHttpHandlers() { m_loginService.RegisterHandlers(m_httpServer, Cfg.EnableLLSDLogin, true); if (m_loginAuthService != null) m_loginAuthService.RegisterHandlers(m_httpServer); m_userManager.RegisterHandlers(m_httpServer); m_friendsModule.RegisterHandlers(m_httpServer); m_avatarAppearanceModule.RegisterHandlers(m_httpServer); m_messagesService.RegisterHandlers(m_httpServer); m_gridInfoService.RegisterHandlers(m_httpServer); m_avatarAppearanceModule.RegisterHandlers(m_httpServer); } public override void ShutdownSpecific() { m_eventDispatcher.Close(); } #region IUGAIMCore protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>(); /// <summary> /// Register an Module interface. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="iface"></param> public void RegisterInterface<T>(T iface) { lock (m_moduleInterfaces) { if (!m_moduleInterfaces.ContainsKey(typeof(T))) { m_moduleInterfaces.Add(typeof(T), iface); } } } public bool TryGet<T>(out T iface) { if (m_moduleInterfaces.ContainsKey(typeof(T))) { iface = (T)m_moduleInterfaces[typeof(T)]; return true; } iface = default(T); return false; } public T Get<T>() { return (T)m_moduleInterfaces[typeof(T)]; } public BaseHttpServer GetHttpServer() { return m_httpServer; } #endregion public void TestResponse(List<InventoryFolderBase> resp) { m_console.Output("response got"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Globalization; using Microsoft.Practices.Prism.Commands; using Microsoft.Practices.Prism.Mvvm; using StockTraderRI.Infrastructure; using StockTraderRI.Infrastructure.Interfaces; using StockTraderRI.Infrastructure.Models; using StockTraderRI.Modules.Position.Interfaces; using StockTraderRI.Modules.Position.Models; using StockTraderRI.Modules.Position.Properties; namespace StockTraderRI.Modules.Position.Orders { [Export(typeof(IOrderDetailsViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public class OrderDetailsViewModel : BindableBase, IOrderDetailsViewModel { private readonly IAccountPositionService accountPositionService; private readonly IOrdersService ordersService; private TransactionInfo transactionInfo; private int? shares; private OrderType orderType = OrderType.Market; private decimal? stopLimitPrice; private TimeInForce timeInForce; private readonly List<string> errors = new List<string>(); [ImportingConstructor] public OrderDetailsViewModel(IAccountPositionService accountPositionService, IOrdersService ordersService) { this.accountPositionService = accountPositionService; this.ordersService = ordersService; this.transactionInfo = new TransactionInfo(); //use localizable enum descriptions this.AvailableOrderTypes = new ValueDescriptionList<OrderType> { new ValueDescription<OrderType>(OrderType.Limit, Resources.OrderType_Limit), new ValueDescription<OrderType>(OrderType.Market, Resources.OrderType_Market), new ValueDescription<OrderType>(OrderType.Stop, Resources.OrderType_Stop) }; this.AvailableTimesInForce = new ValueDescriptionList<TimeInForce> { new ValueDescription<TimeInForce>(TimeInForce.EndOfDay, Resources.TimeInForce_EndOfDay), new ValueDescription<TimeInForce>(TimeInForce.ThirtyDays, Resources.TimeInForce_ThirtyDays) }; this.SubmitCommand = new DelegateCommand<object>(this.Submit, this.CanSubmit); this.CancelCommand = new DelegateCommand<object>(this.Cancel); this.SetInitialValidState(); } public event EventHandler CloseViewRequested = delegate { }; public IValueDescriptionList<OrderType> AvailableOrderTypes { get; private set; } public IValueDescriptionList<TimeInForce> AvailableTimesInForce { get; private set; } public TransactionInfo TransactionInfo { get { return this.transactionInfo; } set { SetProperty(ref this.transactionInfo, value); this.OnPropertyChanged(() => this.TickerSymbol); } } public TransactionType TransactionType { get { return this.transactionInfo.TransactionType; } set { this.ValidateHasEnoughSharesToSell(this.Shares, value, false); if (this.transactionInfo.TransactionType != value) { this.transactionInfo.TransactionType = value; OnPropertyChanged(() => this.TransactionType); } } } public string TickerSymbol { get { return this.transactionInfo.TickerSymbol; } set { if (this.transactionInfo.TickerSymbol != value) { this.transactionInfo.TickerSymbol = value; OnPropertyChanged(() => this.TickerSymbol); } } } public int? Shares { get { return this.shares; } set { this.ValidateShares(value, true); this.ValidateHasEnoughSharesToSell(value, this.TransactionType, true); SetProperty(ref this.shares, value); } } public OrderType OrderType { get { return this.orderType; } set { SetProperty(ref this.orderType, value); } } public decimal? StopLimitPrice { get { return this.stopLimitPrice; } set { this.ValidateStopLimitPrice(value, true); SetProperty(ref this.stopLimitPrice, value); } } public TimeInForce TimeInForce { get { return this.timeInForce; } set { SetProperty(ref this.timeInForce, value); } } public DelegateCommand<object> SubmitCommand { get; private set; } public DelegateCommand<object> CancelCommand { get; private set; } private void SetInitialValidState() { this.ValidateShares(this.Shares, false); this.ValidateStopLimitPrice(this.StopLimitPrice, false); } private void ValidateShares(int? newSharesValue, bool throwException) { if (!newSharesValue.HasValue || newSharesValue.Value <= 0) { this.AddError("InvalidSharesRange"); if (throwException) { throw new InputValidationException(Resources.InvalidSharesRange); } } else { this.RemoveError("InvalidSharesRange"); } } private void ValidateStopLimitPrice(decimal? price, bool throwException) { if (!price.HasValue || price.Value <= 0) { this.AddError("InvalidStopLimitPrice"); if (throwException) { throw new InputValidationException(Resources.InvalidStopLimitPrice); } } else { this.RemoveError("InvalidStopLimitPrice"); } } private void ValidateHasEnoughSharesToSell(int? sharesToSell, TransactionType transactionType, bool throwException) { if (transactionType == TransactionType.Sell && !this.HoldsEnoughShares(this.TickerSymbol, sharesToSell)) { this.AddError("NotEnoughSharesToSell"); if (throwException) { throw new InputValidationException(String.Format(CultureInfo.InvariantCulture, Resources.NotEnoughSharesToSell, sharesToSell)); } } else { this.RemoveError("NotEnoughSharesToSell"); } } private void AddError(string ruleName) { if (!this.errors.Contains(ruleName)) { this.errors.Add(ruleName); this.SubmitCommand.RaiseCanExecuteChanged(); } } private void RemoveError(string ruleName) { if (this.errors.Contains(ruleName)) { this.errors.Remove(ruleName); if (this.errors.Count == 0) { this.SubmitCommand.RaiseCanExecuteChanged(); } } } private bool CanSubmit(object parameter) { return this.errors.Count == 0; } private bool HoldsEnoughShares(string symbol, int? sharesToSell) { if (!sharesToSell.HasValue) { return false; } foreach (AccountPosition accountPosition in this.accountPositionService.GetAccountPositions()) { if (accountPosition.TickerSymbol.Equals(symbol, StringComparison.OrdinalIgnoreCase)) { if (accountPosition.Shares >= sharesToSell) { return true; } else { return false; } } } return false; } private void Submit(object parameter) { if (!this.CanSubmit(parameter)) { throw new InvalidOperationException(); } var order = new Order(); order.TransactionType = this.TransactionType; order.OrderType = this.OrderType; order.Shares = this.Shares.Value; order.StopLimitPrice = this.StopLimitPrice.Value; order.TickerSymbol = this.TickerSymbol; order.TimeInForce = this.TimeInForce; ordersService.Submit(order); CloseViewRequested(this, EventArgs.Empty); } private void Cancel(object parameter) { CloseViewRequested(this, EventArgs.Empty); } } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien 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 MbUnit.Framework; using Rhino.Mocks.Interfaces; namespace Rhino.Mocks.Tests { [TestFixture] public class StubAllTest { [Test] public void StaticAccessorForStubAll() { ICat cat = MockRepository.GenerateStub<ICat>(); cat.Eyes = 2; Assert.AreEqual(2, cat.Eyes ); } [Test] public void StubAllHasPropertyBehaviorForAllProperties() { MockRepository mocks = new MockRepository(); ICat cat = mocks.Stub<ICat>(); cat.Legs = 4; Assert.AreEqual(4, cat.Legs); cat.Name = "Esther"; Assert.AreEqual("Esther", cat.Name); Assert.IsNull(cat.Species, "Should return default value if not set"); cat.Species = "Ordinary housecat"; Assert.AreEqual("Ordinary housecat", cat.Species); cat.IsDeclawed = true; Assert.IsTrue(cat.IsDeclawed); } [Test] public void StubAllHasPropertyBehaviorForAllPropertiesWhenStubbingClasses() { MockRepository mocks = new MockRepository(); Housecat housecat = mocks.Stub<Housecat>(); housecat.FurLength = 7; Assert.AreEqual(7, housecat.FurLength); housecat.Color = "Black"; Assert.AreEqual("Black", housecat.Color); } [Test] public void StubAllCanRegisterToEventsAndRaiseThem() { MockRepository mocks = new MockRepository(); ICat cat = mocks.Stub<ICat>(); cat.Hungry += null; //Note, no expectation! IEventRaiser eventRaiser = LastCall.GetEventRaiser(); bool raised = false; cat.Hungry += delegate { raised = true; }; eventRaiser.Raise(cat, EventArgs.Empty); Assert.IsTrue(raised); } [Test] public void CallingMethodOnStubAllDoesNotCreateExpectations() { MockRepository mocks = new MockRepository(); ICat cat = mocks.Stub<ICat>(); using (mocks.Record()) { cat.Legs = 4; cat.Name = "Esther"; cat.Species = "Ordinary housecat"; cat.IsDeclawed = true; cat.GetMood(); } mocks.VerifyAll(); } [Test] public void DemoStubAllLegsProperty() { ICat catStub = MockRepository.GenerateStub<ICat>(); catStub.Legs = 0; Assert.AreEqual(0, catStub.Legs); SomeClass instance = new SomeClass(catStub); instance.SetLegs(10); Assert.AreEqual(10, catStub.Legs); } [Test] public void StubAllCanCreateExpectationOnMethod() { MockRepository mocks = new MockRepository(); ICat cat = mocks.Stub<ICat>(); using (mocks.Record()) { cat.Legs = 4; cat.Name = "Esther"; cat.Species = "Ordinary housecat"; cat.IsDeclawed = true; cat.GetMood(); LastCall.Return("Happy"); } Assert.AreEqual("Happy", cat.GetMood()); mocks.VerifyAll(); } [Test] public void StubAllCanHandlePropertiesGettingRegisteredMultipleTimes() { MockRepository mocks = new MockRepository(); SpecificFish fish = mocks.Stub<SpecificFish>(); fish.IsFreshWater = true; Assert.IsTrue(fish.IsFreshWater); } } public interface ICat : IAnimal { bool IsDeclawed { get; set; } } public class Feline { private int _furLength; public virtual int FurLength { get { return _furLength; } set { _furLength = value; } } } public class Housecat : Feline { private String _color; public virtual String Color { get { return _color; } set { _color = value; } } } public interface IFish { bool IsFreshWater { get; set; } } public abstract class Fish : IFish { public abstract bool IsFreshWater { get; set; } } public class SpecificFish : Fish { private bool _isFreshWater; public override bool IsFreshWater { get { return _isFreshWater; } set { _isFreshWater = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization.Policy; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Mvc.Authorization { /// <summary> /// An implementation of <see cref="IAsyncAuthorizationFilter"/> which applies a specific /// <see cref="AuthorizationPolicy"/>. MVC recognizes the <see cref="AuthorizeAttribute"/> and adds an instance of /// this filter to the associated action or controller. /// </summary> public class AuthorizeFilter : IAsyncAuthorizationFilter, IFilterFactory { /// <summary> /// Initializes a new <see cref="AuthorizeFilter"/> instance. /// </summary> public AuthorizeFilter() : this(authorizeData: new[] { new AuthorizeAttribute() }) { } /// <summary> /// Initialize a new <see cref="AuthorizeFilter"/> instance. /// </summary> /// <param name="policy">Authorization policy to be used.</param> public AuthorizeFilter(AuthorizationPolicy policy) { if (policy == null) { throw new ArgumentNullException(nameof(policy)); } Policy = policy; } /// <summary> /// Initialize a new <see cref="AuthorizeFilter"/> instance. /// </summary> /// <param name="policyProvider">The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names.</param> /// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param> public AuthorizeFilter(IAuthorizationPolicyProvider policyProvider, IEnumerable<IAuthorizeData> authorizeData) : this(authorizeData) { if (policyProvider == null) { throw new ArgumentNullException(nameof(policyProvider)); } PolicyProvider = policyProvider; } /// <summary> /// Initializes a new instance of <see cref="AuthorizeFilter"/>. /// </summary> /// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param> public AuthorizeFilter(IEnumerable<IAuthorizeData> authorizeData) { if (authorizeData == null) { throw new ArgumentNullException(nameof(authorizeData)); } AuthorizeData = authorizeData; } /// <summary> /// Initializes a new instance of <see cref="AuthorizeFilter"/>. /// </summary> /// <param name="policy">The name of the policy to require for authorization.</param> public AuthorizeFilter(string policy) : this(new[] { new AuthorizeAttribute(policy) }) { } /// <summary> /// The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names. /// </summary> public IAuthorizationPolicyProvider? PolicyProvider { get; } /// <summary> /// The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>. /// </summary> public IEnumerable<IAuthorizeData>? AuthorizeData { get; } /// <summary> /// Gets the authorization policy to be used. /// </summary> /// <remarks> /// If<c>null</c>, the policy will be constructed using /// <see cref="AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProvider, IEnumerable{IAuthorizeData})"/>. /// </remarks> public AuthorizationPolicy? Policy { get; } bool IFilterFactory.IsReusable => true; // Computes the actual policy for this filter using either Policy or PolicyProvider + AuthorizeData private async ValueTask<AuthorizationPolicy> ComputePolicyAsync() { if (Policy != null) { return Policy; } if (PolicyProvider == null) { throw new InvalidOperationException( Resources.FormatAuthorizeFilter_AuthorizationPolicyCannotBeCreated( nameof(AuthorizationPolicy), nameof(IAuthorizationPolicyProvider))); } return (await AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData!))!; } internal async Task<AuthorizationPolicy> GetEffectivePolicyAsync(AuthorizationFilterContext context) { // Combine all authorize filters into single effective policy that's only run on the closest filter var builder = new AuthorizationPolicyBuilder(await ComputePolicyAsync()); for (var i = 0; i < context.Filters.Count; i++) { if (ReferenceEquals(this, context.Filters[i])) { continue; } if (context.Filters[i] is AuthorizeFilter authorizeFilter) { // Combine using the explicit policy, or the dynamic policy provider builder.Combine(await authorizeFilter.ComputePolicyAsync()); } } var endpoint = context.HttpContext.GetEndpoint(); if (endpoint != null) { // When doing endpoint routing, MVC does not create filters for any authorization specific metadata i.e [Authorize] does not // get translated into AuthorizeFilter. Consequently, there are some rough edges when an application uses a mix of AuthorizeFilter // explicilty configured by the user (e.g. global auth filter), and uses endpoint metadata. // To keep the behavior of AuthFilter identical to pre-endpoint routing, we will gather auth data from endpoint metadata // and produce a policy using this. This would mean we would have effectively run some auth twice, but it maintains compat. var policyProvider = PolicyProvider ?? context.HttpContext.RequestServices.GetRequiredService<IAuthorizationPolicyProvider>(); var endpointAuthorizeData = endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>(); var endpointPolicy = await AuthorizationPolicy.CombineAsync(policyProvider, endpointAuthorizeData); if (endpointPolicy != null) { builder.Combine(endpointPolicy); } } return builder.Build(); } /// <inheritdoc /> public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!context.IsEffectivePolicy(this)) { return; } // IMPORTANT: Changes to authorization logic should be mirrored in security's AuthorizationMiddleware var effectivePolicy = await GetEffectivePolicyAsync(context); if (effectivePolicy == null) { return; } var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService<IPolicyEvaluator>(); var authenticateResult = await policyEvaluator.AuthenticateAsync(effectivePolicy, context.HttpContext); // Allow Anonymous skips all authorization if (HasAllowAnonymous(context)) { return; } var authorizeResult = await policyEvaluator.AuthorizeAsync(effectivePolicy, authenticateResult, context.HttpContext, context); if (authorizeResult.Challenged) { context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray()); } else if (authorizeResult.Forbidden) { context.Result = new ForbidResult(effectivePolicy.AuthenticationSchemes.ToArray()); } } IFilterMetadata IFilterFactory.CreateInstance(IServiceProvider serviceProvider) { if (Policy != null || PolicyProvider != null) { // The filter is fully constructed. Use the current instance to authorize. return this; } Debug.Assert(AuthorizeData != null); var policyProvider = serviceProvider.GetRequiredService<IAuthorizationPolicyProvider>(); return AuthorizationApplicationModelProvider.GetFilter(policyProvider, AuthorizeData); } private static bool HasAllowAnonymous(AuthorizationFilterContext context) { var filters = context.Filters; for (var i = 0; i < filters.Count; i++) { if (filters[i] is IAllowAnonymousFilter) { return true; } } // When doing endpoint routing, MVC does not add AllowAnonymousFilters for AllowAnonymousAttributes that // were discovered on controllers and actions. To maintain compat with 2.x, // we'll check for the presence of IAllowAnonymous in endpoint metadata. var endpoint = context.HttpContext.GetEndpoint(); if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null) { return true; } return false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ProtectionPolicyOperationStatusesOperations operations. /// </summary> internal partial class ProtectionPolicyOperationStatusesOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectionPolicyOperationStatusesOperations { /// <summary> /// Initializes a new instance of the ProtectionPolicyOperationStatusesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectionPolicyOperationStatusesOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Provides the status of the asynchronous operations like backup, restore. /// The status can be in progress, completed or failed. You can refer to the /// Operation Status enum for all the possible states of an operation. Some /// operations create jobs. This method returns the list of jobs associated /// with operation. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='policyName'> /// Backup policy name whose operation's status needs to be fetched. /// </param> /// <param name='operationId'> /// Operation ID which represents an operation whose status needs to be /// fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<OperationStatus>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (policyName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyName"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("policyName", policyName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}/operations/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{policyName}", System.Uri.EscapeDataString(policyName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<OperationStatus>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatus>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory; private readonly ITextEditorFactoryService _textEditorFactoryService; private readonly ITextDocumentFactoryService _textDocumentFactoryService; private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; private readonly OutliningTaggerProvider _outliningTaggerProvider; public VisualStudioSymbolNavigationService( SVsServiceProvider serviceProvider, OutliningTaggerProvider outliningTaggerProvider) { _serviceProvider = serviceProvider; _outliningTaggerProvider = outliningTaggerProvider; var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>(); _editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>(); _textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>(); _metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>(); } public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken) { if (project == null || symbol == null) { return false; } options = options ?? project.Solution.Workspace.Options; symbol = symbol.OriginalDefinition; // Prefer visible source locations if possible. var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation()); var sourceLocation = visibleSourceLocations.Any() ? visibleSourceLocations.First() : sourceLocations.FirstOrDefault(); if (sourceLocation != null) { var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree); if (targetDocument != null) { var editorWorkspace = targetDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options); } } // We don't have a source document, so show the Metadata as Source view in a preview tab. var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault(); if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { return false; } // Should we prefer navigating to the Object Browser over metadata-as-source? if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language)) { var libraryService = project.LanguageServices.GetService<ILibraryService>(); if (libraryService == null) { return false; } var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation); if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(project); } if (navInfo != null) { var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>(); return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK; } // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen. } // Generate new source or retrieve existing source for the symbol in question var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken); var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>(); var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath); var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(); IVsUIHierarchy hierarchy; uint itemId; IOleServiceProvider localServiceProvider; IVsWindowFrame windowFrame; openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame); var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath); var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie); var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer); if (!fileAlreadyOpen) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle)); ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip)); } windowFrame.Show(); var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault(); if (openedDocument != null) { var editorWorkspace = openedDocument.Project.Solution.Workspace; var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>(); return navigationService.TryNavigateToSpan( workspace: editorWorkspace, documentId: openedDocument.Id, textSpan: result.IdentifierLocation.SourceSpan, options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true)); } return true; } public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution) { return TryNotifyForSpecificSymbol(symbol, solution); } private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution) { AssertIsForeground(); IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } int navigationHandled; int returnCode = navigationNotify.OnBeforeNavigateToSymbol( hierarchy, itemID, rqname, out navigationHandled); if (returnCode == VSConstants.S_OK && navigationHandled == 1) { return true; } return false; } public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { if (WouldNotifyToSpecificSymbol(symbol, solution, out filePath, out lineNumber, out charOffset)) { return true; } // If the symbol being considered is a constructor and no third parties choose to // navigate to the constructor, then try the constructor's containing type. if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(symbol.ContainingType, solution, out filePath, out lineNumber, out charOffset)) { return true; } filePath = null; lineNumber = 0; charOffset = 0; return false; } public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset) { AssertIsForeground(); filePath = null; lineNumber = 0; charOffset = 0; IVsHierarchy hierarchy; IVsSymbolicNavigationNotify navigationNotify; string rqname; uint itemID; if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out hierarchy, out itemID, out navigationNotify, out rqname)) { return false; } IVsHierarchy navigateToHierarchy; uint navigateToItem; int wouldNavigate; var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1]; int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol( hierarchy, itemID, rqname, out navigateToHierarchy, out navigateToItem, navigateToTextSpan, out wouldNavigate); if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1) { navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath); lineNumber = navigateToTextSpan[0].iStartLine; charOffset = navigateToTextSpan[0].iStartIndex; return true; } return false; } private bool TryGetNavigationAPIRequiredArguments( ISymbol symbol, Solution solution, out IVsHierarchy hierarchy, out uint itemID, out IVsSymbolicNavigationNotify navigationNotify, out string rqname) { AssertIsForeground(); hierarchy = null; navigationNotify = null; rqname = null; itemID = (uint)VSConstants.VSITEMID.Nil; if (!symbol.Locations.Any()) { return false; } var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource); if (!sourceLocations.Any()) { return false; } var documents = sourceLocations.Select(loc => solution.GetDocument(loc.SourceTree)).WhereNotNull(); if (!documents.Any()) { return false; } // We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from // documents we consider to be "generated" to give external language services the best // chance of participating. var generatedCodeRecognitionService = solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>(); var generatedDocuments = documents.Where(d => generatedCodeRecognitionService.IsGeneratedCode(d)); var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First(); if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID)) { return false; } navigationNotify = hierarchy as IVsSymbolicNavigationNotify; if (navigationNotify == null) { return false; } rqname = LanguageServices.RQName.From(symbol); return rqname != null; } private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID) { AssertIsForeground(); var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace != null) { var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id); hierarchy = hostProject.Hierarchy; itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); return true; } hierarchy = null; itemID = (uint)VSConstants.VSITEMID.Nil; return false; } private IVsRunningDocumentTable GetRunningDocumentTable() { var runningDocumentTable = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>(); Debug.Assert(runningDocumentTable != null); return runningDocumentTable; } } }
using System; using UnityEngine; namespace UnityStandardAssets.Vehicles.Aeroplane { [RequireComponent(typeof (Rigidbody))] public class AeroplaneController : MonoBehaviour { [SerializeField] private float m_MaxEnginePower = 40f; // The maximum output of the engine. [SerializeField] private float m_Lift = 0.002f; // The amount of lift generated by the aeroplane moving forwards. [SerializeField] private float m_ZeroLiftSpeed = 300; // The speed at which lift is no longer applied. [SerializeField] private float m_RollEffect = 1f; // The strength of effect for roll input. [SerializeField] private float m_PitchEffect = 1f; // The strength of effect for pitch input. [SerializeField] private float m_YawEffect = 0.2f; // The strength of effect for yaw input. [SerializeField] private float m_BankedTurnEffect = 0.5f; // The amount of turn from doing a banked turn. [SerializeField] private float m_AerodynamicEffect = 0.02f; // How much aerodynamics affect the speed of the aeroplane. [SerializeField] private float m_AutoTurnPitch = 0.5f; // How much the aeroplane automatically pitches when in a banked turn. [SerializeField] private float m_AutoRollLevel = 0.2f; // How much the aeroplane tries to level when not rolling. [SerializeField] private float m_AutoPitchLevel = 0.2f; // How much the aeroplane tries to level when not pitching. [SerializeField] private float m_AirBrakesEffect = 3f; // How much the air brakes effect the drag. [SerializeField] private float m_ThrottleChangeSpeed = 0.3f; // The speed with which the throttle changes. [SerializeField] private float m_DragIncreaseFactor = 0.001f; // how much drag should increase with speed. public float HumanPower = 0; public ForceAdapter ForceAdaptor; public float Altitude { get; private set; } // The aeroplane's height above the ground. public float Throttle { get; private set; } // The amount of throttle being used. public bool AirBrakes { get; private set; } // Whether or not the air brakes are being applied. public float ForwardSpeed { get; private set; } // How fast the aeroplane is traveling in it's forward direction. public float EnginePower { get; private set; } // How much power the engine is being given. public float MaxEnginePower{ get { return m_MaxEnginePower; }} // The maximum output of the engine. public float RollAngle { get; private set; } public float PitchAngle { get; private set; } public float RollInput { get; private set; } public float PitchInput { get; private set; } public float YawInput { get; private set; } public float ThrottleInput { get; private set; } private float m_OriginalDrag; // The drag when the scene starts. private float m_OriginalAngularDrag; // The angular drag when the scene starts. private float m_AeroFactor; private bool m_Immobilized = false; // used for making the plane uncontrollable, i.e. if it has been hit or crashed. private float m_BankedTurnAmount; private Rigidbody m_Rigidbody; WheelCollider[] m_WheelColliders; private void Start() { m_Rigidbody = GetComponent<Rigidbody>(); // Store original drag settings, these are modified during flight. m_OriginalDrag = m_Rigidbody.drag; m_OriginalAngularDrag = m_Rigidbody.angularDrag; for (int i = 0; i < transform.childCount; i++ ) { foreach (var componentsInChild in transform.GetChild(i).GetComponentsInChildren<WheelCollider>()) { componentsInChild.motorTorque = 0.18f; } } } public void Move(float rollInput, float pitchInput, float yawInput, float throttleInput, bool airBrakes) { // transfer input parameters into properties.s RollInput = rollInput; PitchInput = pitchInput; YawInput = yawInput; ThrottleInput = throttleInput; AirBrakes = airBrakes; HumanPower = ForceAdaptor.getHumanPower(); Debug.Log ("AirplaneController got human power of " + HumanPower); ClampInputs(); CalculateRollAndPitchAngles(); AutoLevel(); CalculateForwardSpeed(); ControlThrottle(); CalculateDrag(); CaluclateAerodynamicEffect(); CalculateLinearForces(); CalculateTorque(); CalculateAltitude(); } private void ClampInputs() { // clamp the inputs to -1 to 1 range RollInput = Mathf.Clamp(RollInput, -1, 1); PitchInput = Mathf.Clamp(PitchInput, -1, 1); YawInput = Mathf.Clamp(YawInput, -1, 1); ThrottleInput = Mathf.Clamp(ThrottleInput, -1, 1); } private void CalculateRollAndPitchAngles() { // Calculate roll & pitch angles // Calculate the flat forward direction (with no y component). var flatForward = transform.forward; flatForward.y = 0; // If the flat forward vector is non-zero (which would only happen if the plane was pointing exactly straight upwards) if (flatForward.sqrMagnitude > 0) { flatForward.Normalize(); // calculate current pitch angle var localFlatForward = transform.InverseTransformDirection(flatForward); PitchAngle = Mathf.Atan2(localFlatForward.y, localFlatForward.z); // calculate current roll angle var flatRight = Vector3.Cross(Vector3.up, flatForward); var localFlatRight = transform.InverseTransformDirection(flatRight); RollAngle = Mathf.Atan2(localFlatRight.y, localFlatRight.x); } } private void AutoLevel() { // The banked turn amount (between -1 and 1) is the sine of the roll angle. // this is an amount applied to elevator input if the user is only using the banking controls, // because that's what people expect to happen in games! m_BankedTurnAmount = Mathf.Sin(RollAngle); // auto level roll, if there's no roll input: if (RollInput == 0f) { RollInput = -RollAngle*m_AutoRollLevel; } // auto correct pitch, if no pitch input (but also apply the banked turn amount) if (PitchInput == 0f) { PitchInput = -PitchAngle*m_AutoPitchLevel; PitchInput -= Mathf.Abs(m_BankedTurnAmount*m_BankedTurnAmount*m_AutoTurnPitch); } } private void CalculateForwardSpeed() { // Forward speed is the speed in the planes's forward direction (not the same as its velocity, eg if falling in a stall) var localVelocity = transform.InverseTransformDirection(m_Rigidbody.velocity); ForwardSpeed = Mathf.Max(0, localVelocity.z); } private void ControlThrottle() { m_ThrottleChangeSpeed = (float)((HumanPower / (float)10.0)) * 300f; // override throttle if immobilized if (m_Immobilized) { ThrottleInput = -0.5f; } Debug.Log("Throttle Change Speed is " + m_ThrottleChangeSpeed.ToString()); // Adjust throttle based on throttle input (or immobilized state) Throttle = Mathf.Clamp01(Throttle + ThrottleInput*Time.deltaTime*m_ThrottleChangeSpeed); Debug.Log("Throttle is " + Throttle.ToString()); // current engine power is just: EnginePower = Throttle*m_MaxEnginePower; Debug.Log("Engine Power is " + EnginePower.ToString()); } private void CalculateDrag() { // increase the drag based on speed, since a constant drag doesn't seem "Real" (tm) enough float extraDrag = m_Rigidbody.velocity.magnitude*m_DragIncreaseFactor; // Air brakes work by directly modifying drag. This part is actually pretty realistic! m_Rigidbody.drag = (AirBrakes ? (m_OriginalDrag + extraDrag)*m_AirBrakesEffect : m_OriginalDrag + extraDrag); // Forward speed affects angular drag - at high forward speed, it's much harder for the plane to spin m_Rigidbody.angularDrag = m_OriginalAngularDrag*ForwardSpeed; } private void CaluclateAerodynamicEffect() { // "Aerodynamic" calculations. This is a very simple approximation of the effect that a plane // will naturally try to align itself in the direction that it's facing when moving at speed. // Without this, the plane would behave a bit like the asteroids spaceship! if (m_Rigidbody.velocity.magnitude > 0) { // compare the direction we're pointing with the direction we're moving: m_AeroFactor = Vector3.Dot(transform.forward, m_Rigidbody.velocity.normalized); // multipled by itself results in a desirable rolloff curve of the effect m_AeroFactor *= m_AeroFactor; // Finally we calculate a new velocity by bending the current velocity direction towards // the the direction the plane is facing, by an amount based on this aeroFactor var newVelocity = Vector3.Lerp(m_Rigidbody.velocity, transform.forward*ForwardSpeed, m_AeroFactor*ForwardSpeed*m_AerodynamicEffect*Time.deltaTime); m_Rigidbody.velocity = newVelocity; // also rotate the plane towards the direction of movement - this should be a very small effect, but means the plane ends up // pointing downwards in a stall m_Rigidbody.rotation = Quaternion.Slerp(m_Rigidbody.rotation, Quaternion.LookRotation(m_Rigidbody.velocity, transform.up), m_AerodynamicEffect*Time.deltaTime); } } private void CalculateLinearForces() { // Now calculate forces acting on the aeroplane: // we accumulate forces into this variable: var forces = Vector3.zero; // Add the engine power in the forward direction forces += EnginePower*transform.forward; // The direction that the lift force is applied is at right angles to the plane's velocity (usually, this is 'up'!) var liftDirection = Vector3.Cross(m_Rigidbody.velocity, transform.right).normalized; // The amount of lift drops off as the plane increases speed - in reality this occurs as the pilot retracts the flaps // shortly after takeoff, giving the plane less drag, but less lift. Because we don't simulate flaps, this is // a simple way of doing it automatically: var zeroLiftFactor = Mathf.InverseLerp(m_ZeroLiftSpeed, 0, ForwardSpeed); // Calculate and add the lift power var liftPower = ForwardSpeed*ForwardSpeed*m_Lift*zeroLiftFactor*m_AeroFactor; forces += liftPower*liftDirection; // Apply the calculated forces to the the Rigidbody m_Rigidbody.AddForce(forces); } private void CalculateTorque() { // We accumulate torque forces into this variable: var torque = Vector3.zero; // Add torque for the pitch based on the pitch input. torque += PitchInput*m_PitchEffect*transform.right; // Add torque for the yaw based on the yaw input. torque += YawInput*m_YawEffect*transform.up; // Add torque for the roll based on the roll input. torque += -RollInput*m_RollEffect*transform.forward; // Add torque for banked turning. torque += m_BankedTurnAmount*m_BankedTurnEffect*transform.up; // The total torque is multiplied by the forward speed, so the controls have more effect at high speed, // and little effect at low speed, or when not moving in the direction of the nose of the plane // (i.e. falling while stalled) m_Rigidbody.AddTorque(torque*ForwardSpeed*m_AeroFactor); } private void CalculateAltitude() { // Altitude calculations - we raycast downwards from the aeroplane // starting a safe distance below the plane to avoid colliding with any of the plane's own colliders var ray = new Ray(transform.position - Vector3.up*10, -Vector3.up); RaycastHit hit; Altitude = Physics.Raycast(ray, out hit) ? hit.distance + 10 : transform.position.y; } // Immobilize can be called from other objects, for example if this plane is hit by a weapon and should become uncontrollable public void Immobilize() { m_Immobilized = true; } // Reset is called via the ObjectResetter script, if present. public void Reset() { m_Immobilized = false; } /// <summary> /// Capture event handling /// </summary> bool cap = false; private string ste = "You got Evie!"; public UnityEngine.UI.RawImage trump; public UnityEngine.UI.RawImage trump2; public UnityEngine.UI.RawImage foxie; public UnityEngine.UI.RawImage foxie2; public Texture myFirstImage; void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Pick Up")) { other.gameObject.SetActive(false); cap = true; trump.texture = myFirstImage; trump2.texture = myFirstImage; } if (other.gameObject.CompareTag("Pick Up2")) { other.gameObject.SetActive(false); cap = true; foxie.texture = myFirstImage; foxie2.texture = myFirstImage; } } void OnGUI() { GUIStyle myStyle = new GUIStyle(); myStyle.fontSize = 50; if (cap) { ste = GUI.TextArea(new Rect(500, 200, 200, 100), ste, myStyle); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Globalization; using System.Reflection; using Signum.Utilities.Reflection; using System.Linq.Expressions; using Signum.Utilities.ExpressionTrees; using System.Collections.Concurrent; using System.IO; using System.Xml.Linq; namespace Signum.Utilities { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface, Inherited = true)] public class DescriptionOptionsAttribute : Attribute { public DescriptionOptions Options { get; set; } public DescriptionOptionsAttribute(DescriptionOptions options) { this.Options = options; } } [Flags] public enum DescriptionOptions { None = 0, Members = 1, Description = 2, PluralDescription = 4, Gender = 8, All = Members | Description | PluralDescription | Gender, } public static class DescriptionOptionsExtensions { public static bool IsSetAssert(this DescriptionOptions opts, DescriptionOptions flag, MemberInfo member) { if ((opts.IsSet(DescriptionOptions.PluralDescription) || opts.IsSet(DescriptionOptions.Gender)) && !opts.IsSet(DescriptionOptions.Description)) throw new InvalidOperationException("{0} has {1} set also requires {2}".FormatWith(member.Name, opts, DescriptionOptions.Description)); if ((member is PropertyInfo || member is FieldInfo) && (opts.IsSet(DescriptionOptions.PluralDescription) || opts.IsSet(DescriptionOptions.Gender) || opts.IsSet(DescriptionOptions.Members))) throw new InvalidOperationException("Member {0} has {1} set".FormatWith(member.Name, opts)); return opts.IsSet(flag); } public static bool IsSet(this DescriptionOptions opts, DescriptionOptions flag) { return (opts & flag) == flag; } } [AttributeUsage(AttributeTargets.Class)] public class PluralDescriptionAttribute : Attribute { public string PluralDescription { get; private set; } public PluralDescriptionAttribute(string pluralDescription) { this.PluralDescription = pluralDescription; } } [AttributeUsage(AttributeTargets.Class)] public class GenderAttribute : Attribute { public char Gender { get; set; } public GenderAttribute(char gender) { this.Gender = gender; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = true)] public class DefaultAssemblyCultureAttribute : Attribute { public string DefaultCulture { get; private set; } public DefaultAssemblyCultureAttribute(string defaultCulture) { this.DefaultCulture = defaultCulture; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class FormatAttribute : Attribute { public string Format { get; private set; } public FormatAttribute(string format) { this.Format = format; } } [AttributeUsage(AttributeTargets.Property)] public class TimeSpanDateFormatAttribute : Attribute { public string Format { get; private set; } public TimeSpanDateFormatAttribute(string format) { Format = format; } } public static class DescriptionManager { public static Func<Type, string> CleanTypeName = t => t.Name; //To allow MyEntityEntity public static Func<Type, Type> CleanType = t => t; //To allow Lite<T> public static string TranslationDirectory = Path.Combine(Path.GetDirectoryName(new Uri(typeof(DescriptionManager).Assembly.CodeBase!).LocalPath)!, "Translations"); public static event Func<Type, DescriptionOptions?> DefaultDescriptionOptions = t => t.IsEnum && t.Name.EndsWith("Message") ? DescriptionOptions.Members : (DescriptionOptions?)null; public static event Func<MemberInfo, bool> ShouldLocalizeMemeber = m => true; public static event Action<CultureInfo, MemberInfo>? NotLocalizedMember; public static Dictionary<Type, Func<MemberInfo, string>> ExternalEnums = new Dictionary<Type, Func<MemberInfo, string>> { { typeof(DayOfWeek), m => CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int)((FieldInfo)m).GetValue(null)!] } }; static string Fallback(Type type, Func<LocalizedType, string?> typeValue, Action<LocalizedType> notLocalized) { var cc = CultureInfo.CurrentUICulture; { var loc = GetLocalizedType(type, cc); if (loc != null) { string? result = typeValue(loc); if (result != null) return result; } } if (cc.Parent.Name.HasText()) { var loc = GetLocalizedType(type, cc.Parent); if (loc != null) { string? result = typeValue(loc); if (result != null) return result; } } var defaultCulture = LocalizedAssembly.GetDefaultAssemblyCulture(type.Assembly); { var loc = GetLocalizedType(type, CultureInfo.GetCultureInfo(defaultCulture)); if (loc == null) throw new InvalidOperationException("Type {0} is not localizable".FormatWith(type.TypeName())); if (notLocalized != null) notLocalized.Invoke(loc); return typeValue(loc)!; } } public static string NiceName(this Type type) { type = CleanType(type); if (!LocalizedAssembly.HasDefaultAssemblyCulture(type.Assembly)) { return type.GetCustomAttribute<DescriptionAttribute>()?.Description ?? type.Name.NiceName(); } var result = Fallback(type, lt => lt.Description, lt => OnNotLocalizedMember(type)); if (result != null) return result; return DefaultTypeDescription(type); } public static string NicePluralName(this Type type) { type = CleanType(type); var result = Fallback(type, lt => lt.PluralDescription, lt => OnNotLocalizedMember(type)); if (result != null) return result; return type.GetCustomAttribute<PluralDescriptionAttribute>()?.PluralDescription ?? NaturalLanguageTools.Pluralize(DefaultTypeDescription(type)); } public static string NiceToString(this Enum a, params object?[] args) { return a.NiceToString().FormatWith(args); } public static string NiceToString(this Enum a) { var fi = EnumFieldCache.Get(a.GetType()).TryGetC(a); if (fi != null) return GetMemberNiceName(fi) ?? DefaultMemberDescription(fi); return a.ToString().NiceName(); } public static string NiceName<R>(Expression<Func<R>> expressionToProperty) { return ReflectionTools.GetPropertyInfo(expressionToProperty).NiceName(); } public static string NiceName<T, R>(Expression<Func<T, R>> expressionToProperty) { return ReflectionTools.GetPropertyInfo(expressionToProperty).NiceName(); } public static string NiceName(this FieldInfo fi) { return GetMemberNiceName(fi) ?? DefaultMemberDescription(fi); } public static string NiceName(this PropertyInfo pi) { return GetMemberNiceName(pi) ?? (pi.IsDefaultName() ? pi.PropertyType.NiceName() : DefaultMemberDescription(pi)); } public static bool IsDefaultName(this PropertyInfo pi) { return pi.Name == CleanTypeName(CleanType(pi.PropertyType)); } static string GetMemberNiceName(MemberInfo memberInfo) { //var cc = CultureInfo.CurrentUICulture; var type = memberInfo.DeclaringType!; if (!LocalizedAssembly.HasDefaultAssemblyCulture(type.Assembly)) { var f = ExternalEnums.TryGetC(type); if (f != null) return f(memberInfo); return memberInfo.GetCustomAttribute<DescriptionAttribute>()?.Description ?? memberInfo.Name.NiceName(); } var result = Fallback(type, lt => lt.Members!.TryGetC(memberInfo.Name), lt => OnNotLocalizedMember(memberInfo)); return result; } private static void OnNotLocalizedMember(MemberInfo memberInfo) { NotLocalizedMember?.Invoke(CultureInfo.CurrentUICulture, memberInfo); } public static char? GetGender(this Type type) { type = CleanType(type); var cc = CultureInfo.CurrentUICulture; if (!LocalizedAssembly.HasDefaultAssemblyCulture(type.Assembly)) { return type.GetCustomAttribute<GenderAttribute>()?.Gender ?? NaturalLanguageTools.GetGender(type.NiceName()); } var lt = GetLocalizedType(type, cc); if (lt != null && lt.Gender != null) return lt.Gender; if (cc.Parent.Name.HasText()) { lt = GetLocalizedType(type, cc.Parent); if (lt != null) return lt.Gender; } return null; } static ConcurrentDictionary<CultureInfo, ConcurrentDictionary<Assembly, LocalizedAssembly?>> localizations = new ConcurrentDictionary<CultureInfo, ConcurrentDictionary<Assembly, LocalizedAssembly?>>(); public static LocalizedType? GetLocalizedType(Type type, CultureInfo cultureInfo) { var la = GetLocalizedAssembly(type.Assembly, cultureInfo); if (la == null) return null; var result = la.Types.TryGetC(type); if(result != null) return result; if(type.IsGenericType && !type.IsGenericTypeDefinition) return la.Types.TryGetC(type.GetGenericTypeDefinition()); return null; } public static LocalizedAssembly? GetLocalizedAssembly(Assembly assembly, CultureInfo cultureInfo) { return localizations .GetOrAdd(cultureInfo, ci => new ConcurrentDictionary<Assembly, LocalizedAssembly?>()) .GetOrAdd(assembly, (Assembly a) => LocalizedAssembly.ImportXml(assembly, cultureInfo, forceCreate: false)); } internal static DescriptionOptions? OnDefaultDescriptionOptions(Type type) { if (DescriptionManager.DefaultDescriptionOptions == null) return null; foreach (var func in DescriptionManager.DefaultDescriptionOptions.GetInvocationListTyped()) { var result = func(type); if (result != null) return result.Value; } return null; } public static bool OnShouldLocalizeMember(MemberInfo m) { if (ShouldLocalizeMemeber == null) return true; foreach (var func in ShouldLocalizeMemeber.GetInvocationListTyped()) { if (!func(m)) return false; } return true; } public static Action? Invalidated; public static void Invalidate() { localizations.Clear(); Invalidated?.Invoke(); } internal static string DefaultTypeDescription(Type type) { return type.GetCustomAttribute<DescriptionAttribute>()?.Description ?? DescriptionManager.CleanTypeName(type).SpacePascal(); } internal static string DefaultMemberDescription(MemberInfo m) { return m.GetCustomAttribute<DescriptionAttribute>()?.Description ?? m.Name.NiceName(); } } public class LocalizedAssembly { public Assembly Assembly; public CultureInfo Culture; public bool IsDefault; #pragma warning disable CS8618 // Non-nullable field is uninitialized. LocalizedAssembly() { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public Dictionary<Type, LocalizedType> Types = new Dictionary<Type, LocalizedType>(); public static string TranslationFileName(Assembly assembly, CultureInfo cultureInfo) { return Path.Combine(DescriptionManager.TranslationDirectory, "{0}.{1}.xml".FormatWith(assembly.GetName().Name, cultureInfo.Name)); } public static DescriptionOptions GetDescriptionOptions(Type type) { var doa = type.GetCustomAttribute<DescriptionOptionsAttribute>(true); if (doa != null) return type.IsGenericTypeDefinition ? doa.Options & DescriptionOptions.Members : doa.Options; DescriptionOptions? def = DescriptionManager.OnDefaultDescriptionOptions(type); if (def != null) return type.IsGenericTypeDefinition ? def.Value & DescriptionOptions.Members : def.Value; if (DescriptionManager.ExternalEnums.ContainsKey(type)) return DescriptionOptions.Members; return DescriptionOptions.None; } public static string GetDefaultAssemblyCulture(Assembly assembly) { var defaultLoc = assembly.GetCustomAttribute<DefaultAssemblyCultureAttribute>(); if (defaultLoc == null) throw new InvalidOperationException($"No {nameof(DefaultAssemblyCultureAttribute)} found in {assembly.GetName().Name}"); return defaultLoc.DefaultCulture; } public static bool HasDefaultAssemblyCulture(Assembly assembly) { var defaultLoc = assembly.GetCustomAttribute<DefaultAssemblyCultureAttribute>(); return defaultLoc != null; } public void ExportXml() { var doc = ToXml(); string fileName = TranslationFileName(Assembly, Culture); doc.Save(fileName); DescriptionManager.Invalidate(); } public XDocument ToXml() { var doc = new XDocument(new XDeclaration("1.0", "UTF8", "yes"), new XElement("Translations", from lt in Types.Values let doa = GetDescriptionOptions(lt.Type) where doa != DescriptionOptions.None orderby lt.Type.Name select lt.ExportXml() ) ); return doc; } public static LocalizedAssembly? ImportXml(Assembly assembly, CultureInfo cultureInfo, bool forceCreate) { var defaultCulture = GetDefaultAssemblyCulture(assembly); if(defaultCulture == null) return null; bool isDefault = cultureInfo.Name == defaultCulture; string fileName = TranslationFileName(assembly, cultureInfo); XDocument? doc = !File.Exists(fileName) ? null : XDocument.Load(fileName); if (!isDefault && !forceCreate && doc == null) return null; return FromXml(assembly, cultureInfo, doc, null); } public static LocalizedAssembly FromXml(Assembly assembly, CultureInfo cultureInfo, XDocument? doc, Dictionary<string, string>? replacements /*new -> old*/) { Dictionary<string, XElement>? file = doc?.Element("Translations").Elements("Type") .Select(x => KeyValuePair.Create(x.Attribute("Name").Value, x)) .Distinct(x => x.Key) .ToDictionary(); var result = new LocalizedAssembly { Assembly = assembly, Culture = cultureInfo, IsDefault = GetDefaultAssemblyCulture(assembly) == cultureInfo.Name }; result.Types = (from t in assembly.GetTypes() let opts = GetDescriptionOptions(t) where opts != DescriptionOptions.None let x = file?.TryGetC(replacements?.TryGetC(t.Name) ?? t.Name) select LocalizedType.ImportXml(t, opts, result, x)) .ToDictionary(lt => lt.Type); return result; } public override string ToString() { return "Localized {0}".FormatWith(Assembly.GetName().Name); } } public class LocalizedType { public Type Type { get; private set; } public LocalizedAssembly Assembly { get; private set; } public DescriptionOptions Options { get; private set; } public string? Description { get; set; } public string? PluralDescription { get; set; } public char? Gender { get; set; } public Dictionary<string, string>? Members { get; set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. LocalizedType() { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public XElement ExportXml() { return new XElement("Type", new XAttribute("Name", Type.Name), !Options.IsSetAssert(DescriptionOptions.Description, Type) || Description == null || (Assembly.IsDefault && Description == DescriptionManager.DefaultTypeDescription(Type)) ? null : new XAttribute("Description", Description), !Options.IsSetAssert(DescriptionOptions.PluralDescription, Type) || PluralDescription == null || (PluralDescription == NaturalLanguageTools.Pluralize(Description!, Assembly.Culture)) ? null : new XAttribute("PluralDescription", PluralDescription), !Options.IsSetAssert(DescriptionOptions.Gender, Type) || Gender == null || (Gender == NaturalLanguageTools.GetGender(Description!, Assembly.Culture)) ? null : new XAttribute("Gender", Gender.ToString()), !Options.IsSetAssert(DescriptionOptions.Members, Type) ? null : (from m in GetMembers(Type) where DescriptionManager.OnShouldLocalizeMember(m) orderby m.Name let value = Members!.TryGetC(m.Name) where value != null && !(Assembly.IsDefault && (DescriptionManager.DefaultMemberDescription(m) == value)) select new XElement("Member", new XAttribute("Name", m.Name), new XAttribute("Description", value))) ); } const BindingFlags instanceFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; const BindingFlags staticFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; public static IEnumerable<MemberInfo> GetMembers(Type type) { if (type.IsEnum) return EnumFieldCache.Get(type).Values; else if (type.IsAbstract && type.IsSealed) // static return type.GetFields(staticFlags).Cast<MemberInfo>(); else return type.GetProperties(instanceFlags).Concat(type.GetFields(instanceFlags).Cast<MemberInfo>()); } internal static LocalizedType ImportXml(Type type, DescriptionOptions opts, LocalizedAssembly assembly, XElement x) { string? description = !opts.IsSetAssert(DescriptionOptions.Description, type) ? null : (x == null || x.Attribute("Name").Value != type.Name ? null : x.Attribute("Description")?.Value) ?? (!assembly.IsDefault ? null : DescriptionManager.DefaultTypeDescription(type)); var xMembers = x?.Elements("Member") .Select(m => KeyValuePair.Create(m.Attribute("Name").Value, m.Attribute("Description").Value)) .Distinct(m => m.Key) .ToDictionary(); LocalizedType result = new LocalizedType { Type = type, Options = opts, Assembly = assembly, Description = description, PluralDescription = !opts.IsSetAssert(DescriptionOptions.PluralDescription, type) ? null : ((x == null || x.Attribute("Name").Value != type.Name ? null : x.Attribute("PluralDescription")?.Value) ?? (!assembly.IsDefault ? null : type.GetCustomAttribute<PluralDescriptionAttribute>()?.PluralDescription) ?? (description == null ? null : NaturalLanguageTools.Pluralize(description, assembly.Culture))), Gender = !opts.IsSetAssert(DescriptionOptions.Gender, type) ? null : ((x?.Attribute("Gender")?.Value.Single()) ?? (!assembly.IsDefault ? null : type.GetCustomAttribute<GenderAttribute>()?.Gender) ?? (description == null ? null : NaturalLanguageTools.GetGender(description, assembly.Culture))), Members = !opts.IsSetAssert(DescriptionOptions.Members, type) ? null : (from m in GetMembers(type) where DescriptionManager.OnShouldLocalizeMember(m) let value = xMembers?.TryGetC(m.Name) ?? (!assembly.IsDefault ? null : DescriptionManager.DefaultMemberDescription(m)) where value != null select KeyValuePair.Create(m.Name, value)) .ToDictionary() }; return result; } public override string ToString() { return "Localized {0}".FormatWith(Type.Name); } public bool Contains(string text) { return ContainsDescription(text) || this.Members != null && this.Members.Any(m => m.Key.Contains(text, StringComparison.InvariantCultureIgnoreCase) || m.Value.Contains(text, StringComparison.InvariantCultureIgnoreCase)); } public bool ContainsDescription(string text) { return this.Type.Name.Contains(text, StringComparison.InvariantCultureIgnoreCase) || this.Description?.Contains(text, StringComparison.InvariantCultureIgnoreCase) == true || this.PluralDescription?.Contains(text, StringComparison.InvariantCultureIgnoreCase) == true; } public bool IsTypeCompleted() { if ((Options & DescriptionOptions.Description) != 0 && !this.Description.HasText()) return false; if ((Options & DescriptionOptions.PluralDescription) != 0 && !this.PluralDescription.HasText()) return false; if ((Options & DescriptionOptions.Gender) != 0 && this.Gender == null && NaturalLanguageTools.HasGenders(this.Assembly.Culture)) return false; return true; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Windows.Forms; namespace Project31.ApplicationFramework { /// <summary> /// MenuBuilderEntry is an internal class used to build Command-based menus. /// </summary> internal sealed class MenuBuilderEntry { /// <summary> /// The MenuBuilder for this MenuBuilderEntry. /// </summary> private MenuBuilder menuBuilder; /// <summary> /// Merge menu entry level. /// </summary> private int level; /// <summary> /// Gets the merge menu entry level. /// </summary> public int Level { get { return level; } } /// <summary> /// Merge menu entry position. /// </summary> private int position; /// <summary> /// Gets the merge menu entry position. /// </summary> public int Position { get { return position; } } /// <summary> /// Merge menu entry text. /// </summary> private string text; /// <summary> /// Gets the merge menu entry text. /// </summary> public string Text { get { return text; } } /// <summary> /// Merge menu entry command. /// </summary> private Command command; /// <summary> /// Gets the merge menu entry command. /// </summary> public Command Command { get { return command; } } /// <summary> /// Child merge menu entries. /// </summary> private SortedList childMergeMenuEntries = new SortedList(); /// <summary> /// Initializes a new instance of the MenuBuilderEntry class. /// </summary> public MenuBuilderEntry(MenuBuilder menuBuilder) { this.menuBuilder = menuBuilder; this.level = -1; } /// <summary> /// Initializes a new instance of the MenuBuilderEntry class. This constructor is used for /// top level and "container" menu items. /// </summary> /// <param name="position">Merge menu entry position.</param> /// <param name="text">Merge menu entry text.</param> public MenuBuilderEntry(MenuBuilder menuBuilder, int level, int position, string text) : this(menuBuilder, level, position, text, null) { } /// <summary> /// Initializes a new instance of the MenuBuilderEntry class. This constructor is used for /// the command menu entry. /// </summary> /// <param name="position">Merge menu entry position.</param> /// <param name="text">Merge menu entry text.</param> /// <param name="command">Merge menu entry command.</param> public MenuBuilderEntry(MenuBuilder menuBuilder, int level, int position, string text, Command command) { this.menuBuilder = menuBuilder; this.level = level; this.position = position; this.text = text; this.command = command; } /// <summary> /// Indexer for access child merge menu entries. /// </summary> public MenuBuilderEntry this [int position, string text] { get { string key = String.Format("{0}-{1}", position.ToString("D3"), text); return (MenuBuilderEntry)childMergeMenuEntries[key]; } set { string key = String.Format("{0}-{1}", position.ToString("D3"), text); childMergeMenuEntries[key] = value; } } /// <summary> /// Creates and returns a set of menu items from the child merge menu entries in this merge /// menu entry. /// </summary> /// <param name="mainMenu">The level at which the MenuItems will appear.</param> /// <returns>Array of menu items.</returns> public MenuItem[] CreateMenuItems() { // If this merge menu entry has no child merge menu entries, return null. if (childMergeMenuEntries.Count == 0) return null; // Construct an array list to hold the menu items being created. ArrayList menuItemArrayList = new ArrayList(); // Enumerate the child merge menu entries of this merge menu entry. foreach (MenuBuilderEntry mergeMenuEntry in childMergeMenuEntries.Values) { // Get the text of the merge menu entry. string text = mergeMenuEntry.Text; // Create the menu item for this child merge menu entry. MenuItem menuItem; bool separatorBefore, separatorAfter; if (menuBuilder.MenuType == MenuType.Main && mergeMenuEntry.level == 0) { // Level zero of a main menu. menuItem = new OwnerDrawMenuItem(menuBuilder.MenuType); separatorBefore = separatorAfter = false; } else { // Determine whether a separator before and a separator after the menu item // should be inserted. separatorBefore = text.StartsWith(SEPARATOR_TEXT); separatorAfter = text.EndsWith(SEPARATOR_TEXT); if (separatorBefore || separatorAfter) text = text.Replace(SEPARATOR_TEXT, string.Empty); // Instantiate the menu item. if (mergeMenuEntry.Command == null) menuItem = new OwnerDrawMenuItem(menuBuilder.MenuType); else menuItem = new CommandOwnerDrawMenuItem(menuBuilder.MenuType, mergeMenuEntry.Command); } // Set the menu item text. menuItem.Text = text; // If this child merge menu entry has any child merge menu entries, recursively // create their menu items. MenuItem[] childMenuItems = mergeMenuEntry.CreateMenuItems(); if (childMenuItems != null) menuItem.MenuItems.AddRange(childMenuItems); // Add the separator menu item, as needed. if (separatorBefore) menuItemArrayList.Add(MakeSeparatorMenuItem(menuBuilder.MenuType)); // Add the menu item to the array of menu items being returned. menuItemArrayList.Add(menuItem); // Add the separator menu item, as needed. if (separatorAfter) menuItemArrayList.Add(MakeSeparatorMenuItem(menuBuilder.MenuType)); } // Done. Convert the array list into a MenuItem array and return it. return (MenuItem[])menuItemArrayList.ToArray(typeof(MenuItem)); } /// <summary> /// Helper to make a separator menu item. /// </summary> /// <returns>A MenuItem that is a separator MenuItem.</returns> private static MenuItem MakeSeparatorMenuItem(MenuType menuType) { // Instantiate the separator menu item. MenuItem separatorMenuItem = new OwnerDrawMenuItem(menuType); separatorMenuItem.Text = SEPARATOR_TEXT; return separatorMenuItem; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for EventLog #if !NETCF // SSCLI 1.0 has no support for EventLog #if !SSCLI // NETMF has no support for EventLog #if !NETMF using System; using System.Diagnostics; using System.Globalization; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Writes events to the system event log. /// </summary> /// <remarks> /// <para> /// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges. /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog /// </para> /// <para> /// The <c>EventID</c> of the event log entry can be /// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// </para> /// <para> /// The <c>Category</c> of the event log entry can be /// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// </para> /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// <para> /// When configuring the EventLogAppender a mapping can be /// specified to map a logging level to an event log entry type. For example: /// </para> /// <code lang="XML"> /// &lt;mapping&gt; /// &lt;level value="ERROR" /&gt; /// &lt;eventLogEntryType value="Error" /&gt; /// &lt;/mapping&gt; /// &lt;mapping&gt; /// &lt;level value="DEBUG" /&gt; /// &lt;eventLogEntryType value="Information" /&gt; /// &lt;/mapping&gt; /// </code> /// <para> /// The Level is the standard log4net logging level and eventLogEntryType can be any value /// from the <see cref="EventLogEntryType"/> enum, i.e.: /// <list type="bullet"> /// <item><term>Error</term><description>an error event</description></item> /// <item><term>Warning</term><description>a warning event</description></item> /// <item><term>Information</term><description>an informational event</description></item> /// </list> /// </para> /// </remarks> /// <author>Aspi Havewala</author> /// <author>Douglas de la Torre</author> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Thomas Voss</author> public class EventLogAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="EventLogAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public EventLogAppender() { m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; m_logName = "Application"; // Defaults to application log m_machineName = "."; // Only log on the local machine } /// <summary> /// Initializes a new instance of the <see cref="EventLogAppender" /> class /// with the specified <see cref="ILayout" />. /// </summary> /// <param name="layout">The <see cref="ILayout" /> to use with this appender.</param> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout property")] public EventLogAppender(ILayout layout) : this() { Layout = layout; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// The name of the log where messages will be stored. /// </summary> /// <value> /// The string name of the log where messages will be stored. /// </value> /// <remarks> /// <para>This is the name of the log as it appears in the Event Viewer /// tree. The default value is to log into the <c>Application</c> /// log, this is where most applications write their events. However /// if you need a separate log for your application (or applications) /// then you should set the <see cref="LogName"/> appropriately.</para> /// <para>This should not be used to distinguish your event log messages /// from those of other applications, the <see cref="ApplicationName"/> /// property should be used to distinguish events. This property should be /// used to group together events into a single log. /// </para> /// </remarks> public string LogName { get { return m_logName; } set { m_logName = value; } } /// <summary> /// Property used to set the Application name. This appears in the /// event logs when logging. /// </summary> /// <value> /// The string used to distinguish events from different sources. /// </value> /// <remarks> /// Sets the event log source property. /// </remarks> public string ApplicationName { get { return m_applicationName; } set { m_applicationName = value; } } /// <summary> /// This property is used to return the name of the computer to use /// when accessing the event logs. Currently, this is the current /// computer, denoted by a dot "." /// </summary> /// <value> /// The string name of the machine holding the event log that /// will be logged into. /// </value> /// <remarks> /// This property cannot be changed. It is currently set to '.' /// i.e. the local machine. This may be changed in future. /// </remarks> public string MachineName { get { return m_machineName; } set { /* Currently we do not allow the machine name to be changed */; } } /// <summary> /// Add a mapping of level to <see cref="EventLogEntryType"/> - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="Level2EventLogEntryType"/> mapping to this appender. /// Each mapping defines the event log entry type for a level. /// </para> /// </remarks> public void AddMapping(Level2EventLogEntryType mapping) { m_levelMapping.Add(mapping); } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to write to the EventLog. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to write to the EventLog. /// </value> /// <remarks> /// <para> /// The system security context used to write to the EventLog. /// </para> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } /// <summary> /// Gets or sets the <c>EventId</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> /// <remarks> /// <para> /// The <c>EventID</c> of the event log entry will normally be /// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// This property provides the fallback value which defaults to 0. /// </para> /// </remarks> public int EventId { get { return m_eventId; } set { m_eventId = value; } } /// <summary> /// Gets or sets the <c>Category</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> /// <remarks> /// <para> /// The <c>Category</c> of the event log entry will normally be /// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// This property provides the fallback value which defaults to 0. /// </para> /// </remarks> public short Category { get { return m_category; } set { m_category = value; } } #endregion // Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { try { base.ActivateOptions(); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } bool sourceAlreadyExists = false; string currentLogName = null; using (SecurityContext.Impersonate(this)) { sourceAlreadyExists = EventLog.SourceExists(m_applicationName); if (sourceAlreadyExists) { currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } if (sourceAlreadyExists && currentLogName != m_logName) { LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]"); } else if (!sourceAlreadyExists) { LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]"); } string registeredLogName = null; using (SecurityContext.Impersonate(this)) { if (sourceAlreadyExists && currentLogName != m_logName) { // // Re-register this to the current application if the user has changed // the application / logfile association // EventLog.DeleteEventSource(m_applicationName, m_machineName); CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } else if (!sourceAlreadyExists) { CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } m_levelMapping.ActivateOptions(); LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]"); } catch (System.Security.SecurityException ex) { ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source " + m_applicationName + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", ex); Threshold = Level.Off; } } #endregion // Implementation of IOptionHandler /// <summary> /// Create an event log source /// </summary> /// <remarks> /// Uses different API calls under NET_2_0 /// </remarks> private static void CreateEventSource(string source, string logName, string machineName) { #if NET_2_0 EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); eventSourceCreationData.MachineName = machineName; EventLog.CreateEventSource(eventSourceCreationData); #else EventLog.CreateEventSource(source, logName, machineName); #endif } #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Writes the event to the system event log using the /// <see cref="ApplicationName"/>.</para> /// /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>) /// set then this integer will be used as the event log event id.</para> /// /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // // Write the resulting string to the event log system // int eventID = m_eventId; // Look for the EventID property object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); if (eventIDPropertyObj != null) { if (eventIDPropertyObj is int) { eventID = (int)eventIDPropertyObj; } else { string eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString == null) { eventIDPropertyString = eventIDPropertyObj.ToString(); } if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) { // Read the string property into a number int intVal; if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) { eventID = intVal; } else { ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); } } } } short category = m_category; // Look for the Category property object categoryPropertyObj = loggingEvent.LookupProperty("Category"); if (categoryPropertyObj != null) { if (categoryPropertyObj is short) { category = (short) categoryPropertyObj; } else { string categoryPropertyString = categoryPropertyObj as string; if (categoryPropertyString == null) { categoryPropertyString = categoryPropertyObj.ToString(); } if (categoryPropertyString != null && categoryPropertyString.Length > 0) { // Read the string property into a number short shortVal; if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) { category = shortVal; } else { ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); } } } } // Write to the event log try { string eventTxt = RenderLoggingEvent(loggingEvent); // There is a limit of about 32K characters for an event log message if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) { eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); } EventLogEntryType entryType = GetEntryType(loggingEvent.Level); using(SecurityContext.Impersonate(this)) { EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category); } } catch(Exception ex) { ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Get the equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/> /// </summary> /// <param name="level">the Level to convert to an EventLogEntryType</param> /// <returns>The equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/></returns> /// <remarks> /// Because there are fewer applicable <see cref="EventLogEntryType"/> /// values to use in logging levels than there are in the /// <see cref="Level"/> this is a one way mapping. There is /// a loss of information during the conversion. /// </remarks> virtual protected EventLogEntryType GetEntryType(Level level) { // see if there is a specified lookup. Level2EventLogEntryType entryType = m_levelMapping.Lookup(level) as Level2EventLogEntryType; if (entryType != null) { return entryType.EventLogEntryType; } // Use default behavior if (level >= Level.Error) { return EventLogEntryType.Error; } else if (level == Level.Warn) { return EventLogEntryType.Warning; } // Default setting return EventLogEntryType.Information; } #endregion // Protected Instance Methods #region Private Instance Fields /// <summary> /// The log name is the section in the event logs where the messages /// are stored. /// </summary> private string m_logName; /// <summary> /// Name of the application to use when logging. This appears in the /// application column of the event log named by <see cref="m_logName"/>. /// </summary> private string m_applicationName; /// <summary> /// The name of the machine which holds the event log. This is /// currently only allowed to be '.' i.e. the current machine. /// </summary> private string m_machineName; /// <summary> /// Mapping from level object to EventLogEntryType /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; /// <summary> /// The event ID to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> private int m_eventId = 0; /// <summary> /// The event category to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> private short m_category = 0; #endregion // Private Instance Fields #region Level2EventLogEntryType LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> /// <remarks> /// <para> /// Defines the mapping between a level and its event log entry type. /// </para> /// </remarks> public class Level2EventLogEntryType : LevelMappingEntry { private EventLogEntryType m_entryType; /// <summary> /// The <see cref="EventLogEntryType"/> for this entry /// </summary> /// <remarks> /// <para> /// Required property. /// The <see cref="EventLogEntryType"/> for this entry /// </para> /// </remarks> public EventLogEntryType EventLogEntryType { get { return m_entryType; } set { m_entryType = value; } } } #endregion // LevelColors LevelMapping Entry #region Private Static Fields /// <summary> /// The fully qualified type of the EventLogAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(EventLogAppender); /// <summary> /// The maximum size supported by default. /// </summary> /// <remarks> /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 /// may leave space for a two byte null terminator of #0#0). The 32766 max /// length is what the .NET 4.0 source code checks for, but this is WRONG! /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() /// for the use of the 32766 max size. /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; /// <summary> /// The maximum size supported by a windows operating system that is vista /// or newer. /// </summary> /// <remarks> /// See ReportEvent API: /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx /// ReportEvent's lpStrings parameter: /// "A pointer to a buffer containing an array of /// null-terminated strings that are merged into the message before Event Viewer /// displays the string to the user. This parameter must be a valid pointer /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." /// /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows /// Vista or higher! It may succeed for a while...but you will eventually run into the /// error: "System.ComponentModel.Win32Exception : A device attached to the system is /// not functioning", and the event log will then be corrupt (I was able to corrupt /// an event log using a length of 31877 on Windows 7). /// /// The max size for Windows Vista or higher is documented here: /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. /// Going over this size may succeed a few times but the buffer will overrun and /// eventually corrupt the log (based on testing). /// /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the /// buffer, given enough time). /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; /// <summary> /// The maximum size that the operating system supports for /// a event log message. /// </summary> /// <remarks> /// Used to determine the maximum string length that can be written /// to the operating system event log and eventually truncate a string /// that exceeds the limits. /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); /// <summary> /// This method determines the maximum event log message size allowed for /// the current environment. /// </summary> /// <returns></returns> private static int GetMaxEventLogMessageSize() { if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER; return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; } #endregion Private Static Fields } } #endif // !NETMF #endif // !SSCLI #endif // !NETCF
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using System.Drawing; namespace HtmlRenderer.Dom { /// <summary> /// Represents a line of text. /// </summary> /// <remarks> /// To learn more about line-boxes see CSS spec: /// http://www.w3.org/TR/CSS21/visuren.html /// </remarks> internal sealed class CssLineBox { #region Fields and Consts private readonly List<CssRect> _words; private readonly CssBox _ownerBox; private readonly Dictionary<CssBox, RectangleF> _rects; private readonly List<CssBox> _relatedBoxes; #endregion /// <summary> /// Creates a new LineBox /// </summary> public CssLineBox(CssBox ownerBox) { _rects = new Dictionary<CssBox, RectangleF>(); _relatedBoxes = new List<CssBox>(); _words = new List<CssRect>(); _ownerBox = ownerBox; _ownerBox.LineBoxes.Add(this); } /// <summary> /// Gets a list of boxes related with the linebox. /// To know the words of the box inside this linebox, use the <see cref="WordsOf"/> method. /// </summary> public List<CssBox> RelatedBoxes { get { return _relatedBoxes; } } /// <summary> /// Gets the words inside the linebox /// </summary> public List<CssRect> Words { get { return _words; } } /// <summary> /// Gets the owner box /// </summary> public CssBox OwnerBox { get { return _ownerBox; } } /// <summary> /// Gets a List of rectangles that are to be painted on this linebox /// </summary> public Dictionary<CssBox, RectangleF> Rectangles { get { return _rects; } } /// <summary> /// Get the height of this box line (the max height of all the words) /// </summary> public float LineHeight { get { float height = 0; foreach (var rect in _rects) { height = Math.Max(height, rect.Value.Height); } return height; } } /// <summary> /// Get the bottom of this box line (the max bottom of all the words) /// </summary> public float LineBottom { get { float bottom = 0; foreach (var rect in _rects) { bottom = Math.Max(bottom, rect.Value.Bottom); } return bottom; } } /// <summary> /// Lets the linebox add the word an its box to their lists if necessary. /// </summary> /// <param name="word"></param> internal void ReportExistanceOf(CssRect word) { if (!Words.Contains(word)) { Words.Add(word); } if (!RelatedBoxes.Contains(word.OwnerBox)) { RelatedBoxes.Add(word.OwnerBox); } } /// <summary> /// Return the words of the specified box that live in this linebox /// </summary> /// <param name="box"></param> /// <returns></returns> internal List<CssRect> WordsOf(CssBox box) { List<CssRect> r = new List<CssRect>(); foreach (CssRect word in Words) if (word.OwnerBox.Equals(box)) r.Add(word); return r; } /// <summary> /// Updates the specified rectangle of the specified box. /// </summary> /// <param name="box"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="r"></param> /// <param name="b"></param> internal void UpdateRectangle(CssBox box, float x, float y, float r, float b) { float leftspacing = box.ActualBorderLeftWidth + box.ActualPaddingLeft; float rightspacing = box.ActualBorderRightWidth + box.ActualPaddingRight; float topspacing = box.ActualBorderTopWidth + box.ActualPaddingTop; float bottomspacing = box.ActualBorderBottomWidth + box.ActualPaddingTop; if ((box.FirstHostingLineBox != null && box.FirstHostingLineBox.Equals(this)) || box.IsImage) x -= leftspacing; if ((box.LastHostingLineBox != null && box.LastHostingLineBox.Equals(this)) || box.IsImage) r += rightspacing; if (!box.IsImage) { y -= topspacing; b += bottomspacing; } if (!Rectangles.ContainsKey(box)) { Rectangles.Add(box, RectangleF.FromLTRB(x, y, r, b)); } else { RectangleF f = Rectangles[box]; Rectangles[box] = RectangleF.FromLTRB( Math.Min(f.X, x), Math.Min(f.Y, y), Math.Max(f.Right, r), Math.Max(f.Bottom, b)); } if (box.ParentBox != null && box.ParentBox.IsInline) { UpdateRectangle(box.ParentBox, x, y, r, b); } } /// <summary> /// Copies the rectangles to their specified box /// </summary> internal void AssignRectanglesToBoxes() { foreach (CssBox b in Rectangles.Keys) { b.Rectangles.Add(this, Rectangles[b]); } } /// <summary> /// Draws the rectangles for debug purposes /// </summary> /// <param name="g"></param> internal void DrawRectangles(Graphics g) { foreach (CssBox b in Rectangles.Keys) { if (float.IsInfinity(Rectangles[b].Width)) continue; g.FillRectangle(new SolidBrush(Color.FromArgb(50, Color.Black)), Rectangle.Round(Rectangles[b])); g.DrawRectangle(Pens.Red, Rectangle.Round(Rectangles[b])); } } /// <summary> /// Gets the baseline Height of the rectangle /// </summary> /// <param name="b"> </param> /// <param name="g"></param> /// <returns></returns> public float GetBaseLineHeight(CssBox b, Graphics g) { Font f = b.ActualFont; FontFamily ff = f.FontFamily; FontStyle s = f.Style; return f.GetHeight(g) * ff.GetCellAscent(s) / ff.GetLineSpacing(s); } /// <summary> /// Sets the baseline of the words of the specified box to certain height /// </summary> /// <param name="g">Device info</param> /// <param name="b">box to check words</param> /// <param name="baseline">baseline</param> internal void SetBaseLine(IGraphics g, CssBox b, float baseline) { //TODO: Aqui me quede, checar poniendo "by the" con un font-size de 3em List<CssRect> ws = WordsOf(b); if (!Rectangles.ContainsKey(b)) return; RectangleF r = Rectangles[b]; //Save top of words related to the top of rectangle float gap = 0f; if (ws.Count > 0) { gap = ws[0].Top - r.Top; } else { CssRect firstw = b.FirstWordOccourence(b, this); if (firstw != null) { gap = firstw.Top - r.Top; } } //New top that words will have //float newtop = baseline - (Height - OwnerBox.FontDescent - 3); //OLD float newtop = baseline;// -GetBaseLineHeight(b, g); //OLD if (b.ParentBox != null && b.ParentBox.Rectangles.ContainsKey(this) && r.Height < b.ParentBox.Rectangles[this].Height) { //Do this only if rectangle is shorter than parent's float recttop = newtop - gap; RectangleF newr = new RectangleF(r.X, recttop, r.Width, r.Height); Rectangles[b] = newr; b.OffsetRectangle(this, gap); } foreach (var word in ws) { if (!word.IsImage) word.Top = newtop; } } /// <summary> /// Check if the given word is the last selected word in the line.<br/> /// It can either be the last word in the line or the next word has no selection. /// </summary> /// <param name="word">the word to check</param> /// <returns></returns> public bool IsLastSelectedWord(CssRect word) { for(int i = 0; i < _words.Count-1; i++) { if( _words[i] == word ) { return !_words[i + 1].Selected; } } return true; } /// <summary> /// Returns the words of the linebox /// </summary> /// <returns></returns> public override string ToString() { string[] ws = new string[Words.Count]; for (int i = 0; i < ws.Length; i++) { ws[i] = Words[i].Text; } return string.Join(" ", ws); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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; namespace Microsoft.DirectX { [Serializable] public struct Vector2 { public float X; public float Y; public static Vector2 Empty { get { return new Vector2 (0.0f, 0.0f); } } public override bool Equals (object compare) { throw new NotImplementedException (); } public static bool operator == (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public static bool operator != (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } public Vector2 (float valueX, float valueY) { X = valueX; Y = valueY; } public override string ToString () { throw new NotImplementedException (); } public static Vector2 operator - (Vector2 vec) { throw new NotImplementedException (); } public static Vector2 operator + (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public static Vector2 operator - (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public static Vector2 operator * (float right, Vector2 left) { throw new NotImplementedException (); } public static Vector2 operator * (Vector2 left, float right) { throw new NotImplementedException (); } public static Vector2 Multiply (Vector2 source, float s) { throw new NotImplementedException (); } public void Multiply (float s) { throw new NotImplementedException (); } public float Length () { throw new NotImplementedException (); } public static float Length (Vector2 source) { throw new NotImplementedException (); } public float LengthSq () { throw new NotImplementedException (); } public static float LengthSq (Vector2 source) { throw new NotImplementedException (); } public static float Dot (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public static float Ccw (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public void Add (Vector2 v) { throw new NotImplementedException (); } public static Vector2 Add (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public void Subtract (Vector2 source) { throw new NotImplementedException (); } public static Vector2 Subtract (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public void Minimize (Vector2 source) { throw new NotImplementedException (); } public static Vector2 Minimize (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public void Maximize (Vector2 source) { throw new NotImplementedException (); } public static Vector2 Maximize (Vector2 left, Vector2 right) { throw new NotImplementedException (); } public void Scale (float scalingFactor) { throw new NotImplementedException (); } public static Vector2 Scale (Vector2 source, float scalingFactor) { throw new NotImplementedException (); } public static Vector2 Lerp (Vector2 left, Vector2 right, float interpolater) { throw new NotImplementedException (); } public void Normalize () { throw new NotImplementedException (); } public static Vector2 Normalize (Vector2 source) { throw new NotImplementedException (); } public static Vector2 Hermite (Vector2 position, Vector2 tangent, Vector2 position2, Vector2 tangent2, float weightingFactor) { throw new NotImplementedException (); } public static Vector2 CatmullRom (Vector2 position1, Vector2 position2, Vector2 position3, Vector2 position4, float weightingFactor) { throw new NotImplementedException (); } public static Vector2 BaryCentric (Vector2 v1, Vector2 v2, Vector2 v3, float f, float g) { throw new NotImplementedException (); } public static Vector4[] Transform (Vector2[] vector, Matrix sourceMatrix) { throw new NotImplementedException (); } public static Vector4 Transform (Vector2 source, Matrix sourceMatrix) { throw new NotImplementedException (); } public void TransformCoordinate (Matrix sourceMatrix) { throw new NotImplementedException (); } public static Vector2[] TransformCoordinate (Vector2[] vector, Matrix sourceMatrix) { throw new NotImplementedException (); } public static Vector2 TransformCoordinate (Vector2 source, Matrix sourceMatrix) { throw new NotImplementedException (); } public void TransformNormal (Matrix sourceMatrix) { throw new NotImplementedException (); } public static Vector2[] TransformNormal (Vector2[] vector, Matrix sourceMatrix) { throw new NotImplementedException (); } public static Vector2 TransformNormal (Vector2 source, Matrix sourceMatrix) { throw new NotImplementedException (); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using proto = Google.Protobuf; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.TextToSpeech.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTextToSpeechClientTest { [xunit::FactAttribute] public void ListVoicesRequestObject() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoices(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse response = client.ListVoices(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListVoicesRequestObjectAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoicesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListVoicesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse responseCallSettings = await client.ListVoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ListVoicesResponse responseCancellationToken = await client.ListVoicesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ListVoices() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoices(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse response = client.ListVoices(request.LanguageCode); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListVoicesAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoicesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListVoicesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse responseCallSettings = await client.ListVoicesAsync(request.LanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ListVoicesResponse responseCancellationToken = await client.ListVoicesAsync(request.LanguageCode, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SynthesizeSpeechRequestObject() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), EnableTimePointing = { SynthesizeSpeechRequest.Types.TimepointType.Unspecified, }, }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeech(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse response = client.SynthesizeSpeech(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SynthesizeSpeechRequestObjectAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), EnableTimePointing = { SynthesizeSpeechRequest.Types.TimepointType.Unspecified, }, }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeechAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SynthesizeSpeechResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse responseCallSettings = await client.SynthesizeSpeechAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SynthesizeSpeechResponse responseCancellationToken = await client.SynthesizeSpeechAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SynthesizeSpeech() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeech(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse response = client.SynthesizeSpeech(request.Input, request.Voice, request.AudioConfig); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SynthesizeSpeechAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeechAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SynthesizeSpeechResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse responseCallSettings = await client.SynthesizeSpeechAsync(request.Input, request.Voice, request.AudioConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SynthesizeSpeechResponse responseCancellationToken = await client.SynthesizeSpeechAsync(request.Input, request.Voice, request.AudioConfig, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Used to initiate a recovery protection operation. /// </summary> [Cmdlet( VerbsData.Update, "AzureRmRecoveryServicesAsrProtectionDirection", DefaultParameterSetName = ASRParameterSets.ByRPIObject, SupportsShouldProcess = true)] [Alias("Update-ASRProtectionDirection")] [OutputType(typeof(ASRJob))] public class UpdateAzureRmRecoveryServicesAsrProtection : SiteRecoveryCmdletBase { /// <summary> /// Switch Paramter to Reprotect azure to vmware. /// </summary> [Parameter( Position = 0, ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] public SwitchParameter AzureToVMware { get; set; } /// <summary> /// Switch Paramter to create VMware to azure. /// </summary> [Parameter( Position = 0, ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] public SwitchParameter VMwareToAzure { get; set; } /// <summary> /// Switch Paramter to create HyperVToAzure policy. /// </summary> [Parameter( Position = 0, ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = true)] public SwitchParameter HyperVToAzure { get; set; } /// <summary> /// Switch Paramter to create HyperVSiteToHyperVSite policy. /// </summary> [Parameter( Position = 0, ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true)] public SwitchParameter VmmToVmm { get; set; } /// <summary> /// Gets or sets RunAsAccount. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware)] [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [ValidateNotNullOrEmpty] public ASRRunAsAccount Account { get; set; } /// <summary> /// Gets or sets DataStore. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [ValidateNotNullOrEmpty] public ASRDataStore DataStore { get; set; } /// <summary> /// Gets or sets Master Target Server. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware)] [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure)] [ValidateNotNullOrEmpty] public ASRMasterTargetServer MasterTarget { get; set; } /// <summary> /// Gets or sets Process Server. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [ValidateNotNullOrEmpty] public ASRProcessServer ProcessServer { get; set; } /// <summary> /// Gets or sets Policy. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [ValidateNotNullOrEmpty] public ASRProtectionContainerMapping ProtectionContainerMapping { get; set; } /// <summary> /// Gets or sets Recovery Azure Log Storage Account Id. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure)] [Parameter(ParameterSetName = ASRParameterSets.HyperVToAzure)] [ValidateNotNullOrEmpty] public string LogStorageAccountId { get; set; } /// <summary> /// Gets or sets Recovery Azure Storage Account Name of the Policy for V2A scenarios. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure)] [Parameter(ParameterSetName = ASRParameterSets.HyperVToAzure)] public string RecoveryAzureStorageAccountId { get; set; } /// <summary> /// Gets or sets Recovery Plan object. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRRecoveryPlan RecoveryPlan { get; set; } /// <summary> /// Gets or sets Replication Protected Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRReplicationProtectedItem ReplicationProtectedItem { get; set; } /// <summary> /// Gets or sets Failover direction for the recovery plan. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.ByPEObject, Mandatory = true)] [ValidateSet( Constants.PrimaryToRecovery, Constants.RecoveryToPrimary)] public string Direction { get; set; } /// <summary> /// Gets or sets Retention Volume. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [ValidateNotNullOrEmpty] public ASRRetentionVolume RetentionVolume { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( "Protected item or Recovery plan", "Update protection direction")) { switch (this.ParameterSetName) { case ASRParameterSets.ByRPIObject: case ASRParameterSets.AzureToVMware: case ASRParameterSets.VMwareToAzure: case ASRParameterSets.HyperVToAzure: case ASRParameterSets.EnterpriseToEnterprise: this.protectionContainerName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers); this.fabricName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics); this.SetRPIReprotect(); break; case ASRParameterSets.ByRPObject: this.SetRPReprotect(); break; case ASRParameterSets.ByPEObject: this.WriteWarning( Resources.UnsupportedReplicationReprotectScenerio); break; } } } /// <summary> /// RPI Reprotect. /// </summary> private void SetRPIReprotect() { var plannedFailoverInputProperties = new ReverseReplicationInputProperties { FailoverDirection = this.Direction, ProviderSpecificDetails = new ReverseReplicationProviderSpecificInput() }; var input = new ReverseReplicationInput { Properties = plannedFailoverInputProperties }; // fetch the latest Protectable item objects var replicationProtectedItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryReplicationProtectedItem( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name); validateRPISwitchParam(); var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( this.fabricName, this.protectionContainerName, Utilities.GetValueFromArmId( replicationProtectedItemResponse.Properties.ProtectableItemId, ARMResourceTypeConstants.ProtectableItems)); var asrProtectableItem = new ASRProtectableItem(protectableItemResponse); if (0 == string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var reprotectInput = new HyperVReplicaAzureReprotectInput { HvHostVmId = asrProtectableItem.FabricObjectId, VmName = asrProtectableItem.FriendlyName, OsType = string.Compare( asrProtectableItem.OS, "Windows") == 0 || string.Compare( asrProtectableItem.OS, "Linux") == 0 ? asrProtectableItem.OS : "Windows", VHDId = asrProtectableItem.OSDiskId }; var providerSpecificDetails = (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse .Properties.ProviderSpecificDetails; reprotectInput.StorageAccountId =this.RecoveryAzureStorageAccountId == null ? providerSpecificDetails.RecoveryAzureStorageAccount :this.RecoveryAzureStorageAccountId; reprotectInput.LogStorageAccountId = this.LogStorageAccountId == null ? providerSpecificDetails.RecoveryAzureLogStorageAccountId : this.LogStorageAccountId; input.Properties.ProviderSpecificDetails = reprotectInput; } } else if (string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) == 0) { // Validate the Direction as RecoveryToPrimary. if (this.Direction == Constants.RecoveryToPrimary) { // Set the InMage Provider specific input in the Reprotect Input. var reprotectInput = new InMageReprotectInput { ProcessServerId = this.ProcessServer.Id, MasterTargetId = this.MasterTarget != null ? this.MasterTarget.Id : this.ProcessServer .Id, // Assumption: PS and MT may or may not be same. RunAsAccountId = this.Account != null ? this.Account.AccountId : null, RetentionDrive = this.RetentionVolume.VolumeName, DatastoreName = this.DataStore.SymbolicName, ProfileId = this.ProtectionContainerMapping.PolicyId, DiskExclusionInput = new InMageDiskExclusionInput { VolumeOptions = new List<InMageVolumeExclusionOptions>(), DiskSignatureOptions = null }, DisksToInclude = null }; // excluding the azure temporary storage. reprotectInput.DiskExclusionInput.VolumeOptions.Add( new InMageVolumeExclusionOptions { VolumeLabel = Constants.TemporaryStorage, OnlyExcludeIfSingleVolume = Constants.Yes }); input.Properties.ProviderSpecificDetails = reprotectInput; } else { // PrimaryToRecovery Direction is Invalid for InMageAzureV2. new ArgumentException(Resources.InvalidDirectionForAzureToVMWare); } } else if (string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.InMage, StringComparison.OrdinalIgnoreCase) == 0) { // Validate the Direction as RecoveryToPrimary. if (this.Direction == Constants.RecoveryToPrimary) { // Set the InMageAzureV2 Provider specific input in the Reprotect Input. var reprotectInput = new InMageAzureV2ReprotectInput { ProcessServerId = this.ProcessServer.Id, MasterTargetId = this.MasterTarget != null ? this.MasterTarget.Id : this.ProcessServer .Id, // Assumption: PS and MT are same. RunAsAccountId = this.Account.AccountId, PolicyId = this.ProtectionContainerMapping.PolicyId, StorageAccountId = this.RecoveryAzureStorageAccountId, LogStorageAccountId = this.LogStorageAccountId, DisksToInclude = null }; input.Properties.ProviderSpecificDetails = reprotectInput; } else { // PrimaryToRecovery Direction is Invalid for InMage. new ArgumentException(Resources.InvalidDirectionForVMWareToAzure); } } var response = this.RecoveryServicesClient.StartAzureSiteRecoveryReprotection( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name, input); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } /// <summary> /// Starts RP Reprotect. /// </summary> private void SetRPReprotect() { // Check if the Recovery Plan contains any InMageAzureV2 and InMage Replication Provider Entities. var rp = this.RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan( this.RecoveryPlan .Name); foreach (var replicationProvider in rp.Properties.ReplicationProviders) { if (string.Compare( replicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare( replicationProvider, Constants.InMage, StringComparison.OrdinalIgnoreCase) == 0) { throw new InvalidOperationException( string.Format( Resources.UnsupportedReplicationProviderForReprotect, replicationProvider)); } } var response = this.RecoveryServicesClient.UpdateAzureSiteRecoveryProtection( this.RecoveryPlan.Name); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } private void validateRPISwitchParam() { if ((this.AzureToVMware.IsPresent && !this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.InMageAzureV2)) || (this.VMwareToAzure.IsPresent && !this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.InMage)) || (this.HyperVToAzure.IsPresent && !this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.HyperVReplicaAzure)) || (this.VmmToVmm.IsPresent && !(this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.HyperVReplica2012) || this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.HyperVReplica2012R2)))) { throw new PSInvalidOperationException(Resources.InvalidParameterSet); } } private void validateRPSwitchParam(RecoveryPlan rp, string replicationProvider) { if ((this.HyperVToAzure.IsPresent && !replicationProvider.Equals(Constants.HyperVReplicaAzure)) || (this.VmmToVmm.IsPresent && !(this.ReplicationProtectedItem.ReplicationProvider.Equals(Constants.HyperVReplica2012) || replicationProvider.Equals(Constants.HyperVReplica2012R2)))) { throw new PSInvalidOperationException(Resources.InvalidParameterSet); } } #region local parameters /// <summary> /// Gets or sets Name of the Fabric. /// </summary> private string fabricName; /// <summary> /// Gets or sets Name of the Protection Container. /// </summary> private string protectionContainerName; #endregion } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Composing; using Umbraco.Cms.Core.Dashboards; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Manifest; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.PropertyEditors.Validators; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Serialization; using Umbraco.Cms.Tests.UnitTests.TestHelpers; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Manifest { [TestFixture] public class ManifestParserTests { private ManifestParser _parser; private IIOHelper _ioHelper; [SetUp] public void Setup() { var validators = new IManifestValueValidator[] { new RequiredValidator(Mock.Of<ILocalizedTextService>()), new RegexValidator(Mock.Of<ILocalizedTextService>(), null), new DelimitedValueValidator(), }; _ioHelper = TestHelper.IOHelper; NullLoggerFactory loggerFactory = NullLoggerFactory.Instance; _parser = new ManifestParser( AppCaches.Disabled, new ManifestValueValidatorCollection(() => validators), new ManifestFilterCollection(() => Enumerable.Empty<IManifestFilter>()), loggerFactory.CreateLogger<ManifestParser>(), _ioHelper, TestHelper.GetHostingEnvironment(), new JsonNetSerializer(), Mock.Of<ILocalizedTextService>(), Mock.Of<IShortStringHelper>(), Mock.Of<IDataValueEditorFactory>()); } [Test] public void DelimitedValueValidator() { const string json = @"{'propertyEditors': [ { alias: 'Test.Test2', name: 'Test 2', isParameterEditor: true, defaultConfig: { key1: 'some default val' }, editor: { view: '~/App_Plugins/MyPackage/PropertyEditors/MyEditor.html', valueType: 'int', validation: { delimited: { delimiter: ',', pattern: '^[a-zA-Z]*$' } } } } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(1, manifest.ParameterEditors.Length); Assert.AreEqual(1, manifest.ParameterEditors[0].GetValueEditor().Validators.Count); Assert.IsTrue(manifest.ParameterEditors[0].GetValueEditor().Validators[0] is DelimitedValueValidator); var validator = manifest.ParameterEditors[0].GetValueEditor().Validators[0] as DelimitedValueValidator; Assert.IsNotNull(validator.Configuration); Assert.AreEqual(",", validator.Configuration.Delimiter); Assert.AreEqual("^[a-zA-Z]*$", validator.Configuration.Pattern); } [Test] public void CanParseComments() { const string json1 = @" // this is a single-line comment { ""x"": 2, // this is an end-of-line comment ""y"": 3, /* this is a single line comment block /* comment */ ""z"": /* comment */ 4, ""t"": ""this is /* comment */ a string"", ""u"": ""this is // more comment in a string"" } "; var jobject = (JObject)JsonConvert.DeserializeObject(json1); Assert.AreEqual("2", jobject.Property("x").Value.ToString()); Assert.AreEqual("3", jobject.Property("y").Value.ToString()); Assert.AreEqual("4", jobject.Property("z").Value.ToString()); Assert.AreEqual("this is /* comment */ a string", jobject.Property("t").Value.ToString()); Assert.AreEqual("this is // more comment in a string", jobject.Property("u").Value.ToString()); } [Test] public void ThrowOnJsonError() { // invalid json, missing the final ']' on javascript const string json = @"{ propertyEditors: []/*we have empty property editors**/, javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2.js' }"; // parsing fails Assert.Throws<JsonReaderException>(() => _parser.ParseManifest(json)); } [Test] public void CanParseManifest_ScriptsAndStylesheets() { string json = "{}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(0, manifest.Scripts.Length); json = "{javascript: []}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(0, manifest.Scripts.Length); json = "{javascript: ['~/test.js', '~/test2.js']}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Scripts.Length); json = "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js']}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Scripts.Length); Assert.AreEqual(_ioHelper.ResolveUrl("/test.js"), manifest.Scripts[0]); Assert.AreEqual(_ioHelper.ResolveUrl("/test2.js"), manifest.Scripts[1]); // kludge is gone - must filter before parsing json = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()) + "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js']}"; Assert.Throws<JsonReaderException>(() => _parser.ParseManifest(json)); json = "{}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(0, manifest.Stylesheets.Length); json = "{css: []}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(0, manifest.Stylesheets.Length); json = "{css: ['~/style.css', '~/folder-name/sdsdsd/stylesheet.css']}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Stylesheets.Length); json = "{propertyEditors: [], css: ['~/stylesheet.css', '~/random-long-name.css']}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Stylesheets.Length); json = "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js'], css: ['~/stylesheet.css', '~/random-long-name.css']}"; manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Scripts.Length); Assert.AreEqual(2, manifest.Stylesheets.Length); } [Test] public void CanParseManifest_PropertyEditors() { const string json = @"{'propertyEditors': [ { alias: 'Test.Test1', name: 'Test 1', editor: { view: '~/App_Plugins/MyPackage/PropertyEditors/MyEditor.html', valueType: 'int', hideLabel: true, validation: { 'required': true, 'Regex': '\\d*' } }, prevalues: { fields: [ { label: 'Some config 1', key: 'key1', view: '~/App_Plugins/MyPackage/PropertyEditors/Views/pre-val1.html', validation: { required: true } }, { label: 'Some config 2', key: 'key2', view: '~/App_Plugins/MyPackage/PropertyEditors/Views/pre-val2.html' } ] } }, { alias: 'Test.Test2', name: 'Test 2', isParameterEditor: true, defaultConfig: { key1: 'some default val' }, editor: { view: '~/App_Plugins/MyPackage/PropertyEditors/MyEditor.html', valueType: 'int', validation: { required : true, regex : '\\d*' } } } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.PropertyEditors.Length); IDataEditor editor = manifest.PropertyEditors[1]; Assert.IsTrue((editor.Type & EditorType.MacroParameter) > 0); Assert.IsNotEmpty(editor.DefaultConfiguration); Assert.AreEqual("some default val", editor.DefaultConfiguration["key1"]); editor = manifest.PropertyEditors[0]; Assert.AreEqual("Test.Test1", editor.Alias); Assert.AreEqual("Test 1", editor.Name); Assert.IsFalse((editor.Type & EditorType.MacroParameter) > 0); IDataValueEditor valueEditor = editor.GetValueEditor(); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/MyEditor.html"), valueEditor.View); Assert.AreEqual("int", valueEditor.ValueType); Assert.IsTrue(valueEditor.HideLabel); // these two don't make much sense here //// valueEditor.RegexValidator; //// valueEditor.RequiredValidator; List<IValueValidator> validators = valueEditor.Validators; Assert.AreEqual(2, validators.Count); IValueValidator validator = validators[0]; var v1 = validator as RequiredValidator; Assert.IsNotNull(v1); Assert.AreEqual("Required", v1.ValidationName); validator = validators[1]; var v2 = validator as RegexValidator; Assert.IsNotNull(v2); Assert.AreEqual("Regex", v2.ValidationName); Assert.AreEqual("\\d*", v2.Configuration); // this is not part of the manifest IDictionary<string, object> preValues = editor.GetConfigurationEditor().DefaultConfiguration; Assert.IsEmpty(preValues); IConfigurationEditor preValueEditor = editor.GetConfigurationEditor(); Assert.IsNotNull(preValueEditor); Assert.IsNotNull(preValueEditor.Fields); Assert.AreEqual(2, preValueEditor.Fields.Count); ConfigurationField f = preValueEditor.Fields[0]; Assert.AreEqual("key1", f.Key); Assert.AreEqual("Some config 1", f.Name); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/Views/pre-val1.html"), f.View); List<IValueValidator> fvalidators = f.Validators; Assert.IsNotNull(fvalidators); Assert.AreEqual(1, fvalidators.Count); var fv = fvalidators[0] as RequiredValidator; Assert.IsNotNull(fv); Assert.AreEqual("Required", fv.ValidationName); f = preValueEditor.Fields[1]; Assert.AreEqual("key2", f.Key); Assert.AreEqual("Some config 2", f.Name); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/Views/pre-val2.html"), f.View); fvalidators = f.Validators; Assert.IsNotNull(fvalidators); Assert.AreEqual(0, fvalidators.Count); } [Test] public void CanParseManifest_ParameterEditors() { const string json = @"{'parameterEditors': [ { alias: 'parameter1', name: 'My Parameter', view: '~/App_Plugins/MyPackage/PropertyEditors/MyEditor.html' }, { alias: 'parameter2', name: 'Another parameter', config: { key1: 'some config val' }, view: '~/App_Plugins/MyPackage/PropertyEditors/CsvEditor.html' }, { alias: 'parameter3', name: 'Yet another parameter' } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(3, manifest.ParameterEditors.Length); Assert.IsTrue(manifest.ParameterEditors.All(x => (x.Type & EditorType.MacroParameter) > 0)); IDataEditor editor = manifest.ParameterEditors[1]; Assert.AreEqual("parameter2", editor.Alias); Assert.AreEqual("Another parameter", editor.Name); IDictionary<string, object> config = editor.DefaultConfiguration; Assert.AreEqual(1, config.Count); Assert.IsTrue(config.ContainsKey("key1")); Assert.AreEqual("some config val", config["key1"]); IDataValueEditor valueEditor = editor.GetValueEditor(); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/PropertyEditors/CsvEditor.html"), valueEditor.View); editor = manifest.ParameterEditors[2]; Assert.Throws<InvalidOperationException>(() => { IDataValueEditor valueEditor = editor.GetValueEditor(); }); } [Test] public void CanParseManifest_GridEditors() { const string json = @"{ 'javascript': [ ], 'css': [ ], 'gridEditors': [ { 'name': 'Small Hero', 'alias': 'small-hero', 'view': '~/App_Plugins/MyPlugin/small-hero/editortemplate.html', 'render': '~/Views/Partials/Grid/Editors/SmallHero.cshtml', 'icon': 'icon-presentation', 'config': { 'image': { 'size': { 'width': 1200, 'height': 185 } }, 'link': { 'maxNumberOfItems': 1, 'minNumberOfItems': 0 } } }, { 'name': 'Document Links By Category', 'alias': 'document-links-by-category', 'view': '~/App_Plugins/MyPlugin/document-links-by-category/editortemplate.html', 'render': '~/Views/Partials/Grid/Editors/DocumentLinksByCategory.cshtml', 'icon': 'icon-umb-members' } ] }"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.GridEditors.Length); GridEditor editor = manifest.GridEditors[0]; Assert.AreEqual("small-hero", editor.Alias); Assert.AreEqual("Small Hero", editor.Name); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPlugin/small-hero/editortemplate.html"), editor.View); Assert.AreEqual(_ioHelper.ResolveUrl("/Views/Partials/Grid/Editors/SmallHero.cshtml"), editor.Render); Assert.AreEqual("icon-presentation", editor.Icon); IDictionary<string, object> config = editor.Config; Assert.AreEqual(2, config.Count); Assert.IsTrue(config.ContainsKey("image")); object c = config["image"]; Assert.IsInstanceOf<JObject>(c); // FIXME: is this what we want? Assert.IsTrue(config.ContainsKey("link")); c = config["link"]; Assert.IsInstanceOf<JObject>(c); // FIXME: is this what we want? // FIXME: should we resolveUrl in configs? } [Test] public void CanParseManifest_ContentApps() { const string json = @"{'contentApps': [ { alias: 'myPackageApp1', name: 'My App1', icon: 'icon-foo', view: '~/App_Plugins/MyPackage/ContentApps/MyApp1.html' }, { alias: 'myPackageApp2', name: 'My App2', config: { key1: 'some config val' }, icon: 'icon-bar', view: '~/App_Plugins/MyPackage/ContentApps/MyApp2.html' } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.ContentApps.Length); Assert.IsInstanceOf<ManifestContentAppDefinition>(manifest.ContentApps[0]); var app0 = (ManifestContentAppDefinition)manifest.ContentApps[0]; Assert.AreEqual("myPackageApp1", app0.Alias); Assert.AreEqual("My App1", app0.Name); Assert.AreEqual("icon-foo", app0.Icon); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/ContentApps/MyApp1.html"), app0.View); Assert.IsInstanceOf<ManifestContentAppDefinition>(manifest.ContentApps[1]); var app1 = (ManifestContentAppDefinition)manifest.ContentApps[1]; Assert.AreEqual("myPackageApp2", app1.Alias); Assert.AreEqual("My App2", app1.Name); Assert.AreEqual("icon-bar", app1.Icon); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/ContentApps/MyApp2.html"), app1.View); } [Test] public void CanParseManifest_Dashboards() { const string json = @"{'dashboards': [ { 'alias': 'something', 'view': '~/App_Plugins/MyPackage/Dashboards/one.html', 'sections': [ 'content' ], 'access': [ {'grant':'user'}, {'deny':'foo'} ] }, { 'alias': 'something.else', 'weight': -1, 'view': '~/App_Plugins/MyPackage/Dashboards/two.html', 'sections': [ 'forms' ], } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Dashboards.Length); Assert.IsInstanceOf<ManifestDashboard>(manifest.Dashboards[0]); ManifestDashboard db0 = manifest.Dashboards[0]; Assert.AreEqual("something", db0.Alias); Assert.AreEqual(100, db0.Weight); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/Dashboards/one.html"), db0.View); Assert.AreEqual(1, db0.Sections.Length); Assert.AreEqual("content", db0.Sections[0]); Assert.AreEqual(2, db0.AccessRules.Length); Assert.AreEqual(AccessRuleType.Grant, db0.AccessRules[0].Type); Assert.AreEqual("user", db0.AccessRules[0].Value); Assert.AreEqual(AccessRuleType.Deny, db0.AccessRules[1].Type); Assert.AreEqual("foo", db0.AccessRules[1].Value); Assert.IsInstanceOf<ManifestDashboard>(manifest.Dashboards[1]); ManifestDashboard db1 = manifest.Dashboards[1]; Assert.AreEqual("something.else", db1.Alias); Assert.AreEqual(-1, db1.Weight); Assert.AreEqual(_ioHelper.ResolveUrl("/App_Plugins/MyPackage/Dashboards/two.html"), db1.View); Assert.AreEqual(1, db1.Sections.Length); Assert.AreEqual("forms", db1.Sections[0]); } [Test] public void CanParseManifest_Sections() { const string json = @"{'sections': [ { ""alias"": ""content"", ""name"": ""Content"" }, { ""alias"": ""hello"", ""name"": ""World"" } ]}"; PackageManifest manifest = _parser.ParseManifest(json); Assert.AreEqual(2, manifest.Sections.Length); Assert.AreEqual("content", manifest.Sections[0].Alias); Assert.AreEqual("hello", manifest.Sections[1].Alias); Assert.AreEqual("Content", manifest.Sections[0].Name); Assert.AreEqual("World", manifest.Sections[1].Name); } } }
// // ChangeTrackerTest.cs // // Author: // Pasin Suriyentrakorn <[email protected]> // // Copyright (c) 2014 Couchbase Inc // Copyright (c) 2014 .NET 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. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; using Sharpen; using System.Net.Http; using System.Threading.Tasks; using NUnit.Framework; using Couchbase.Lite.Tests; using System.Collections; using System.Threading; using Couchbase.Lite.Auth; #if NET_3_5 using System.Net.Couchbase; #else using System.Net; #endif namespace Couchbase.Lite { public class ChangeTrackerTest : LiteTestCase { public const string Tag = "ChangeTracker"; private class ChangeTrackerTestClient : IChangeTrackerClient { #region IChangeTrackerClient implementation public delegate void ChangeTrackerStoppedDelegate(ChangeTracker tracker); public delegate void ChangeTrackerReceivedChangeDelegate(IDictionary<string, object> change); public MockHttpClientFactory HttpClientFactory { get; set; } public MockHttpRequestHandler HttpRequestHandler { get { return HttpClientFactory.HttpHandler; } } public MessageProcessingHandler Handler { get { return HttpClientFactory.Handler; } } public ChangeTrackerStoppedDelegate StoppedDelegate { get; set; } public ChangeTrackerReceivedChangeDelegate ReceivedChangeDelegate { get; set; } private CountDownLatch stoppedSignal; private CountDownLatch changedSignal; public ChangeTrackerTestClient(CountDownLatch stoppedSignal, CountDownLatch changedSignal) { this.stoppedSignal = stoppedSignal; this.changedSignal = changedSignal; HttpClientFactory = new MockHttpClientFactory(); } public void ChangeTrackerStopped(ChangeTracker tracker) { if (StoppedDelegate != null) { StoppedDelegate(tracker); } if (stoppedSignal != null) { stoppedSignal.CountDown(); } } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { if (ReceivedChangeDelegate != null) { ReceivedChangeDelegate(change); } if (changedSignal != null) { changedSignal.CountDown(); } } public void AddCookies(CookieCollection cookies) { HttpClientFactory.AddCookies(cookies); } public void DeleteCookie(Uri domain, string name) { HttpClientFactory.DeleteCookie(domain, name); } public CookieContainer GetCookieContainer() { return HttpClientFactory.GetCookieContainer(); } #endregion #region IHttpClientFactory implementation public HttpClient GetHttpClient(bool longPoll) { return HttpClientFactory.GetHttpClient(longPoll); } public IDictionary<string, string> Headers { get { return HttpClientFactory.Headers; } set { HttpClientFactory.Headers = value; } } #endregion } private Boolean IsSyncGateway(Uri remote) { return (remote.Port == 4984 || remote.Port == 4985); } private void ChangeTrackerTestWithMode(ChangeTrackerMode mode) { var changeTrackerFinishedSignal = new CountDownLatch(1); var changeReceivedSignal = new CountDownLatch(1); var client = new ChangeTrackerTestClient(changeTrackerFinishedSignal, changeReceivedSignal); client.ReceivedChangeDelegate = (IDictionary<string, object> change) => { Assert.IsTrue(change.ContainsKey("seq")); Assert.AreEqual("1", change["seq"]); }; var handler = client.HttpRequestHandler; handler.SetResponder("_changes", (request) => { var json = "{\"results\":[\n" + "{\"seq\":\"1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return MockHttpRequestHandler.GenerateHttpResponseMessage(System.Net.HttpStatusCode.OK, null, json); }); var testUrl = GetReplicationURL(); var scheduler = new SingleTaskThreadpoolScheduler(); var changeTracker = new ChangeTracker(testUrl, mode, 0, false, client, new TaskFactory(scheduler)); changeTracker.UsePost = IsSyncGateway(testUrl); changeTracker.Start(); var success = changeReceivedSignal.Await(TimeSpan.FromSeconds(30)); Assert.IsTrue(success); changeTracker.Stop(); success = changeTrackerFinishedSignal.Await(TimeSpan.FromSeconds(30)); Assert.IsTrue(success); } private void TestChangeTrackerBackoff(MockHttpClientFactory httpClientFactory) { var changeTrackerFinishedSignal = new CountDownLatch(1); var client = new ChangeTrackerTestClient(changeTrackerFinishedSignal, null); client.HttpClientFactory = httpClientFactory; var testUrl = GetReplicationURL(); var scheduler = new SingleTaskThreadpoolScheduler(); var changeTracker = new ChangeTracker(testUrl, ChangeTrackerMode.LongPoll, 0, false, client, new TaskFactory(scheduler)); changeTracker.UsePost = IsSyncGateway(testUrl); changeTracker.Start(); // sleep for a few seconds Thread.Sleep(10 * 1000); // make sure we got less than 10 requests in those 10 seconds (if it was hammering, we'd get a lot more) var handler = client.HttpRequestHandler; Assert.IsTrue(handler.CapturedRequests.Count < 25); Assert.IsTrue(changeTracker.backoff.NumAttempts > 0, "Observed attempts: {0}".Fmt(changeTracker.backoff.NumAttempts)); handler.ClearResponders(); handler.AddResponderReturnEmptyChangesFeed(); // at this point, the change tracker backoff should cause it to sleep for about 3 seconds // and so lets wait 3 seconds until it wakes up and starts getting valid responses Thread.Sleep(3 * 1000); // now find the delta in requests received in a 2s period int before = handler.CapturedRequests.Count; Thread.Sleep(2 * 1000); int after = handler.CapturedRequests.Count; // assert that the delta is high, because at this point the change tracker should // be hammering away Assert.IsTrue((after - before) > 25, "{0} <= 25", (after - before)); // the backoff numAttempts should have been reset to 0 Assert.IsTrue(changeTracker.backoff.NumAttempts == 0); changeTracker.Stop(); var success = changeTrackerFinishedSignal.Await(TimeSpan.FromSeconds(30)); Assert.IsTrue(success); } private MockHttpRequestHandler.HttpResponseDelegate RunChangeTrackerTransientErrorDefaultResponder() { MockHttpRequestHandler.HttpResponseDelegate responder = (request) => { var json = "{\"results\":[\n" + "{\"seq\":\"1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return MockHttpRequestHandler.GenerateHttpResponseMessage(System.Net.HttpStatusCode.OK, null, json); }; return responder; } private void RunChangeTrackerTransientError( ChangeTrackerMode mode, Int32 errorCode, string statusMessage, Int32 numExpectedChangeCallbacks) { var changeTrackerFinishedSignal = new CountDownLatch(1); var changeReceivedSignal = new CountDownLatch(numExpectedChangeCallbacks); var client = new ChangeTrackerTestClient(changeTrackerFinishedSignal, changeReceivedSignal); MockHttpRequestHandler.HttpResponseDelegate sentinal = RunChangeTrackerTransientErrorDefaultResponder(); var responders = new List<MockHttpRequestHandler.HttpResponseDelegate>(); responders.Add(RunChangeTrackerTransientErrorDefaultResponder()); responders.Add(MockHttpRequestHandler.TransientErrorResponder(errorCode, statusMessage)); MockHttpRequestHandler.HttpResponseDelegate chainResponder = (request) => { if (responders.Count > 0) { var responder = responders[0]; responders.RemoveAt(0); return responder(request); } return sentinal(request); }; var handler = client.HttpRequestHandler; handler.SetResponder("_changes", chainResponder); var testUrl = GetReplicationURL(); var scheduler = new SingleTaskThreadpoolScheduler(); var changeTracker = new ChangeTracker(testUrl, mode, 0, false, client, new TaskFactory(scheduler)); changeTracker.UsePost = IsSyncGateway(testUrl); changeTracker.Start(); var success = changeReceivedSignal.Await(TimeSpan.FromSeconds(30)); Assert.IsTrue(success); changeTracker.Stop(); success = changeTrackerFinishedSignal.Await(TimeSpan.FromSeconds(30)); Assert.IsTrue(success); } [Test] public void TestChangeTrackerOneShot() { ChangeTrackerTestWithMode(ChangeTrackerMode.OneShot); } [Test] public void TestChangeTrackerLongPoll() { ChangeTrackerTestWithMode(ChangeTrackerMode.LongPoll); } [Test] public void TestChangeTrackerWithConflictsIncluded() { Uri testUrl = GetReplicationURL(); var changeTracker = new ChangeTracker(testUrl, ChangeTrackerMode.LongPoll, 0, true, null); Assert.AreEqual("_changes?feed=longpoll&limit=500&heartbeat=300000&style=all_docs&since=0", changeTracker.GetChangesFeedPath()); } [Test] public void TestChangeTrackerWithFilterURL() { var testUrl = GetReplicationURL(); var changeTracker = new ChangeTracker(testUrl, ChangeTrackerMode.LongPoll, 0, false, null); // set filter changeTracker.SetFilterName("filter"); // build filter map var filterMap = new Dictionary<string, object>(); filterMap["param"] = "value"; // set filter map changeTracker.SetFilterParams(filterMap); Assert.AreEqual("_changes?feed=longpoll&limit=500&heartbeat=300000&since=0&filter=filter&param=value", changeTracker.GetChangesFeedPath()); } [Test] public void TestChangeTrackerBackoffExceptions() { var factory = new MockHttpClientFactory(); var httpHandler = (MockHttpRequestHandler)factory.HttpHandler; httpHandler.AddResponderThrowExceptionAllRequests(); TestChangeTrackerBackoff(factory); } [Test] public void TestChangeTrackerBackoffInvalidJson() { var factory = new MockHttpClientFactory(); var httpHandler = (MockHttpRequestHandler)factory.HttpHandler; httpHandler.AddResponderReturnInvalidChangesFeedJson(); TestChangeTrackerBackoff(factory); } [Test] public void TestChangeTrackerRecoverableError() { var errorCode = System.Net.HttpStatusCode.ServiceUnavailable; var statusMessage = "Transient Error"; var numExpectedChangeCallbacks = 2; RunChangeTrackerTransientError(ChangeTrackerMode.LongPoll, (Int32)errorCode, statusMessage, numExpectedChangeCallbacks); } [Test] public void TestChangeTrackerRecoverableIOException() { var errorCode = -1; var statusMessage = (string)null; var numExpectedChangeCallbacks = 2; RunChangeTrackerTransientError(ChangeTrackerMode.LongPoll, (Int32)errorCode, statusMessage, numExpectedChangeCallbacks); } [Test] public void TestChangeTrackerNonRecoverableError() { var errorCode = System.Net.HttpStatusCode.NotFound; var statusMessage = "Not Found"; var numExpectedChangeCallbacks = 1; RunChangeTrackerTransientError(ChangeTrackerMode.LongPoll, (Int32)errorCode, statusMessage, numExpectedChangeCallbacks); } [Test] public void TestChangeTrackerWithDocsIds() { var testURL = GetReplicationURL(); var changeTracker = new ChangeTracker(testURL, ChangeTrackerMode .LongPoll, 0, false, null); var docIds = new List<string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTracker.SetDocIDs(docIds); var docIdsJson = "[\"doc1\",\"doc2\"]"; var docIdsEncoded = Uri.EscapeUriString(docIdsJson); var expectedFeedPath = string.Format("_changes?feed=longpoll&limit=500&heartbeat=300000&since=0&filter=_doc_ids&doc_ids={0}", docIdsEncoded); string changesFeedPath = changeTracker.GetChangesFeedPath(); Assert.AreEqual(expectedFeedPath, changesFeedPath); changeTracker.UsePost = true; var parameters = changeTracker.GetChangesFeedParams(); Assert.AreEqual("_doc_ids", parameters["filter"]); AssertEnumerablesAreEqual(docIds, (IEnumerable)parameters["doc_ids"]); var body = changeTracker.GetChangesFeedPostBody(); Assert.IsTrue(body.Contains(docIdsJson)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text.RegularExpressions; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; /// <summary> /// Managed environment. Acts as a gateway for native code. /// </summary> internal static class ExceptionUtils { /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */ private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError"; /** NoSuchMethodError fully-qualified class name which is important during startup phase. */ private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError"; /** InteropCachePartialUpdateException. */ private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException"; /** Map with predefined exceptions. */ private static readonly IDictionary<string, ExceptionFactory> Exs = new Dictionary<string, ExceptionFactory>(); /** Inner class regex. */ private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled); /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability")] static ExceptionUtils() { // Common Java exceptions mapped to common .NET exceptions. Exs["java.lang.IllegalArgumentException"] = (c, m, e, i) => new ArgumentException(m, e); Exs["java.lang.IllegalStateException"] = (c, m, e, i) => new InvalidOperationException(m, e); Exs["java.lang.UnsupportedOperationException"] = (c, m, e, i) => new NotSupportedException(m, e); Exs["java.lang.InterruptedException"] = (c, m, e, i) => new ThreadInterruptedException(m, e); // Generic Ignite exceptions. Exs["org.apache.ignite.IgniteException"] = (c, m, e, i) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteCheckedException"] = (c, m, e, i) => new IgniteException(m, e); Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask); Exs["org.apache.ignite.binary.BinaryObjectException"] = (c, m, e, i) => new BinaryObjectException(m, e); // Cluster exceptions. Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e); Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (c, m, e, i) => new ClusterTopologyException(m, e); // Compute exceptions. Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (c, m, e, i) => new ComputeExecutionRejectedException(m, e); Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (c, m, e, i) => new ComputeJobFailoverException(m, e); Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (c, m, e, i) => new ComputeTaskCancelledException(m, e); Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (c, m, e, i) => new ComputeTaskTimeoutException(m, e); Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (c, m, e, i) => new ComputeUserUndeclaredException(m, e); // Cache exceptions. Exs["javax.cache.CacheException"] = (c, m, e, i) => new CacheException(m, e); Exs["javax.cache.integration.CacheLoaderException"] = (c, m, e, i) => new CacheStoreException(m, e); Exs["javax.cache.integration.CacheWriterException"] = (c, m, e, i) => new CacheStoreException(m, e); Exs["javax.cache.processor.EntryProcessorException"] = (c, m, e, i) => new CacheEntryProcessorException(m, e); // Transaction exceptions. Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (c, m, e, i) => new TransactionOptimisticException(m, e); Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (c, m, e, i) => new TransactionTimeoutException(m, e); Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (c, m, e, i) => new TransactionRollbackException(m, e); Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (c, m, e, i) => new TransactionHeuristicException(m, e); Exs["org.apache.ignite.transactions.TransactionDeadlockException"] = (c, m, e, i) => new TransactionDeadlockException(m, e); // Security exceptions. Exs["org.apache.ignite.IgniteAuthenticationException"] = (c, m, e, i) => new SecurityException(m, e); Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (c, m, e, i) => new SecurityException(m, e); // Future exceptions. Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e); Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e); // Service exceptions. Exs["org.apache.ignite.services.ServiceDeploymentException"] = (c, m, e, i) => new ServiceDeploymentException(m, e); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="igniteInt">The ignite.</param> /// <param name="clsName">Exception class name.</param> /// <param name="msg">Exception message.</param> /// <param name="stackTrace">Native stack trace.</param> /// <param name="reader">Error data reader.</param> /// <param name="innerException">Inner exception.</param> /// <returns>Exception.</returns> public static Exception GetException(IIgniteInternal igniteInt, string clsName, string msg, string stackTrace, BinaryReader reader = null, Exception innerException = null) { // Set JavaException as immediate inner. var jex = new JavaException(clsName, msg, stackTrace, innerException); return GetException(igniteInt, jex, reader); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="igniteInt">The ignite.</param> /// <param name="innerException">Java exception.</param> /// <param name="reader">Error data reader.</param> /// <returns>Exception.</returns> public static Exception GetException(IIgniteInternal igniteInt, JavaException innerException, BinaryReader reader = null) { var ignite = igniteInt == null ? null : igniteInt.GetIgnite(); var msg = innerException.JavaMessage; var clsName = innerException.JavaClassName; ExceptionFactory ctor; if (Exs.TryGetValue(clsName, out ctor)) { var match = InnerClassRegex.Match(msg ?? string.Empty); ExceptionFactory innerCtor; if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor)) { return ctor(clsName, msg, innerCtor(match.Groups[1].Value, match.Groups[2].Value, innerException, ignite), ignite); } return ctor(clsName, msg, innerException, ignite); } if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " + "variable?): " + msg, innerException); if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase)) return ProcessCachePartialUpdateException(igniteInt, msg, innerException.Message, reader); // Predefined mapping not found - check plugins. if (igniteInt != null && igniteInt.PluginProcessor != null) { ctor = igniteInt.PluginProcessor.GetExceptionMapping(clsName); if (ctor != null) { return ctor(clsName, msg, innerException, ignite); } } // Return default exception. return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg), innerException); } /// <summary> /// Process cache partial update exception. /// </summary> /// <param name="ignite">The ignite.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <param name="reader">Reader.</param> /// <returns>CachePartialUpdateException.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static Exception ProcessCachePartialUpdateException(IIgniteInternal ignite, string msg, string stackTrace, BinaryReader reader) { if (reader == null) return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available.")); bool dataExists = reader.ReadBoolean(); Debug.Assert(dataExists); if (reader.ReadBoolean()) { bool keepBinary = reader.ReadBoolean(); BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary); try { return new CachePartialUpdateException(msg, ReadNullableList(keysReader)); } catch (Exception e) { // Failed to deserialize data. return new CachePartialUpdateException(msg, e); } } // Was not able to write keys. string innerErrCls = reader.ReadString(); string innerErrMsg = reader.ReadString(); Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace); return new CachePartialUpdateException(msg, innerErr); } /// <summary> /// Create JVM initialization exception. /// </summary> /// <param name="clsName">Class name.</param> /// <param name="msg">Message.</param> /// <param name="stackTrace">Stack trace.</param> /// <returns>Exception.</returns> [ExcludeFromCodeCoverage] // Covered by a test in a separate process. public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace) { if (clsName != null) return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace)); if (msg != null) return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace); return new IgniteException("Failed to initialize JVM."); } /// <summary> /// Reads nullable list. /// </summary> /// <param name="reader">Reader.</param> /// <returns>List.</returns> private static List<object> ReadNullableList(BinaryReader reader) { if (!reader.ReadBoolean()) return null; var size = reader.ReadInt(); var list = new List<object>(size); for (int i = 0; i < size; i++) list.Add(reader.ReadObject<object>()); return list; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace Lucene.Net.Util { /* * 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. */ /// <summary> /// Methods for manipulating arrays. /// <para/> /// @lucene.internal /// </summary> public sealed class ArrayUtil { /// <summary> /// Maximum length for an array; we set this to "a /// bit" below <see cref="int.MaxValue"/> because the exact max /// allowed byte[] is JVM dependent, so we want to avoid /// a case where a large value worked during indexing on /// one JVM but failed later at search time with a /// different JVM. /// </summary> public static readonly int MAX_ARRAY_LENGTH = int.MaxValue - 256; private ArrayUtil() // no instance { } /* Begin Apache Harmony code Revision taken on Friday, June 12. https://svn.apache.org/repos/asf/harmony/enhanced/classlib/archive/java6/modules/luni/src/main/java/java/lang/Integer.java */ /// <summary> /// Parses the string argument as if it was an <see cref="int"/> value and returns the /// result. Throws <see cref="FormatException"/> if the string does not represent an /// int quantity. /// <para/> /// NOTE: This was parseInt() in Lucene /// </summary> /// <param name="chars"> A string representation of an int quantity. </param> /// <returns> The value represented by the argument </returns> /// <exception cref="FormatException"> If the argument could not be parsed as an int quantity. </exception> public static int ParseInt32(char[] chars) { return ParseInt32(chars, 0, chars.Length, 10); } /// <summary> /// Parses a char array into an <see cref="int"/>. /// <para/> /// NOTE: This was parseInt() in Lucene /// </summary> /// <param name="chars"> The character array </param> /// <param name="offset"> The offset into the array </param> /// <param name="len"> The length </param> /// <returns> the <see cref="int"/> </returns> /// <exception cref="FormatException"> If it can't parse </exception> public static int ParseInt32(char[] chars, int offset, int len) { return ParseInt32(chars, offset, len, 10); } /// <summary> /// Parses the string argument as if it was an <see cref="int"/> value and returns the /// result. Throws <see cref="FormatException"/> if the string does not represent an /// <see cref="int"/> quantity. The second argument specifies the radix to use when parsing /// the value. /// <para/> /// NOTE: This was parseInt() in Lucene /// </summary> /// <param name="chars"> A string representation of an int quantity. </param> /// <param name="radix"> The base to use for conversion. </param> /// <returns> The value represented by the argument </returns> /// <exception cref="FormatException"> If the argument could not be parsed as an int quantity. </exception> public static int ParseInt32(char[] chars, int offset, int len, int radix) { int minRadix = 2, maxRadix = 36; if (chars == null || radix < minRadix || radix > maxRadix) { throw new System.FormatException(); } int i = 0; if (len == 0) { throw new System.FormatException("chars length is 0"); } bool negative = chars[offset + i] == '-'; if (negative && ++i == len) { throw new System.FormatException("can't convert to an int"); } if (negative == true) { offset++; len--; } return Parse(chars, offset, len, radix, negative); } private static int Parse(char[] chars, int offset, int len, int radix, bool negative) { int max = int.MinValue / radix; int result = 0; for (int i = 0; i < len; i++) { int digit = (int)System.Char.GetNumericValue(chars[i + offset]); if (digit == -1) { throw new System.FormatException("Unable to parse"); } if (max > result) { throw new System.FormatException("Unable to parse"); } int next = result * radix - digit; if (next > result) { throw new System.FormatException("Unable to parse"); } result = next; } /*while (offset < len) { }*/ if (!negative) { result = -result; if (result < 0) { throw new System.FormatException("Unable to parse"); } } return result; } /* END APACHE HARMONY CODE */ /// <summary> /// Returns an array size &gt;= <paramref name="minTargetSize"/>, generally /// over-allocating exponentially to achieve amortized /// linear-time cost as the array grows. /// <para/> /// NOTE: this was originally borrowed from Python 2.4.2 /// listobject.c sources (attribution in LICENSE.txt), but /// has now been substantially changed based on /// discussions from java-dev thread with subject "Dynamic /// array reallocation algorithms", started on Jan 12 /// 2010. /// <para/> /// @lucene.internal /// </summary> /// <param name="minTargetSize"> Minimum required value to be returned. </param> /// <param name="bytesPerElement"> Bytes used by each element of /// the array. See constants in <see cref="RamUsageEstimator"/>. </param> public static int Oversize(int minTargetSize, int bytesPerElement) { if (minTargetSize < 0) { // catch usage that accidentally overflows int throw new System.ArgumentException("invalid array size " + minTargetSize); } if (minTargetSize == 0) { // wait until at least one element is requested return 0; } // asymptotic exponential growth by 1/8th, favors // spending a bit more CPU to not tie up too much wasted // RAM: int extra = minTargetSize >> 3; if (extra < 3) { // for very small arrays, where constant overhead of // realloc is presumably relatively high, we grow // faster extra = 3; } int newSize = minTargetSize + extra; // add 7 to allow for worst case byte alignment addition below: if (newSize + 7 < 0) { // int overflowed -- return max allowed array size return int.MaxValue; } if (Constants.RUNTIME_IS_64BIT) { // round up to 8 byte alignment in 64bit env switch (bytesPerElement) { case 4: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 2: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 1: // round up to multiple of 8 return (newSize + 7) & 0x7ffffff8; case 8: // no rounding default: // odd (invalid?) size return newSize; } } else { // round up to 4 byte alignment in 64bit env switch (bytesPerElement) { case 2: // round up to multiple of 2 return (newSize + 1) & 0x7ffffffe; case 1: // round up to multiple of 4 return (newSize + 3) & 0x7ffffffc; case 4: case 8: // no rounding default: // odd (invalid?) size return newSize; } } } public static int GetShrinkSize(int currentSize, int targetSize, int bytesPerElement) { int newSize = Oversize(targetSize, bytesPerElement); // Only reallocate if we are "substantially" smaller. // this saves us from "running hot" (constantly making a // bit bigger then a bit smaller, over and over): if (newSize < currentSize / 2) { return newSize; } else { return currentSize; } } public static short[] Grow(short[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { short[] newArray = new short[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT16)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static short[] Grow(short[] array) { return Grow(array, 1 + array.Length); } public static float[] Grow(float[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { float[] newArray = new float[Oversize(minSize, RamUsageEstimator.NUM_BYTES_SINGLE)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static float[] Grow(float[] array) { return Grow(array, 1 + array.Length); } public static double[] Grow(double[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { double[] newArray = new double[Oversize(minSize, RamUsageEstimator.NUM_BYTES_DOUBLE)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static double[] Grow(double[] array) { return Grow(array, 1 + array.Length); } public static short[] Shrink(short[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT16); if (newSize != array.Length) { short[] newArray = new short[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } public static int[] Grow(int[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { int[] newArray = new int[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT32)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static int[] Grow(int[] array) { return Grow(array, 1 + array.Length); } public static int[] Shrink(int[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT32); if (newSize != array.Length) { int[] newArray = new int[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } public static long[] Grow(long[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { long[] newArray = new long[Oversize(minSize, RamUsageEstimator.NUM_BYTES_INT64)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static long[] Grow(long[] array) { return Grow(array, 1 + array.Length); } public static long[] Shrink(long[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_INT64); if (newSize != array.Length) { long[] newArray = new long[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } [CLSCompliant(false)] public static sbyte[] Grow(sbyte[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { var newArray = new sbyte[Oversize(minSize, 1)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static byte[] Grow(byte[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { byte[] newArray = new byte[Oversize(minSize, 1)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static byte[] Grow(byte[] array) { return Grow(array, 1 + array.Length); } public static byte[] Shrink(byte[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, 1); if (newSize != array.Length) { var newArray = new byte[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } public static bool[] Grow(bool[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { bool[] newArray = new bool[Oversize(minSize, 1)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static bool[] Grow(bool[] array) { return Grow(array, 1 + array.Length); } public static bool[] Shrink(bool[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, 1); if (newSize != array.Length) { bool[] newArray = new bool[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } public static char[] Grow(char[] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { char[] newArray = new char[Oversize(minSize, RamUsageEstimator.NUM_BYTES_CHAR)]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } public static char[] Grow(char[] array) { return Grow(array, 1 + array.Length); } public static char[] Shrink(char[] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_CHAR); if (newSize != array.Length) { char[] newArray = new char[newSize]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } [CLSCompliant(false)] public static int[][] Grow(int[][] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { var newArray = new int[Oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } [CLSCompliant(false)] public static int[][] Grow(int[][] array) { return Grow(array, 1 + array.Length); } [CLSCompliant(false)] public static int[][] Shrink(int[][] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF); if (newSize != array.Length) { int[][] newArray = new int[newSize][]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } [CLSCompliant(false)] public static float[][] Grow(float[][] array, int minSize) { Debug.Assert(minSize >= 0, "size must be positive (got " + minSize + "): likely integer overflow?"); if (array.Length < minSize) { float[][] newArray = new float[Oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][]; Array.Copy(array, 0, newArray, 0, array.Length); return newArray; } else { return array; } } [CLSCompliant(false)] public static float[][] Grow(float[][] array) { return Grow(array, 1 + array.Length); } [CLSCompliant(false)] public static float[][] Shrink(float[][] array, int targetSize) { Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?"); int newSize = GetShrinkSize(array.Length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF); if (newSize != array.Length) { float[][] newArray = new float[newSize][]; Array.Copy(array, 0, newArray, 0, newSize); return newArray; } else { return array; } } /// <summary> /// Returns hash of chars in range start (inclusive) to /// end (inclusive) /// </summary> public static int GetHashCode(char[] array, int start, int end) { int code = 0; for (int i = end - 1; i >= start; i--) { code = code * 31 + array[i]; } return code; } /// <summary> /// Returns hash of bytes in range start (inclusive) to /// end (inclusive) /// </summary> public static int GetHashCode(byte[] array, int start, int end) { int code = 0; for (int i = end - 1; i >= start; i--) { code = code * 31 + array[i]; } return code; } // Since Arrays.equals doesn't implement offsets for equals /// <summary> /// See if two array slices are the same. /// </summary> /// <param name="left"> The left array to compare </param> /// <param name="offsetLeft"> The offset into the array. Must be positive </param> /// <param name="right"> The right array to compare </param> /// <param name="offsetRight"> the offset into the right array. Must be positive </param> /// <param name="length"> The length of the section of the array to compare </param> /// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal /// </returns> /// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/> public static bool Equals(char[] left, int offsetLeft, char[] right, int offsetRight, int length) { if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length)) { for (int i = 0; i < length; i++) { if (left[offsetLeft + i] != right[offsetRight + i]) { return false; } } return true; } return false; } // Since Arrays.equals doesn't implement offsets for equals /// <summary> /// See if two array slices are the same. /// </summary> /// <param name="left"> The left array to compare </param> /// <param name="offsetLeft"> The offset into the array. Must be positive </param> /// <param name="right"> The right array to compare </param> /// <param name="offsetRight"> the offset into the right array. Must be positive </param> /// <param name="length"> The length of the section of the array to compare </param> /// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal /// </returns> /// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/> public static bool Equals(byte[] left, int offsetLeft, byte[] right, int offsetRight, int length) { if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length)) { for (int i = 0; i < length; i++) { if (left[offsetLeft + i] != right[offsetRight + i]) { return false; } } return true; } return false; } /* DISABLE this FOR NOW: this has performance problems until Java creates intrinsics for Class#getComponentType() and Array.newInstance() public static <T> T[] grow(T[] array, int minSize) { assert minSize >= 0: "size must be positive (got " + minSize + "): likely integer overflow?"; if (array.length < minSize) { @SuppressWarnings("unchecked") final T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), oversize(minSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } else return array; } public static <T> T[] grow(T[] array) { return grow(array, 1 + array.length); } public static <T> T[] shrink(T[] array, int targetSize) { assert targetSize >= 0: "size must be positive (got " + targetSize + "): likely integer overflow?"; final int newSize = getShrinkSize(array.length, targetSize, RamUsageEstimator.NUM_BYTES_OBJECT_REF); if (newSize != array.length) { @SuppressWarnings("unchecked") final T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), newSize); System.arraycopy(array, 0, newArray, 0, newSize); return newArray; } else return array; } */ // Since Arrays.equals doesn't implement offsets for equals /// <summary> /// See if two array slices are the same. /// </summary> /// <param name="left"> The left array to compare </param> /// <param name="offsetLeft"> The offset into the array. Must be positive </param> /// <param name="right"> The right array to compare </param> /// <param name="offsetRight"> the offset into the right array. Must be positive </param> /// <param name="length"> The length of the section of the array to compare </param> /// <returns> <c>true</c> if the two arrays, starting at their respective offsets, are equal /// </returns> /// <seealso cref="Support.Arrays.Equals{T}(T[], T[])"/> public static bool Equals(int[] left, int offsetLeft, int[] right, int offsetRight, int length) { if ((offsetLeft + length <= left.Length) && (offsetRight + length <= right.Length)) { for (int i = 0; i < length; i++) { if (left[offsetLeft + i] != right[offsetRight + i]) { return false; } } return true; } return false; } /// <summary> /// NOTE: This was toIntArray() in Lucene /// </summary> public static int[] ToInt32Array(ICollection<int?> ints) { int[] result = new int[ints.Count]; int upto = 0; foreach (int? v in ints) { if (v.HasValue) { result[upto++] = v.Value; } else { throw new NullReferenceException(); // LUCENENET NOTE: This is the same behavior you get in Java when setting int = Integer and the integer is null. } } // paranoia: Debug.Assert(upto == result.Length); return result; } // LUCENENET specific - we don't have an IComparable<T> constraint - // the logic of GetNaturalComparer<T> handles that so we just // do a cast here. #if FEATURE_SERIALIZABLE [Serializable] #endif private class NaturalComparer<T> : IComparer<T> //where T : IComparable<T> { internal NaturalComparer() { } public virtual int Compare(T o1, T o2) { return ((IComparable<T>)o1).CompareTo(o2); } } /// <summary> /// Get the natural <see cref="IComparer{T}"/> for the provided object class. /// <para/> /// The comparer returned depends on the <typeparam name="T"/> argument: /// <list type="number"> /// <item><description>If the type is <see cref="string"/>, the comparer returned uses /// the <see cref="string.CompareOrdinal(string, string)"/> to make the comparison /// to ensure that the current culture doesn't affect the results. This is the /// default string comparison used in Java, and what Lucene's design depends on.</description></item> /// <item><description>If the type implements <see cref="IComparable{T}"/>, the comparer uses /// <see cref="IComparable{T}.CompareTo(T)"/> for the comparison. This allows /// the use of types with custom comparison schemes.</description></item> /// <item><description>If neither of the above conditions are true, will default to <see cref="Comparer{T}.Default"/>.</description></item> /// </list> /// <para/> /// NOTE: This was naturalComparer() in Lucene /// </summary> public static IComparer<T> GetNaturalComparer<T>() //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed { Type genericClosingType = typeof(T); // LUCENENET specific - we need to ensure that strings are compared // in a culture-insenitive manner. if (genericClosingType.Equals(typeof(string))) { return (IComparer<T>)StringComparer.Ordinal; } // LUCENENET specific - Only return the NaturalComparer if the type // implements IComparable<T>, otherwise use Comparer<T>.Default. // This allows the comparison to be customized, but it is not mandatory // to implement IComparable<T>. else if (typeof(IComparable<T>).GetTypeInfo().IsAssignableFrom(genericClosingType)) { return new NaturalComparer<T>(); } return Comparer<T>.Default; } /// <summary> /// Swap values stored in slots <paramref name="i"/> and <paramref name="j"/> </summary> public static void Swap<T>(T[] arr, int i, int j) { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } // intro-sorts /// <summary> /// Sorts the given array slice using the <see cref="IComparer{T}"/>. This method uses the intro sort /// algorithm, but falls back to insertion sort for small arrays. </summary> /// <param name="fromIndex"> Start index (inclusive) </param> /// <param name="toIndex"> End index (exclusive) </param> public static void IntroSort<T>(T[] a, int fromIndex, int toIndex, IComparer<T> comp) { if (toIndex - fromIndex <= 1) { return; } (new ArrayIntroSorter<T>(a, comp)).Sort(fromIndex, toIndex); } /// <summary> /// Sorts the given array using the <see cref="IComparer{T}"/>. This method uses the intro sort /// algorithm, but falls back to insertion sort for small arrays. /// </summary> public static void IntroSort<T>(T[] a, IComparer<T> comp) { IntroSort(a, 0, a.Length, comp); } /// <summary> /// Sorts the given array slice in natural order. This method uses the intro sort /// algorithm, but falls back to insertion sort for small arrays. </summary> /// <param name="fromIndex"> Start index (inclusive) </param> /// <param name="toIndex"> End index (exclusive) </param> public static void IntroSort<T>(T[] a, int fromIndex, int toIndex) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed { if (toIndex - fromIndex <= 1) { return; } IntroSort(a, fromIndex, toIndex, ArrayUtil.GetNaturalComparer<T>()); } /// <summary> /// Sorts the given array in natural order. This method uses the intro sort /// algorithm, but falls back to insertion sort for small arrays. /// </summary> public static void IntroSort<T>(T[] a) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed { IntroSort(a, 0, a.Length); } // tim sorts: /// <summary> /// Sorts the given array slice using the <see cref="IComparer{T}"/>. This method uses the Tim sort /// algorithm, but falls back to binary sort for small arrays. </summary> /// <param name="fromIndex"> Start index (inclusive) </param> /// <param name="toIndex"> End index (exclusive) </param> public static void TimSort<T>(T[] a, int fromIndex, int toIndex, IComparer<T> comp) { if (toIndex - fromIndex <= 1) { return; } (new ArrayTimSorter<T>(a, comp, a.Length / 64)).Sort(fromIndex, toIndex); } /// <summary> /// Sorts the given array using the <see cref="IComparer{T}"/>. this method uses the Tim sort /// algorithm, but falls back to binary sort for small arrays. /// </summary> public static void TimSort<T>(T[] a, IComparer<T> comp) { TimSort(a, 0, a.Length, comp); } /// <summary> /// Sorts the given array slice in natural order. this method uses the Tim sort /// algorithm, but falls back to binary sort for small arrays. </summary> /// <param name="fromIndex"> Start index (inclusive) </param> /// <param name="toIndex"> End index (exclusive) </param> public static void TimSort<T>(T[] a, int fromIndex, int toIndex) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed { if (toIndex - fromIndex <= 1) { return; } TimSort(a, fromIndex, toIndex, ArrayUtil.GetNaturalComparer<T>()); } /// <summary> /// Sorts the given array in natural order. this method uses the Tim sort /// algorithm, but falls back to binary sort for small arrays. /// </summary> public static void TimSort<T>(T[] a) //where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed { TimSort(a, 0, a.Length); } } }
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using Tango; namespace Tango { /// <summary> /// Wraps separate textures for Y, U, and V planes. /// </summary> public class YUVTexture { /// <summary> /// The m_video overlay texture y. /// Columns 1280/4 [bytes packed in RGBA channels] /// Rows 720 /// </summary> public Texture2D m_videoOverlayTextureY; /// <summary> /// The m_video overlay texture cb. /// Columns 640/4 [bytes packed in RGBA channels] /// Rows 360 /// </summary> public Texture2D m_videoOverlayTextureCb; /// <summary> /// The m_video overlay texture cr. /// Columns 640 * 2 / 4 [bytes packed in RGBA channels] /// Rows 360 /// </summary> public Texture2D m_videoOverlayTextureCr; /// <summary> /// Initializes a new instance of the <see cref="Tango.YUVTexture"/> class. /// NOTE : Texture resolutions will be reset by the API. The sizes passed /// into the constructor are not guaranteed to persist when running on device. /// </summary> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="format">Format.</param> /// <param name="mipmap">If set to <c>true</c> mipmap.</param> public YUVTexture(int yPlaneWidth, int yPlaneHeight, int uvPlaneWidth, int uvPlaneHeight, TextureFormat format, bool mipmap) { m_videoOverlayTextureY = new Texture2D(yPlaneWidth, yPlaneHeight, format, mipmap); m_videoOverlayTextureCb = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap); m_videoOverlayTextureCr = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap); } /// <summary> /// Resizes all yuv texture planes. /// </summary> /// <param name="yPlaneWidth">Y plane width.</param> /// <param name="yPlaneHeight">Y plane height.</param> /// <param name="uvPlaneWidth">Uv plane width.</param> /// <param name="uvPlaneHeight">Uv plane height.</param> public void ResizeAll(int yPlaneWidth, int yPlaneHeight, int uvPlaneWidth, int uvPlaneHeight) { m_videoOverlayTextureY.Resize(yPlaneWidth, yPlaneHeight); m_videoOverlayTextureCb.Resize(uvPlaneWidth, uvPlaneHeight); m_videoOverlayTextureCr.Resize(uvPlaneWidth, uvPlaneHeight); } } /// <summary> /// Video Overlay Provider class provide video functions /// to get frame textures. /// </summary> public class VideoOverlayProvider { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void TangoService_onImageAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId, [In,Out] TangoImageBuffer image); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void TangoService_onUnityFrameAvailable(IntPtr callbackContext, Tango.TangoEnums.TangoCameraId cameraId); private static readonly string CLASS_NAME = "VideoOverlayProvider"; private static IntPtr callbackContext; /// <summary> /// Connects the texture. /// </summary> /// <param name="cameraId">Camera identifier.</param> /// <param name="textureId">Texture identifier.</param> public static void ConnectTexture(TangoEnums.TangoCameraId cameraId, int textureId) { int returnValue = VideoOverlayAPI.TangoService_connectTextureId(cameraId, textureId); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!"); } } public static void ExperimentalConnectTexture(TangoEnums.TangoCameraId cameraId, YUVTexture textures, TangoService_onUnityFrameAvailable onUnityFrameAvailable) { int returnValue = VideoOverlayAPI.TangoService_Experimental_connectTextureIdUnity(cameraId, (uint)textures.m_videoOverlayTextureY.GetNativeTextureID(), (uint)textures.m_videoOverlayTextureCb.GetNativeTextureID(), (uint)textures.m_videoOverlayTextureCr.GetNativeTextureID(), callbackContext, onUnityFrameAvailable); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!"); } } /// <summary> /// Renders the latest frame. /// </summary> /// <returns>The latest frame timestamp.</returns> /// <param name="cameraId">Camera identifier.</param> public static double RenderLatestFrame(TangoEnums.TangoCameraId cameraId) { double timestamp = 0.0; int returnValue = VideoOverlayAPI.TangoService_updateTexture(cameraId, ref timestamp); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("VideoOverlayProvider.UpdateTexture() Texture was not updated by camera!"); } return timestamp; } /// <summary> /// Get the camera/sensor intrinsics. /// </summary> /// <param name="cameraId">Camera identifier.</param> /// <param name="intrinsics">Camera intrinsics data.</param> public static void GetIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics) { int returnValue = VideoOverlayAPI.TangoService_getCameraIntrinsics(cameraId, intrinsics); if (returnValue != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("IntrinsicsProviderAPI.TangoService_getCameraIntrinsics() failed!"); } } /// <summary> /// Sets the callback for notifications when image data is ready. /// </summary> /// <param name="cameraId">Camera identifier.</param> /// <param name="onImageAvailable">On image available callback handler.</param> public static void SetCallback(TangoEnums.TangoCameraId cameraId, TangoService_onImageAvailable onImageAvailable) { int returnValue = VideoOverlayAPI.TangoService_connectOnFrameAvailable(cameraId, callbackContext, onImageAvailable); if(returnValue == Tango.Common.ErrorType.TANGO_SUCCESS) { Debug.Log(CLASS_NAME + ".SetCallback() Callback was set."); } else { Debug.Log(CLASS_NAME + ".SetCallback() Callback was not set!"); } } #region NATIVE_FUNCTIONS /// <summary> /// Video overlay native function import. /// </summary> private struct VideoOverlayAPI { #if UNITY_ANDROID && !UNITY_EDITOR [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId, IntPtr context, [In,Out] TangoService_onImageAvailable onImageAvailable); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id, uint texture_y, uint texture_Cb, uint texture_Cr, IntPtr context, TangoService_onUnityFrameAvailable onUnityFrameAvailable); #else public static int TangoService_connectTextureId(TangoEnums.TangoCameraId cameraId, int textureHandle) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_getCameraIntrinsics(TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_connectOnFrameAvailable(TangoEnums.TangoCameraId cameraId, IntPtr context, [In,Out] TangoService_onImageAvailable onImageAvailable) { return Tango.Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_Experimental_connectTextureIdUnity(TangoEnums.TangoCameraId id, uint texture_y, uint texture_Cb, uint texture_Cr, IntPtr context, TangoService_onUnityFrameAvailable onUnityFrameAvailable) { return Tango.Common.ErrorType.TANGO_SUCCESS; } #endif #endregion } } }
/* * MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Text; /** * by bn on 30/06/2018. */ namespace Photon.Parts { public class PhotonFile { private IFileHeader iFileHeader; private int islandLayerCount; private List<int> islandLayers; private StringBuilder islandList; private List<PhotonFileLayer> layers; private int margin; private List<int> marginLayers; private PhotonFilePreview previewOne; private PhotonFilePreview previewTwo; public void AdjustLayerSettings() { for (int i = 0; i < layers.Count; i++) { PhotonFileLayer layer = layers[i]; if (i < iFileHeader.GetBottomLayers()) { layer.SetLayerExposure(iFileHeader.GetBottomExposureTimeSeconds()); } else { layer.SetLayerExposure(iFileHeader.GetNormalExposure()); } layer.SetLayerOffTimeSeconds(iFileHeader.GetOffTimeSeconds()); } } public void Calculate(Action<string> reportProgress) { PhotonFileLayer.CalculateLayers((PhotonFileHeader)iFileHeader, layers, margin, reportProgress); ResetMarginAndIslandInfo(); } public void Calculate(int layerNo) { PhotonFileLayer.CalculateLayers((PhotonFileHeader)iFileHeader, layers, margin, layerNo); ResetMarginAndIslandInfo(); } public void CalculateAaLayers(Action<string> reportProgress, PhotonAaMatrix photonAaMatrix) { PhotonFileLayer.CalculateAALayers((PhotonFileHeader)iFileHeader, layers, photonAaMatrix, reportProgress); } public void ChangeToVersion2() { iFileHeader.SetFileVersion(2); } public void FixAll(Action<string> reportProgress) { bool layerWasFixed; do { do { // Repeatedly fix layers until none are possible to fix // Fixing some layers can make other layers auto-fixable layerWasFixed = FixLayers(reportProgress); } while (layerWasFixed); if (islandLayers.Count > 0) { // Nothing can be done further, just remove all layers left layerWasFixed = RemoveAllIslands(reportProgress) || layerWasFixed; } if (layerWasFixed && islandLayers.Count > 0) { // We could've created new islands by removing islands, repeat fixing process // until everything is fixed or nothing can be done reportProgress?.Invoke("<br>Some layers were fixed, but " + islandLayers.Count + " still unsupported, repeating...<br>"); } } while (layerWasFixed); } public void FixLayerHeights() { int index = 0; foreach (var layer in layers) { layer.SetLayerPositionZ(index * iFileHeader.GetLayerHeight()); index++; } } public bool FixLayers(Action<string> reportProgress) { bool layersFixed = false; PhotonLayer layer = null; foreach (int layerNo in islandLayers) { reportProgress?.Invoke("Checking layer " + layerNo); // Unpack the layer data to the layer utility class PhotonFileLayer fileLayer = layers[layerNo]; if (layer == null) { layer = fileLayer.GetLayer(); } else { fileLayer.GetUpdateLayer(layer); } int changed = Fixit(reportProgress, layer, fileLayer, 10); if (changed == 0) { reportProgress?.Invoke(", but nothing could be done."); } else { fileLayer.SaveLayer(layer); Calculate(layerNo); if (layerNo < GetLayerCount() - 1) { Calculate(layerNo + 1); } layersFixed = true; } reportProgress?.Invoke("<br>"); } FindIslands(); return layersFixed; } public int GetAALevels() { return iFileHeader.GetAALevels(); } public int GetHeight() { return iFileHeader.GetResolutionX(); } public string GetInformation() { if (iFileHeader == null) return ""; return iFileHeader.GetInformation(); } public int GetIslandLayerCount() { if (islandList == null) { FindIslands(); } return islandLayerCount; } public List<int> GetIslandLayers() { if (islandList == null) { FindIslands(); } return islandLayers; } public PhotonFileLayer GetLayer(int i) { if (layers != null && layers.Count > i) { return layers[i]; } return null; } public int GetLayerCount() { return iFileHeader.GetNumberOfLayers(); } public string GetLayerInformation() { if (islandList == null) { FindIslands(); } if (islandLayerCount == 0) { return "Whoopee, all is good, no unsupported areas"; } else if (islandLayerCount == 1) { return "Unsupported islands found in layer " + islandList.ToString(); } return "Unsupported islands found in layers " + islandList.ToString(); } public string GetMarginInformation() { if (marginLayers == null) { return "No safety margin set, printing to the border."; } else { if (marginLayers.Count == 0) { return "The model is within the defined safety margin (" + this.margin + " pixels)."; } else if (marginLayers.Count == 1) { return "The layer " + marginLayers[0] + " contains model parts that extend beyond the margin."; } var marginList = new StringBuilder(); int count = 0; foreach (var layer in marginLayers) { if (count > 10) { marginList.Append(", ..."); break; } else { if (marginList.Length > 0) marginList.Append(", "); marginList.Append(layer); } count++; } return "The layers " + marginList.ToString() + " contains model parts that extend beyond the margin."; } } public List<int> GetMarginLayers() { if (marginLayers == null) { return new List<int>(); } return marginLayers; } public IFileHeader GetPhotonFileHeader() { return iFileHeader; } public long GetPixels() { long total = 0; if (layers != null) { foreach (var layer in layers) { total += layer.GetPixels(); } } return total; } public PhotonFilePreview GetPreviewOne() { return previewOne; } public PhotonFilePreview GetPreviewTwo() { return previewTwo; } public int GetVersion() { return iFileHeader.GetVersion(); } public int GetWidth() { return iFileHeader.GetResolutionY(); } public float GetZdrift() { float expectedHeight = iFileHeader.GetLayerHeight() * (iFileHeader.GetNumberOfLayers() - 1); float actualHeight = layers[layers.Count - 1].GetLayerPositionZ(); return expectedHeight - actualHeight; } public bool HasAA() { return iFileHeader.HasAA(); } public PhotonFile ReadFile(string fileName, Action<string> reportProgress) { using (var file = File.OpenRead(fileName)) { return ReadFile(GetBinaryData(file), reportProgress); } } public bool RemoveAllIslands(Action<string> reportProgress) { bool layersFixed = false; reportProgress?.Invoke("Removing islands from " + islandLayers.Count + " layers...<br>"); PhotonLayer layer = null; foreach (var layerNo in islandLayers) { PhotonFileLayer fileLayer = layers[layerNo]; if (layer == null) { layer = fileLayer.GetLayer(); } else { fileLayer.GetUpdateLayer(layer); } reportProgress?.Invoke("Removing islands from layer " + layerNo); int removed = layer.RemoveIslands(); if (removed == 0) { reportProgress?.Invoke(", but nothing could be done."); } else { reportProgress?.Invoke(", " + removed + " islands removed"); fileLayer.SaveLayer(layer); Calculate(layerNo); if (layerNo < GetLayerCount() - 1) { Calculate(layerNo + 1); } layersFixed = true; } reportProgress?.Invoke("<br>"); } FindIslands(); return layersFixed; } public void SaveFile(string fileName) { using (var fileOutputStream = new BinaryWriter(File.OpenWrite(fileName))) { WriteFile(fileOutputStream); } } // only call this when recalculating AA levels public void SetAALevels(int levels) { iFileHeader.SetAALevels(levels, layers); } public void SetMargin(int margin) { this.margin = margin; } public void UnLink() { while (layers.Count > 0) { PhotonFileLayer layer = layers[0]; layers.RemoveAt(0); layer.UnLink(); } if (islandLayers != null) { islandLayers.Clear(); } if (marginLayers != null) { marginLayers.Clear(); } iFileHeader.UnLink(); iFileHeader = null; previewOne.UnLink(); previewOne = null; previewTwo.UnLink(); previewTwo = null; } private void FindIslands() { if (islandLayers != null) { islandLayers.Clear(); islandList = new StringBuilder(); islandLayerCount = 0; if (layers != null) { for (int i = 0; i < iFileHeader.GetNumberOfLayers(); i++) { PhotonFileLayer layer = layers[i]; if (layer.GetIsLandsCount() > 0) { if (islandLayerCount < 11) { if (islandLayerCount == 10) { islandList.Append(", ..."); } else { if (islandList.Length > 0) islandList.Append(", "); islandList.Append(i); } } islandLayerCount++; islandLayers.Add(i); } } } } } private int Fixit(Action<string> reportProgress, PhotonLayer layer, PhotonFileLayer fileLayer, int loops) { int changed = layer.Fixlayer(); if (changed > 0) { layer.Reduce(); fileLayer.UpdateLayerIslands(layer); reportProgress?.Invoke(", " + changed + " pixels changed"); if (loops > 0) { changed += Fixit(reportProgress, layer, fileLayer, loops - 1); } } return changed; } private byte[] GetBinaryData(FileStream entry) { int fileSize = (int)entry.Length; byte[] fileData = new byte[fileSize]; var stream = new BinaryReader(entry); int bytesRead = 0; while (bytesRead < fileSize) { int readCount = stream.Read(fileData, bytesRead, fileSize - bytesRead); if (readCount < 0) { throw new IOException("Could not read all bytes of the file"); } bytesRead += readCount; } return fileData; } private PhotonFile ReadFile(byte[] file, Action<string> reportProgress) { reportProgress?.Invoke("Reading Photon file header information..."); var photonFileHeader = new PhotonFileHeader(file); iFileHeader = photonFileHeader; reportProgress?.Invoke("Reading photon large preview image information..."); previewOne = new PhotonFilePreview(photonFileHeader.GetPreviewOneOffsetAddress(), file); reportProgress?.Invoke("Reading photon small preview image information..."); previewTwo = new PhotonFilePreview(photonFileHeader.GetPreviewTwoOffsetAddress(), file); if (photonFileHeader.GetVersion() > 1) { reportProgress?.Invoke("Reading Print parameters information..."); photonFileHeader.ReadParameters(file); } reportProgress?.Invoke("Reading photon layers information..."); layers = PhotonFileLayer.ReadLayers(photonFileHeader, file, margin, reportProgress); ResetMarginAndIslandInfo(); return this; } private void ResetMarginAndIslandInfo() { islandList = null; islandLayerCount = 0; islandLayers = new List<int>(); if (margin > 0) { marginLayers = new List<int>(); int i = 0; foreach (PhotonFileLayer layer in layers) { if (layer.DoExtendMargin()) { marginLayers.Add(i); } i++; } } } private void WriteFile(BinaryWriter writer) { int antiAliasLevel = iFileHeader.GetAALevels(); int headerPos = 0; int previewOnePos = headerPos + iFileHeader.GetByteSize(); int previewTwoPos = previewOnePos + previewOne.GetByteSize(); int layerDefinitionPos = previewTwoPos + previewTwo.GetByteSize(); int parametersPos = 0; int machineInfoPos = 0; if (iFileHeader.GetVersion() > 1) { parametersPos = layerDefinitionPos; if (((PhotonFileHeader)iFileHeader).photonFileMachineInfo.GetByteSize() > 0) { machineInfoPos = parametersPos + ((PhotonFileHeader)iFileHeader).photonFilePrintParameters.GetByteSize(); layerDefinitionPos = machineInfoPos + ((PhotonFileHeader)iFileHeader).photonFileMachineInfo.GetByteSize(); } else { layerDefinitionPos = parametersPos + ((PhotonFileHeader)iFileHeader).photonFilePrintParameters.GetByteSize(); } } int dataPosition = layerDefinitionPos + (PhotonFileLayer.GetByteSize() * iFileHeader.GetNumberOfLayers() * antiAliasLevel); ((PhotonFileHeader)iFileHeader).Save(writer, previewOnePos, previewTwoPos, layerDefinitionPos, parametersPos, machineInfoPos); previewOne.Save(writer, previewOnePos); previewTwo.Save(writer, previewTwoPos); if (iFileHeader.GetVersion() > 1) { ((PhotonFileHeader)iFileHeader).photonFilePrintParameters.Save(writer); ((PhotonFileHeader)iFileHeader).photonFileMachineInfo.Save(writer, machineInfoPos); } // Optimize order for speed read on photon for (int i = 0; i < iFileHeader.GetNumberOfLayers(); i++) { PhotonFileLayer layer = layers[i]; dataPosition = layer.SavePos(dataPosition); if (antiAliasLevel > 1) { for (int a = 0; a < (antiAliasLevel - 1); a++) { dataPosition = layer.GetAntiAlias(a).SavePos(dataPosition); } } } // Order for backward compatibility with photon/cbddlp version 1 for (int i = 0; i < iFileHeader.GetNumberOfLayers(); i++) { layers[i].Save(writer); } if (antiAliasLevel > 1) { for (int a = 0; a < (antiAliasLevel - 1); a++) { for (int i = 0; i < iFileHeader.GetNumberOfLayers(); i++) { layers[i].GetAntiAlias(a).Save(writer); } } } // Optimize order for speed read on photon for (int i = 0; i < iFileHeader.GetNumberOfLayers(); i++) { PhotonFileLayer layer = layers[i]; layer.SaveData(writer); if (antiAliasLevel > 1) { for (int a = 0; a < (antiAliasLevel - 1); a++) { layer.GetAntiAlias(a).SaveData(writer); } } } } } }
// ---------------------------------------------------------------------------- // <copyright file="AccountService.cs" company="Exit Games GmbH"> // Photon Cloud Account Service - Copyright (C) 2012 Exit Games GmbH // </copyright> // <summary> // Provides methods to register a new user-account for the Photon Cloud and // get the resulting appId. // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- #if UNITY_EDITOR using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System; using System.Collections.Generic; using System.IO; using System.Net; using ExitGames.Client.Photon; using Newtonsoft.Json; public class AccountService { private const string ServiceUrl = "https://service.exitgames.com/AccountExt/AccountServiceExt.aspx"; private Action<AccountService> registrationCallback; // optional (when using async reg) public string Message { get; private set; } // msg from server (in case of success, this is the appid) protected internal Exception Exception { get; set; } // exceptions in account-server communication public string AppId { get; private set; } public string AppId2 { get; private set; } public int ReturnCode { get; private set; } // 0 = OK. anything else is a error with Message public enum Origin : byte { ServerWeb = 1, CloudWeb = 2, Pun = 3, Playmaker = 4 }; /// <summary> /// Creates a instance of the Account Service to register Photon Cloud accounts. /// </summary> public AccountService() { WebRequest.DefaultWebProxy = null; ServicePointManager.ServerCertificateValidationCallback = Validator; } public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; // any certificate is ok in this case } /// <summary> /// Attempts to create a Photon Cloud Account. /// Check ReturnCode, Message and AppId to get the result of this attempt. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">Marks which channel created the new account (if it's new).</param> /// <param name="serviceType">Defines which type of Photon-service is being requested.</param> public void RegisterByEmail(string email, Origin origin, string serviceType = null) { this.registrationCallback = null; this.AppId = string.Empty; this.AppId2 = string.Empty; this.Message = string.Empty; this.ReturnCode = -1; string result; try { WebRequest req = HttpWebRequest.Create(this.RegistrationUri(email, (byte)origin, serviceType)); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; // now read result StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } catch (Exception ex) { this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; return; } this.ParseResult(result); } /// <summary> /// Attempts to create a Photon Cloud Account asynchronously. /// Once your callback is called, check ReturnCode, Message and AppId to get the result of this attempt. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">Marks which channel created the new account (if it's new).</param> /// <param name="serviceType">Defines which type of Photon-service is being requested.</param> /// <param name="callback">Called when the result is available.</param> public void RegisterByEmailAsync(string email, Origin origin, string serviceType, Action<AccountService> callback = null) { this.registrationCallback = callback; this.AppId = string.Empty; this.AppId2 = string.Empty; this.Message = string.Empty; this.ReturnCode = -1; try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(this.RegistrationUri(email, (byte)origin, serviceType)); req.Timeout = 5000; // TODO: The Timeout property has no effect on asynchronous requests made with the BeginGetResponse req.BeginGetResponse(this.OnRegisterByEmailCompleted, req); } catch (Exception ex) { this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; if (this.registrationCallback != null) { this.registrationCallback(this); } } } /// <summary> /// Internal callback with result of async HttpWebRequest (in RegisterByEmailAsync). /// </summary> /// <param name="ar"></param> private void OnRegisterByEmailCompleted(IAsyncResult ar) { try { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.OK) { // no error. use the result StreamReader reader = new StreamReader(response.GetResponseStream()); string result = reader.ReadToEnd(); this.ParseResult(result); } else { // a response but some error on server. show message this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; } } catch (Exception ex) { // not even a response. show message this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; } if (this.registrationCallback != null) { this.registrationCallback(this); } } /// <summary> /// Creates the service-call Uri, escaping the email for security reasons. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">1 = server-web, 2 = cloud-web, 3 = PUN, 4 = playmaker</param> /// <param name="serviceType">Defines which type of Photon-service is being requested. Options: "", "voice", "chat"</param> /// <returns>Uri to call.</returns> private Uri RegistrationUri(string email, byte origin, string serviceType) { if (serviceType == null) { serviceType = string.Empty; } string emailEncoded = Uri.EscapeDataString(email); string uriString = string.Format("{0}?email={1}&origin={2}&serviceType={3}", ServiceUrl, emailEncoded, origin, serviceType); return new Uri(uriString); } /// <summary> /// Reads the Json response and applies it to local properties. /// </summary> /// <param name="result"></param> private void ParseResult(string result) { if (string.IsNullOrEmpty(result)) { this.Message = "Server's response was empty. Please register through account website during this service interruption."; return; } Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(result); if (values == null) { this.Message = "Service temporarily unavailable. Please register through account website."; return; } int returnCodeInt = -1; string returnCodeString = string.Empty; string message; string messageDetailed; values.TryGetValue("ReturnCode", out returnCodeString); values.TryGetValue("Message", out message); values.TryGetValue("MessageDetailed", out messageDetailed); int.TryParse(returnCodeString, out returnCodeInt); this.ReturnCode = returnCodeInt; if (returnCodeInt == 0) { // returnCode == 0 means: all ok. message is new AppId this.AppId = message; if (PhotonEditorUtils.HasVoice) { this.AppId2 = messageDetailed; } } else { // any error gives returnCode != 0 this.AppId = string.Empty; if (PhotonEditorUtils.HasVoice) { this.AppId2 = string.Empty; } this.Message = message; } } } #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. #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using Xunit; using System; using System.Collections.Generic; using System.IO; namespace BasicEventSourceTests { /// <summary> /// The EventTestHarness class knows how to run a set of single-event tests on either /// the ETW pipeline or the EventListener pipeline. /// /// Basically you make up a bunch of SubTests and then hand it to this harness /// to run them in bulk. /// </summary> public static class EventTestHarness { /// <summary> /// LogWriteLine will dump its output into a string that will be appended to any exception /// that happened during a test the harness is running. /// </summary> /// <param name="format"></param> /// <param name="arg"></param> public static void LogWriteLine(string format, params object[] arg) { if (_log == null) return; _log.Write("{0:mm:ss.fff} : ", DateTime.UtcNow); _log.WriteLine(format, arg); } // Use to log things in the test itself if needed private static StringWriter _log = null; /// <summary> /// Runs a series of tests 'tests' using the listener (either an ETWListener or an EventListenerListener) on /// an EventSource 'source' passing it the filter parameters=options (by default source turn on completely /// /// Note that this routine calls Dispose on the listener, so it can't be used after that. /// </summary> public static void RunTests(List<SubTest> tests, Listener listener, EventSource source, FilteringOptions options = null) { int expectedTestNumber = 0; SubTest currentTest = null; List<Event> replies = new List<Event>(2); // Wire up the callback to handle the validation when the listener receives events. listener.OnEvent = delegate (Event data) { if (data.ProviderName == "TestHarnessEventSource") { Assert.Equal(data.EventName, "StartTest"); int testNumber = (int)data.PayloadValue(1, "testNumber"); Assert.Equal(expectedTestNumber, testNumber); // Validate that the events that came in during the test are correct. if (currentTest != null) { // You can use the currentTest.Name to set a filter in the harness // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII") // so the test only runs this one sub-test. Then you can set // breakpoints to watch the events be generated. // // All events from EventSource infrastructure should be coming from // the ReportOutOfBand, so placing a breakpoint there is typically useful. if (currentTest.EventListValidator != null) currentTest.EventListValidator(replies); else { // we only expect exactly one reply Assert.Equal(replies.Count, 1); currentTest.EventValidator(replies[0]); } } replies.Clear(); if (testNumber < tests.Count) { currentTest = tests[testNumber]; Assert.Equal(currentTest.Name, data.PayloadValue(0, "name")); expectedTestNumber++; _log = new StringWriter(); LogWriteLine("STARTING Sub-Test {0}", currentTest.Name); } else { Assert.NotNull(currentTest); Assert.Equal("", data.PayloadValue(0, "name")); Assert.Equal(tests.Count, testNumber); currentTest = null; } } else { LogWriteLine("Received Event {0}", data); // If expectedTestNumber is 0 then this is before the first test // If expectedTestNumber is count then it is after the last test Assert.NotNull(currentTest); replies.Add(data); } }; // Run the tests. collecting and validating the results. try { using (TestHarnessEventSource testHarnessEventSource = new TestHarnessEventSource()) { // Turn on the test EventSource. listener.EventSourceSynchronousEnable(source, options); // And the harnesses's EventSource. listener.EventSourceSynchronousEnable(testHarnessEventSource); // Generate events for all the tests, surrounded by events that tell us we are starting a test. int testNumber = 0; foreach (var test in tests) { testHarnessEventSource.StartTest(test.Name, testNumber); test.EventGenerator(); testNumber++; } testHarnessEventSource.StartTest("", testNumber); // Empty test marks the end of testing. // Disable the listeners. listener.EventSourceCommand(source.Name, EventCommand.Disable); listener.EventSourceCommand(testHarnessEventSource.Name, EventCommand.Disable); // Send something that should be ignored. testHarnessEventSource.IgnoreEvent(); } } catch (Exception e) { if (e is EventSourceException) e = e.InnerException; LogWriteLine("Exception thrown: {0}", e.Message); var exceptionText = new StringWriter(); exceptionText.WriteLine("Error Detected in EventTestHarness.RunTest"); if (currentTest != null) exceptionText.WriteLine("FAILURE IN SUBTEST: \"{0}\"", currentTest.Name); exceptionText.WriteLine("************* EXCEPTION INFO ***************"); exceptionText.WriteLine(e.ToString()); exceptionText.WriteLine("*********** END EXCEPTION INFO *************"); if (_log != null) { exceptionText.WriteLine("************* LOGGING MESSAGES ***************"); exceptionText.WriteLine(_log.ToString()); exceptionText.WriteLine("*********** END LOGGING MESSAGES *************"); } exceptionText.WriteLine("Version of Runtime {0}", Environment.Version); exceptionText.WriteLine("Version of OS {0}", Environment.OSVersion); exceptionText.WriteLine("**********************************************"); throw new EventTestHarnessException(exceptionText.ToString(), e); } listener.Dispose(); // Indicate we are done listening. For the ETW file based cases, we do all the processing here // expectedTetst number are the number of tests we successfully ran. Assert.Equal(expectedTestNumber, tests.Count); } public class EventTestHarnessException : Exception { public EventTestHarnessException(string message, Exception exception) : base(message, exception) { } } /// <summary> /// This eventSource I use to emit events to separate tests from each other. /// </summary> private class TestHarnessEventSource : EventSource { public void StartTest(string name, int testNumber) { WriteEvent(1, name, testNumber); } /// <summary> /// Sent to make sure the listener is ignoring when it should be. /// </summary> public void IgnoreEvent() { WriteEvent(2); } } } /// <summary> /// A boring typed container that holds information about a test of single EventSource event /// It holds the /// name, /// the code to generate an event to test (EventGenerator) /// the code to validate that the event is correct (EventValidator) /// OR the code to validate that the List of events is (EventListValidator) (when the output is not a single event) /// </summary> public class SubTest : IEquatable<SubTest> { public SubTest(string name, Action eventGenerator, Action<Event> eventValidator) { Name = name; EventGenerator = eventGenerator; EventValidator = eventValidator; } /// <summary> /// If a single event does not produce a single response (if you expect additional error messages) /// use this constructor to validate the response. /// </summary> public SubTest(string name, Action eventGenerator, Action<List<Event>> eventListValidator) { Name = name; EventGenerator = eventGenerator; EventListValidator = eventListValidator; } // This action cause the eventSource to emit an event (it is the test) public Action EventGenerator { get; private set; } // This action is given the resulting event and should Assert that it is correct public Action<Event> EventValidator { get; private set; } public Action<List<Event>> EventListValidator { get; private set; } public string Name { get; private set; } public bool Equals(SubTest other) { return Name == other.Name; } public override string ToString() { return Name; } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TEST_EXCEPTIONS using System; using System.IO; using System.Text; namespace Microsoft.Zelig.Test { public class Write : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } //TODO Test with position longer then length public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; result |= Assert.CheckFailed( InvalidCases( ) ); result |= Assert.CheckFailed( VanillaWrite_Dynamic_Ctor( ) ); result |= Assert.CheckFailed( VanillaWrite_Static_Ctor( ) ); result |= Assert.CheckFailed( ShiftBuffer( ) ); result |= Assert.CheckFailed( BoundaryCheck( ) ); return result; } #region Local Helper methods private bool TestWrite(MemoryStream ms, int length) { return TestWrite(ms, length, length, 0); } private bool TestWrite(MemoryStream ms, int length, long ExpectedLength) { return TestWrite(ms, length, length, 0, ExpectedLength); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset) { return TestWrite(ms, BufferLength, BytesToWrite, Offset, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength) { bool result = true; long startLength = ms.Position; long nextbyte = startLength % 256; byte[] byteBuffer = new byte[BufferLength]; for (int i = Offset; i < (Offset + BytesToWrite); i++) { byteBuffer[i] = (byte)nextbyte; // Reset if wraps past 255 if (++nextbyte > 255) nextbyte = 0; } ms.Write(byteBuffer, Offset, BytesToWrite); ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expected final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public TestResult InvalidCases() { MemoryStream fs = new MemoryStream(); byte[] writebuff = new byte[1024]; TestResult result = TestResult.Pass; try { try { Log.Comment("Write to null buffer"); fs.Write(null, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentNullException"); } catch (ArgumentNullException) { /* pass case */ } try { Log.Comment("Write to negative offset"); fs.Write(writebuff, -1, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } try { Log.Comment("Write to out of range offset"); fs.Write(writebuff, writebuff.Length + 1, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ArgumentException"); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Write negative count"); fs.Write(writebuff, 0, -1); result = TestResult.Fail; // previous Bug # 21669 Log.Exception("Expected ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { /* pass case */ } try { Log.Comment("Write count larger then buffer"); fs.Write(writebuff, 0, writebuff.Length + 1); result = TestResult.Fail; Log.Exception("Expected ArgumentException"); } catch (ArgumentException) { /* pass case */ } try { Log.Comment("Write closed stream"); fs.Close(); fs.Write(writebuff, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } try { Log.Comment("Write disposed stream"); fs = new MemoryStream(); fs.Dispose(); fs.Write(writebuff, 0, writebuff.Length); result = TestResult.Fail; Log.Exception("Expected ObjectDisposedException"); } catch (ObjectDisposedException) { /* pass case */ } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public TestResult VanillaWrite_Dynamic_Ctor() { TestResult result = TestResult.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256)) result = TestResult.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100)) result = TestResult.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0)) result = TestResult.Fail; Log.Comment("Write end of buffer"); if (!TestWrite(ms, 1000, 900, 100)) result = TestResult.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int read = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read)); if (test != testResult) { result = TestResult.Fail; Log.Comment("Expected: " + test + ", but got: " + testResult); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult VanillaWrite_Static_Ctor() { TestResult result = TestResult.Pass; try { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256, 1024)) result = TestResult.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100, 1024)) result = TestResult.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0, 1024)) result = TestResult.Fail; #if TEST_EXCEPTIONS Log.Comment("Write past end of buffer"); try { TestWrite(ms, 50, 1024); result = TestResult.Fail; Log.Exception("Expected NotSupportedException"); } catch (NotSupportedException) { /* pass case */ } #endif Log.Comment("Verify failed Write did not move position"); if (ms.Position != 1000) { result = TestResult.Fail; Log.Comment("Expected position to be 1000, but it is " + ms.Position); } Log.Comment("Write final 24 bytes of static buffer"); if (!TestWrite(ms, 24)) result = TestResult.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int read = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read)); if (test != testResult) { result = TestResult.Fail; Log.Comment("Expected: " + test + ", but got: " + testResult); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult ShiftBuffer() { TestResult result = TestResult.Pass; try { int bufSize; int iCountErrors = 0; for (int i = 1; i < 10; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); //we'll read till one before the last since these should be shifted by 1 for (int j = 0; j < ms.Length - 1; ++j) { int bit = ms.ReadByte(); if (bit != j + 1) { ++iCountErrors; Log.Exception("Err_8324t! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } //last bit should be the same if (ms.ReadByte() != i - 1) { ++iCountErrors; Log.Exception("Err_32947gs! Last bit is not correct Check VSWhdibey #458551"); } } //Buffer sizes of 9 (10 here since we shift by 1) and above doesn't have the above 'optimization' problem for (int i = 10; i < 64; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); for (int j = 0; j < ms.Length; ++j) { int bit = ms.ReadByte(); if (j != ms.Length - 1) { if (bit != (j + 1)) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } else if (bit != j) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected:" + (j + 1)); } } } if (iCountErrors > 0) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } [TestMethod] public TestResult BoundaryCheck() { TestResult result = TestResult.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { TestWrite(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) result = TestResult.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { result = TestResult.Fail; Log.Exception("Expected Position and Length to be " + i); } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); result = TestResult.Fail; } return result; } #endregion Test Cases } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebChat.Access.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Log2Console.Log; namespace Log2Console.Receiver { [Serializable] [DisplayName("WebSockets")] public class WebSocketsReceiver : BaseReceiver { private string _serverUri = @"wss://localhost:443"; private string _handshakeMsg = string.Empty; private int _bufferSize = 10000; [NonSerialized] private Thread _worker; [NonSerialized] private CancellationToken _cancellationToken; [NonSerialized] private ClientWebSocket _websocketClient; [NonSerialized] private byte[] _buffer; [NonSerialized] private StringBuilder _messageBuilder; [Category("Configuration")] [DisplayName("Server Host")] [DefaultValue("ws://localhost:80")] public string WebSocketServerUri { get { return _serverUri; } set { _serverUri = value; this.Connect(); } } [Category("Configuration")] [DisplayName("Handshake Msg.")] [DefaultValue("")] public string WebsocketHandshakeMsg { get { return _handshakeMsg; } set { _handshakeMsg = value; this.Connect(); } } [Category("Configuration")] [DisplayName("Receive Buffer Size")] public int BufferSize { get { return _bufferSize; } set { _bufferSize = value; this.Connect(); } } #region IReceiver Members [Browsable(false)] public override string SampleClientConfig { get { return "Configuration for log4net:" + Environment.NewLine + "<appender name=\"UdpAppender\" type=\"log4net.Appender.UdpAppender\">" + Environment.NewLine + " <remoteAddress value=\"localhost\" />" + Environment.NewLine + " <remotePort value=\"7071\" />" + Environment.NewLine + " <layout type=\"log4net.Layout.XmlLayoutSchemaLog4j\" />" + Environment.NewLine + "</appender>"; } } public override void Initialize() { if ((_worker != null) && _worker.IsAlive) return; Connect(); // We need a working thread _worker = new Thread(Start); _worker.IsBackground = true; _worker.Start(); } private void Connect() { try { if (this._websocketClient != null) { this.Disconnect(); } this._buffer = new byte[this._bufferSize]; this._messageBuilder = new StringBuilder(); this._websocketClient = new ClientWebSocket(); this._cancellationToken = new CancellationToken(); _websocketClient .ConnectAsync(new Uri(this._serverUri), this._cancellationToken) .ContinueWith(WssAuthenticate, this._cancellationToken); } catch (Exception ex) { this._websocketClient = null; Console.WriteLine(ex); } } private void WssAuthenticate(Task obj) { if (!string.IsNullOrEmpty(_handshakeMsg)) { ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(_handshakeMsg)); _websocketClient .SendAsync(buffer, WebSocketMessageType.Text, true, this._cancellationToken) .ContinueWith(AuthenticationComplete, this._cancellationToken); } } private void AuthenticationComplete(Task obj) { // ignore it } public override void Terminate() { Disconnect(); if ((_worker != null) && _worker.IsAlive) _worker.Abort(); _worker = null; } private void Disconnect() { try { if (this._websocketClient != null) { this._websocketClient.Abort(); this._websocketClient.Dispose(); this._websocketClient = null; } } catch (Exception ex) { this._websocketClient = null; Console.WriteLine(ex); } } #endregion public void Clear() { } private void Start() { ArraySegment<byte> buffer = new ArraySegment<byte>(this._buffer); var lastState = this._websocketClient?.State; while (true) { try { if (this._websocketClient != null && lastState != this._websocketClient.State) { this.NotifyWebSocketStateChange(this._websocketClient.State); } lastState = this._websocketClient?.State; if (this._websocketClient == null || this._websocketClient.State != WebSocketState.Open || Notifiable == null) { Thread.Sleep(150); // don't let it throttle so badly continue; } this._websocketClient.ReceiveAsync(buffer, this._cancellationToken) .ContinueWith(OnBufferReceived, _cancellationToken) .Wait(this._cancellationToken); } catch (Exception ex) { Console.WriteLine(ex); return; } } } private void OnBufferReceived(Task<WebSocketReceiveResult> obj) { if (obj.IsCompleted) { var loggingEvent = Encoding.UTF8.GetString(this._buffer); this._messageBuilder.Append(loggingEvent); Console.WriteLine(loggingEvent); if (obj.Result.EndOfMessage) { var logMsg = ReceiverUtils.ParseLog4JXmlLogEvent(loggingEvent, "wssLogger"); logMsg.Level = LogLevels.Instance[LogLevel.Debug]; var loggerName = this._serverUri.Replace("wss://", "wss-").Replace(":", "-").Replace(".", "-"); logMsg.RootLoggerName = loggerName; logMsg.LoggerName = $"{loggerName}_{logMsg.LoggerName}"; Notifiable.Notify(logMsg); this._messageBuilder.Clear(); } } } private void NotifyWebSocketStateChange(WebSocketState state) { var logMsg = ReceiverUtils.ParseLog4JXmlLogEvent($"WebSocket state changed: {state}", "wssLogger"); logMsg.Level = LogLevels.Instance[LogLevel.Info]; var loggerName = this._serverUri.Replace("wss://", "wss-").Replace(":", "-").Replace(".", "-"); logMsg.RootLoggerName = loggerName; logMsg.LoggerName = $"{loggerName}_{logMsg.LoggerName}"; Notifiable.Notify(logMsg); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Threading.Tasks; using System.Web; using ASC.Common.Data.AdoProxy; using ASC.Common.Data.Sql; using ASC.Common.Logging; using ASC.Common.Web; namespace ASC.Common.Data { public class DbManager : IDbManager { private readonly ILog logger = LogManager.GetLogger("ASC.SQL"); private readonly ProxyContext proxyContext; private DbCommand command; private ISqlDialect dialect; private volatile bool disposed; private readonly int? commandTimeout; private DbCommand Command { get { CheckDispose(); if (command == null) { command = OpenConnection().CreateCommand(); } if (command.Connection.State == ConnectionState.Closed || command.Connection.State == ConnectionState.Broken) { command = OpenConnection().CreateCommand(); } if (commandTimeout.HasValue) { command.CommandTimeout = commandTimeout.Value; } return command; } } public string DatabaseId { get; private set; } public bool InTransaction { get { return Command.Transaction != null; } } public DbConnection Connection { get { return Command.Connection; } } private DbManager(string databaseId, int? commandTimeout = null) { if (databaseId == null) throw new ArgumentNullException("databaseId"); DatabaseId = databaseId; if (logger.IsDebugEnabled) { proxyContext = new ProxyContext(AdoProxyExecutedEventHandler); } if (commandTimeout.HasValue) { this.commandTimeout = commandTimeout; } } #region IDisposable Members public void Dispose() { lock (this) { if (disposed) return; disposed = true; if (command != null) { if (command.Connection != null) command.Connection.Dispose(); command.Dispose(); command = null; } } } #endregion public static IDbManager FromHttpContext(string databaseId, int? commandTimeout = null) { if (HttpContext.Current != null) { var dbManager = DisposableHttpContext.Current[databaseId] as DbManager; if (dbManager == null || dbManager.disposed) { var localDbManager = new DbManager(databaseId, commandTimeout); var dbManagerAdapter = new DbManagerProxy(localDbManager); DisposableHttpContext.Current[databaseId] = localDbManager; return dbManagerAdapter; } return new DbManagerProxy(dbManager); } return new DbManager(databaseId, commandTimeout); } private DbConnection OpenConnection() { var connection = GetConnection(); connection.Open(); return connection; } private DbConnection GetConnection() { CheckDispose(); var connection = DbRegistry.CreateDbConnection(DatabaseId); if (proxyContext != null) { connection = new DbConnectionProxy(connection, proxyContext); } return connection; } public IDbTransaction BeginTransaction() { if (InTransaction) throw new InvalidOperationException("Transaction already open."); Command.Transaction = Command.Connection.BeginTransaction(); var tx = new DbTransaction(Command.Transaction); tx.Unavailable += TransactionUnavailable; return tx; } public IDbTransaction BeginTransaction(IsolationLevel il) { if (InTransaction) throw new InvalidOperationException("Transaction already open."); il = GetDialect().GetSupportedIsolationLevel(il); Command.Transaction = Command.Connection.BeginTransaction(il); var tx = new DbTransaction(Command.Transaction); tx.Unavailable += TransactionUnavailable; return tx; } public IDbTransaction BeginTransaction(bool nestedIfAlreadyOpen) { return nestedIfAlreadyOpen && InTransaction ? new DbNestedTransaction(Command.Transaction) : BeginTransaction(); } public List<object[]> ExecuteList(string sql, params object[] parameters) { return Command.ExecuteList(sql, parameters); } public Task<List<object[]>> ExecuteListAsync(string sql, params object[] parameters) { return Command.ExecuteListAsync(sql, parameters); } public List<object[]> ExecuteList(ISqlInstruction sql) { return Command.ExecuteList(sql, GetDialect()); } public Task<List<object[]>> ExecuteListAsync(ISqlInstruction sql) { return Command.ExecuteListAsync(sql, GetDialect()); } public List<T> ExecuteList<T>(ISqlInstruction sql, Converter<IDataRecord, T> converter) { return Command.ExecuteList(sql, GetDialect(), converter); } public T ExecuteScalar<T>(string sql, params object[] parameters) { return Command.ExecuteScalar<T>(sql, parameters); } public T ExecuteScalar<T>(ISqlInstruction sql) { return Command.ExecuteScalar<T>(sql, GetDialect()); } public int ExecuteNonQuery(string sql, params object[] parameters) { return Command.ExecuteNonQuery(sql, parameters); } public Task<int> ExecuteNonQueryAsync(string sql, params object[] parameters) { return Command.ExecuteNonQueryAsync(sql, parameters); } public int ExecuteNonQuery(ISqlInstruction sql) { return Command.ExecuteNonQuery(sql, GetDialect()); } public int ExecuteBatch(IEnumerable<ISqlInstruction> batch) { if (batch == null) throw new ArgumentNullException("batch"); var affected = 0; using (var tx = BeginTransaction()) { foreach (var sql in batch) { affected += ExecuteNonQuery(sql); } tx.Commit(); } return affected; } private void TransactionUnavailable(object sender, EventArgs e) { if (Command.Transaction != null) { Command.Transaction = null; } } private void CheckDispose() { if (disposed) throw new ObjectDisposedException(GetType().FullName); } private ISqlDialect GetDialect() { return dialect ?? (dialect = DbRegistry.GetSqlDialect(DatabaseId)); } private void AdoProxyExecutedEventHandler(ExecutedEventArgs a) { logger.DebugWithProps(a.SqlMethod, new KeyValuePair<string, object>("duration", a.Duration.TotalMilliseconds), new KeyValuePair<string, object>("sql", RemoveWhiteSpaces(a.Sql)), new KeyValuePair<string, object>("sqlParams", RemoveWhiteSpaces(a.SqlParameters)), new KeyValuePair<string, object>("sqlThread", a.SqlThread) ); } private string RemoveWhiteSpaces(string str) { return !string.IsNullOrEmpty(str) ? str.Replace(Environment.NewLine, " ").Replace("\n", "").Replace("\r", "").Replace("\t", " ") : string.Empty; } } public class DbManagerProxy : IDbManager { private DbManager dbManager { get; set; } public DbManagerProxy(DbManager dbManager) { this.dbManager = dbManager; } public void Dispose() { if (HttpContext.Current == null) { dbManager.Dispose(); } } public DbConnection Connection { get { return dbManager.Connection; } } public string DatabaseId { get { return dbManager.DatabaseId; } } public bool InTransaction { get { return dbManager.InTransaction; } } public IDbTransaction BeginTransaction() { return dbManager.BeginTransaction(); } public IDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return dbManager.BeginTransaction(isolationLevel); } public IDbTransaction BeginTransaction(bool nestedIfAlreadyOpen) { return dbManager.BeginTransaction(nestedIfAlreadyOpen); } public List<object[]> ExecuteList(string sql, params object[] parameters) { return dbManager.ExecuteList(sql, parameters); } public List<object[]> ExecuteList(ISqlInstruction sql) { return dbManager.ExecuteList(sql); } public Task<List<object[]>> ExecuteListAsync(ISqlInstruction sql) { return dbManager.ExecuteListAsync(sql); } public List<T> ExecuteList<T>(ISqlInstruction sql, Converter<IDataRecord, T> converter) { return dbManager.ExecuteList<T>(sql, converter); } public T ExecuteScalar<T>(string sql, params object[] parameters) { return dbManager.ExecuteScalar<T>(sql, parameters); } public T ExecuteScalar<T>(ISqlInstruction sql) { return dbManager.ExecuteScalar<T>(sql); } public int ExecuteNonQuery(string sql, params object[] parameters) { return dbManager.ExecuteNonQuery(sql, parameters); } public int ExecuteNonQuery(ISqlInstruction sql) { return dbManager.ExecuteNonQuery(sql); } public int ExecuteBatch(IEnumerable<ISqlInstruction> batch) { return dbManager.ExecuteBatch(batch); } public Task<int> ExecuteNonQueryAsync(string sql, params object[] parameters) { return dbManager.ExecuteNonQueryAsync(sql, parameters); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace SimpleSSO.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MyApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Security.Cryptography; using System.Text; using System.Threading; using MindTouch.Tasking; using MindTouch.Text; namespace MindTouch.IO { using Yield = IEnumerator<IYield>; /// <summary> /// A set of static and extension methods to simplify common stream opreations and add <see cref="Result"/> based asynchronous operations /// </summary> public static class StreamUtil { //--- Constants --- /// <summary> /// Common size for internal byte buffer used for Stream operations /// </summary> public const int BUFFER_SIZE = 16 * 1024; private static readonly TimeSpan READ_TIMEOUT = TimeSpan.FromSeconds(30); //--- Class Fields --- private static readonly Random Randomizer = new Random(); private static log4net.ILog _log = log4net.LogManager.GetLogger(typeof(StreamUtil)); //--- Extension Methods --- /// <summary> /// Write a string to <see cref="Stream"/> /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="encoding">Encoding to use to convert the string to bytes</param> /// <param name="text">Regular string or composite format string to write to the <see cref="Stream"/></param> /// <param name="args">An System.Object array containing zero or more objects to format.</param> public static void Write(this Stream stream, Encoding encoding, string text, params object[] args) { const int bufferSize = BUFFER_SIZE / sizeof(char); if(text.Length > bufferSize) { // to avoid a allocating a byte array of greater than 64k, we chunk our string writing here if(args.Length != 0) { text = string.Format(text, args); } var length = text.Length; var idx = 0; var buffer = new char[bufferSize]; while(true) { var size = Math.Min(bufferSize, length - idx); if(size == 0) { break; } text.CopyTo(idx, buffer, 0, size); stream.Write(encoding.GetBytes(buffer, 0, size)); idx += size; } } else { if(args.Length == 0) { stream.Write(encoding.GetBytes(text)); } else { stream.Write(encoding.GetBytes(string.Format(text, args))); } } } /// <summary> /// Write an entire buffer to a <see cref="Stream"/> /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="buffer">An array of bytes to write to the <see cref="Stream"/></param> public static void Write(this Stream stream, byte[] buffer) { stream.Write(buffer, 0, buffer.Length); } /// <summary> /// Determine whether a <see cref="Stream"/> contents are in memory /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <returns><see langword="true"/> If the <see cref="Stream"/> contents are in memory</returns> public static bool IsStreamMemorized(this Stream stream) { return (stream is ChunkedMemoryStream) || (stream is MemoryStream); } /// <summary> /// Asynchronously read from a <see cref="Stream"/> /// </summary> /// <param name="stream">Source <see cref="Stream"/></param> /// <param name="buffer">Byte array to fill from the source</param> /// <param name="offset">Position in buffer to start writing to</param> /// <param name="count">Number of bytes to read from the <see cref="Stream"/></param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes read.</returns> public static Result<int> Read(this Stream stream, byte[] buffer, int offset, int count, Result<int> result) { if(SysUtil.UseAsyncIO) { return Async.From(stream.BeginRead, stream.EndRead, buffer, offset, count, null, result); } return Async.Fork(() => SyncRead_Helper(stream, buffer, offset, count), result); } private static int SyncRead_Helper(Stream stream, byte[] buffer, int offset, int count) { var readTotal = 0; while(count != 0) { var read = stream.Read(buffer, offset, count); if(read <= 0) { return readTotal; } readTotal += read; offset += read; count -= read; } return readTotal; } /// <summary> /// Asynchronously write to a <see cref="Stream"/>. /// </summary> /// <param name="stream">Target <see cref="Stream"/>.</param> /// <param name="buffer">Byte array to write to the target.</param> /// <param name="offset">Position in buffer to start reading from.</param> /// <param name="count">Number of bytes to read from buffer.</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes read.</returns> public static Result Write(this Stream stream, byte[] buffer, int offset, int count, Result result) { if(SysUtil.UseAsyncIO) { return Async.From(stream.BeginWrite, stream.EndWrite, buffer, offset, count, null, result); } return Async.Fork(() => stream.Write(buffer, offset, count), result); } /// <summary> /// Synchronous copying of one stream to another. /// </summary> /// <param name="source">Source <see cref="Stream"/>.</param> /// <param name="target">Target <see cref="Stream"/>.</param> /// <param name="length">Number of bytes to copy from source to target.</param> /// <returns>Actual bytes copied.</returns> public static long CopyTo(this Stream source, Stream target, long length) { var bufferLength = length >= 0 ? length : long.MaxValue; var buffer = new byte[Math.Min(bufferLength, BUFFER_SIZE)]; long total = 0; while(length != 0) { var count = (length >= 0) ? Math.Min(length, buffer.LongLength) : buffer.LongLength; count = source.Read(buffer, 0, (int)count); if(count == 0) { break; } target.Write(buffer, 0, (int)count); total += count; length -= count; } return total; } /// <summary> /// Asynchronous copying of one stream to another. /// </summary> /// <param name="source">Source <see cref="Stream"/>.</param> /// <param name="target">Target <see cref="Stream"/>.</param> /// <param name="length">Number of bytes to copy from source to target.</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes copied.</returns> public static Result<long> CopyTo(this Stream source, Stream target, long length, Result<long> result) { if(!SysUtil.UseAsyncIO) { return Async.Fork(() => CopyTo(source, target, length), result); } // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if((source == Stream.Null) || (length == 0)) { result.Return(0); } else if(source.IsStreamMemorized() && target.IsStreamMemorized()) { // source & target are memory streams; let's do the copy inline as fast as we can result.Return(CopyTo(source, target, length)); } else { // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(CopyTo_Helper, source, target, length, result)); } return result; } private static Yield CopyTo_Helper(Stream source, Stream target, long length, Result<long> result) { byte[] readBuffer = new byte[BUFFER_SIZE]; byte[] writeBuffer = new byte[BUFFER_SIZE]; long total = 0; int zero_read_counter = 0; Result write = null; // NOTE (steveb): we stop when we've read the expected number of bytes and the length was non-negative, // otherwise we stop when we can't read anymore bytes. while(length != 0) { // read first long count = (length >= 0) ? Math.Min(length, readBuffer.LongLength) : readBuffer.LongLength; if(source.IsStreamMemorized()) { count = source.Read(readBuffer, 0, (int)count); // check if we failed to read if(count == 0) { break; } } else { yield return Read(source, readBuffer, 0, (int)count, new Result<int>(READ_TIMEOUT)).Set(v => count = v); // check if we failed to read if(count == 0) { // let's abort after 10 tries to read more data if(++zero_read_counter > 10) { break; } continue; } zero_read_counter = 0; } total += count; length -= count; // swap buffers byte[] tmp = writeBuffer; writeBuffer = readBuffer; readBuffer = tmp; // write second if((target == Stream.Null) || target.IsStreamMemorized()) { target.Write(writeBuffer, 0, (int)count); } else { if(write != null) { yield return write; } write = Write(target, writeBuffer, 0, (int)count, new Result()); } } if(write != null) { yield return write; } // return result result.Return(total); } /// <summary> /// Asynchrounously copy a <see cref="Stream"/> to several targets /// </summary> /// <param name="source">Source <see cref="Stream"/></param> /// <param name="targets">Array of target <see cref="Stream"/> objects</param> /// <param name="length">Number of bytes to copy from source to targets</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for the number of bytes copied to each target.</returns> public static Result<long?[]> CopyTo(this Stream source, Stream[] targets, long length, Result<long?[]> result) { // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if((source == Stream.Null) || (length == 0)) { long?[] totals = new long?[targets.Length]; for(int i = 0; i < totals.Length; ++i) { totals[i] = 0; } result.Return(totals); } else { // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(CopyTo_Helper, source, targets, length, result)); } return result; } private static Yield CopyTo_Helper(Stream source, Stream[] targets, long length, Result<long?[]> result) { byte[] readBuffer = new byte[BUFFER_SIZE]; byte[] writeBuffer = new byte[BUFFER_SIZE]; int zero_read_counter = 0; Result[] writes = new Result[targets.Length]; // initialize totals long?[] totals = new long?[targets.Length]; for(int i = 0; i < totals.Length; ++i) { totals[i] = 0; } // NOTE (steveb): we stop when we've read the expected number of bytes when the length was non-negative, // otherwise we stop when we can't read anymore bytes. while(length != 0) { // read first long count = (length >= 0) ? Math.Min(length, readBuffer.LongLength) : readBuffer.LongLength; if(source.IsStreamMemorized()) { count = source.Read(readBuffer, 0, (int)count); // check if we failed to read if(count == 0) { break; } } else { yield return Read(source, readBuffer, 0, (int)count, new Result<int>(READ_TIMEOUT)).Set(v => count = v); // check if we failed to read if(count == 0) { // let's abort after 10 tries to read more data if(++zero_read_counter > 10) { break; } continue; } zero_read_counter = 0; } length -= count; // swap buffers byte[] tmp = writeBuffer; writeBuffer = readBuffer; readBuffer = tmp; // wait for pending writes to complete for(int i = 0; i < writes.Length; ++i) { if(writes[i] != null) { yield return writes[i].Catch(); if(writes[i].HasException) { totals[i] = null; } writes[i] = null; } } // write second for(int i = 0; i < targets.Length; ++i) { // check that write hasn't had an error yet if(totals[i] != null) { totals[i] += count; Stream target = targets[i]; if((target == Stream.Null) || target.IsStreamMemorized()) { target.Write(writeBuffer, 0, (int)count); } else { writes[i] = Write(target, writeBuffer, 0, (int)count, new Result()); } } } } // wait for pending writes to complete for(int i = 0; i < writes.Length; ++i) { if(writes[i] != null) { yield return writes[i].Catch(); if(writes[i].HasException) { totals[i] = null; } } } // return result result.Return(totals); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static void CopyToFile(this Stream stream, string filename, long length) { FileStream file = null; try { using(file = File.Create(filename)) { CopyTo(stream, file, length); } } catch { // check if we created a file, if so delete it if(file != null) { try { File.Delete(filename); } catch { } } throw; } finally { // make sure the source stream is closed try { stream.Close(); } catch { } } } /// <summary> /// Asychronously Pad a stream with a sequence of bytes /// </summary> /// <param name="stream">Target <see cref="Stream"/></param> /// <param name="count">Number of bytes to pad</param> /// <param name="value">Byte value to use for padding</param> /// <param name="result">The <see cref="Result"/> instance to be returned by the call.</param> /// <returns>Synchronization handle for completion of padding action.</returns> public static Result Pad(this Stream stream, long count, byte value, Result result) { if(count < 0) { throw new ArgumentException("count must be non-negative"); } // NOTE (steveb): intermediary copy steps already have a timeout operation, no need to limit the duration of the entire copy operation if(count == 0) { result.Return(); } else { // initialize buffer so we can write in large chunks if need be byte[] bytes = new byte[(int)Math.Min(4096L, count)]; for(int i = 0; i < bytes.Length; ++i) { bytes[i] = value; } // use new task environment so we don't copy the task state over and over again TaskEnv.ExecuteNew(() => Coroutine.Invoke(Pad_Helper, stream, count, bytes, result)); } return result; } private static Yield Pad_Helper(Stream stream, long count, byte[] bytes, Result result) { // write until we reach zero while(count > 0) { var byteCount = (int)Math.Min(count, bytes.LongLength); yield return Write(stream, bytes, 0, byteCount, new Result()); count -= byteCount; } result.Return(); } /// <summary> /// Compute the MD5 hash. /// </summary> /// <param name="stream">Stream to hash.</param> /// <returns>MD5 hash.</returns> public static byte[] ComputeHash(this Stream stream) { return MD5.Create().ComputeHash(stream); } /// <summary> /// Compute the MD5 hash string. /// </summary> /// <param name="stream">Stream to hash.</param> /// <returns>MD5 hash string.</returns> public static string ComputeHashString(this Stream stream) { return StringUtil.HexStringFromBytes(ComputeHash(stream)); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static byte[] ReadBytes(this Stream source, long length) { var result = new MemoryStream(); CopyTo(source, result, length); return result.ToArray(); } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Result<MemoryStream> ToMemoryStream(this Stream stream, long length, Result<MemoryStream> result) { MemoryStream copy; if(stream is MemoryStream) { var mem = (MemoryStream)stream; copy = new MemoryStream(mem.GetBuffer(), 0, (int)mem.Length, false, true); result.Return(copy); } else { copy = new MemoryStream(); stream.CopyTo(copy, length, new Result<long>(TimeSpan.MaxValue)).WhenDone( v => { copy.Position = 0; result.Return(copy); }, result.Throw ); } return result; } #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Result<ChunkedMemoryStream> ToChunkedMemoryStream(this Stream stream, long length, Result<ChunkedMemoryStream> result) { var copy = new ChunkedMemoryStream(); stream.CopyTo(copy, length, new Result<long>(TimeSpan.MaxValue)).WhenDone( v => { copy.Position = 0; result.Return(copy); }, result.Throw ); return result; } /// <summary> /// Detect stream encoding. /// </summary> /// <param name="stream">Stream to examine</param> /// <returns>Encoding type detected or null</returns> public static Encoding DetectEncoding(this Stream stream) { return new BOMEncodingDetector().Detect(stream) // TODO (steveb): add <meta> tag detector here ?? new CharacterEncodingDetector().Detect(stream); } //--- Class Methods --- #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif /// <summary> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </summary> public static Stream[] DupStream(Stream stream, long length, int copies) { if(copies < 2) { throw new ArgumentException("copies"); } Stream[] result = new Stream[copies]; // make master stream MemoryStream master = stream.ToMemoryStream(length, new Result<MemoryStream>()).Wait(); result[0] = master; for(int i = 1; i < copies; i++) { result[i] = new MemoryStream(master.GetBuffer(), 0, (int)master.Length, false, true); } return result; } /// <summary> /// Try to open a file for exclusive read/write access /// </summary> /// <param name="filename">Path to file</param> /// <returns>A <see cref="Stream"/> for the opened file, or <see langword="null"/> on failure to open the file.</returns> public static Stream FileOpenExclusive(string filename) { for(int attempts = 0; attempts < 10; ++attempts) { try { return File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch(IOException e) { _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts); } catch(UnauthorizedAccessException e) { _log.TraceExceptionMethodCall(e, "FileOpenExclusive", filename, attempts); } Thread.Sleep((attempts + 1) * Randomizer.Next(100)); } return null; } /// <summary> /// Create a pipe /// </summary> /// <param name="writer">The writer endpoint of the pipe</param> /// <param name="reader">The reader endpoint of the pipe</param> public static void CreatePipe(out Stream writer, out Stream reader) { PipeStreamBuffer buffer = new PipeStreamBuffer(); writer = new PipeStreamWriter(buffer); reader = new PipeStreamReader(buffer); } /// <summary> /// Create a pipe /// </summary> /// <param name="size">The size of the pipe buffer</param> /// <param name="writer">The writer endpoint of the pipe</param> /// <param name="reader">The reader endpoint of the pipe</param> public static void CreatePipe(int size, out Stream writer, out Stream reader) { PipeStreamBuffer buffer = new PipeStreamBuffer(size); writer = new PipeStreamWriter(buffer); reader = new PipeStreamReader(buffer); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedZonesClientSnippets { /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetZoneRequest, CallSettings) // Create client ZonesClient zonesClient = ZonesClient.Create(); // Initialize request argument(s) GetZoneRequest request = new GetZoneRequest { Zone = "", Project = "", }; // Make the request Zone response = zonesClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetZoneRequest, CallSettings) // Additional: GetAsync(GetZoneRequest, CancellationToken) // Create client ZonesClient zonesClient = await ZonesClient.CreateAsync(); // Initialize request argument(s) GetZoneRequest request = new GetZoneRequest { Zone = "", Project = "", }; // Make the request Zone response = await zonesClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client ZonesClient zonesClient = ZonesClient.Create(); // Initialize request argument(s) string project = ""; string zone = ""; // Make the request Zone response = zonesClient.Get(project, zone); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client ZonesClient zonesClient = await ZonesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string zone = ""; // Make the request Zone response = await zonesClient.GetAsync(project, zone); // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListZonesRequest, CallSettings) // Create client ZonesClient zonesClient = ZonesClient.Create(); // Initialize request argument(s) ListZonesRequest request = new ListZonesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<ZoneList, Zone> response = zonesClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Zone item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ZoneList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Zone item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Zone> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Zone item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListZonesRequest, CallSettings) // Create client ZonesClient zonesClient = await ZonesClient.CreateAsync(); // Initialize request argument(s) ListZonesRequest request = new ListZonesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<ZoneList, Zone> response = zonesClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Zone item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ZoneList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Zone item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Zone> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Zone item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client ZonesClient zonesClient = ZonesClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<ZoneList, Zone> response = zonesClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (Zone item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ZoneList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Zone item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Zone> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Zone item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client ZonesClient zonesClient = await ZonesClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<ZoneList, Zone> response = zonesClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Zone item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ZoneList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Zone item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Zone> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Zone item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
// 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; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using static System.Buffers.Binary.BinaryPrimitives; using System.Text; using System.Reflection; namespace System { public static class TestHelpers { public static void Validate<T>(this Span<T> span, params T[] expected) where T : struct, IEquatable<T> { Assert.True(span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this Span<T> span, params T[] expected) where T : class { Assert.Equal(span.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = span[i]; Assert.Same(expected[i], actual); } T ignore; AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]); } public static unsafe void ValidateNonNullEmpty<T>(this Span<T> span) { Assert.True(span.IsEmpty); // Validate that empty Span is not normalized to null Assert.True(Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)) != null); } public delegate void AssertThrowsAction<T>(Span<T> span); // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along. public static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E : Exception { try { action(span); Assert.False(true, "Expected exception: " + typeof(E).GetType()); } catch (E) { } catch (Exception wrongException) { Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType()); } } // // The innocent looking construct: // // Assert.Throws<E>( () => new Span() ); // // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...) // // The workaround is to code it like this: // // Assert.Throws<E>( () => new Span().DontBox() ); // // which turns the lambda return type back to "void" and eliminates the troublesome box instruction. // public static void DontBox<T>(this Span<T> span) { // This space intentionally left blank. } public static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected) where T : struct, IEquatable<T> { Assert.True(span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this ReadOnlySpan<T> span, params T[] expected) where T : class { Assert.Equal(span.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = span[i]; Assert.Same(expected[i], actual); } T ignore; AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]); } public static unsafe void ValidateNonNullEmpty<T>(this ReadOnlySpan<T> span) { Assert.True(span.IsEmpty); // Validate that empty Span is not normalized to null Assert.True(Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)) != null); } public delegate void AssertThrowsActionReadOnly<T>(ReadOnlySpan<T> span); // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along. public static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsActionReadOnly<T> action) where E : Exception { try { action(span); Assert.False(true, "Expected exception: " + typeof(E).GetType()); } catch (E) { } catch (Exception wrongException) { Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType()); } } // // The innocent looking construct: // // Assert.Throws<E>( () => new Span() ); // // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...) // // The workaround is to code it like this: // // Assert.Throws<E>( () => new Span().DontBox() ); // // which turns the lambda return type back to "void" and eliminates the troublesome box instruction. // public static void DontBox<T>(this ReadOnlySpan<T> span) { // This space intentionally left blank. } public static void Validate<T>(this Memory<T> memory, params T[] expected) where T : IEquatable<T> { Assert.True(memory.Span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this Memory<T> memory, params T[] expected) where T : class { T[] bufferArray = memory.ToArray(); Assert.Equal(memory.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = bufferArray[i]; Assert.Same(expected[i], actual); } } public static void Validate<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : IEquatable<T> { Assert.True(memory.Span.SequenceEqual(expected)); } public static void ValidateReferenceType<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : class { T[] bufferArray = memory.ToArray(); Assert.Equal(memory.Length, expected.Length); for (int i = 0; i < expected.Length; i++) { T actual = bufferArray[i]; Assert.Same(expected[i], actual); } } public static void Validate<T>(Span<byte> span, T value) where T : struct { T read = MemoryMarshal.Read<T>(span); Assert.Equal(value, read); span.Clear(); } public static TestStructExplicit s_testExplicitStruct = new TestStructExplicit { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; public static Span<byte> GetSpanBE() { Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStructExplicit>()]; WriteInt16BigEndian(spanBE, s_testExplicitStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), s_testExplicitStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), s_testExplicitStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), s_testExplicitStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), s_testExplicitStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), s_testExplicitStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), s_testExplicitStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), s_testExplicitStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), s_testExplicitStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), s_testExplicitStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), s_testExplicitStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), s_testExplicitStruct.UL1); Assert.Equal(56, spanBE.Length); return spanBE; } public static Span<byte> GetSpanLE() { Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStructExplicit>()]; WriteInt16LittleEndian(spanLE, s_testExplicitStruct.S0); WriteInt32LittleEndian(spanLE.Slice(2), s_testExplicitStruct.I0); WriteInt64LittleEndian(spanLE.Slice(6), s_testExplicitStruct.L0); WriteUInt16LittleEndian(spanLE.Slice(14), s_testExplicitStruct.US0); WriteUInt32LittleEndian(spanLE.Slice(16), s_testExplicitStruct.UI0); WriteUInt64LittleEndian(spanLE.Slice(20), s_testExplicitStruct.UL0); WriteInt16LittleEndian(spanLE.Slice(28), s_testExplicitStruct.S1); WriteInt32LittleEndian(spanLE.Slice(30), s_testExplicitStruct.I1); WriteInt64LittleEndian(spanLE.Slice(34), s_testExplicitStruct.L1); WriteUInt16LittleEndian(spanLE.Slice(42), s_testExplicitStruct.US1); WriteUInt32LittleEndian(spanLE.Slice(44), s_testExplicitStruct.UI1); WriteUInt64LittleEndian(spanLE.Slice(48), s_testExplicitStruct.UL1); Assert.Equal(56, spanLE.Length); return spanLE; } public static string BuildString(int length, int seed) { Random rnd = new Random(seed); var builder = new StringBuilder(); for (int i = 0; i < length; i++) { builder.Append((char)rnd.Next(65, 91)); } return builder.ToString(); } [StructLayout(LayoutKind.Explicit)] public struct TestStructExplicit { [FieldOffset(0)] public short S0; [FieldOffset(2)] public int I0; [FieldOffset(6)] public long L0; [FieldOffset(14)] public ushort US0; [FieldOffset(16)] public uint UI0; [FieldOffset(20)] public ulong UL0; [FieldOffset(28)] public short S1; [FieldOffset(30)] public int I1; [FieldOffset(34)] public long L1; [FieldOffset(42)] public ushort US1; [FieldOffset(44)] public uint UI1; [FieldOffset(48)] public ulong UL1; } [StructLayout(LayoutKind.Sequential)] public sealed class TestClass { private double _d; public char C0; public char C1; public char C2; public char C3; public char C4; } [StructLayout(LayoutKind.Sequential)] public struct TestValueTypeWithReference { public int I; public string S; } #pragma warning disable 0649 //Field 'SpanTests.InnerStruct.J' is never assigned to, and will always have its default value 0 internal struct StructWithReferences { public int I; public InnerStruct Inner; } internal struct InnerStruct { public int J; public object O; } #pragma warning restore 0649 //Field 'SpanTests.InnerStruct.J' is never assigned to, and will always have its default value 0 public enum TestEnum { E0, E1, E2, E3, E4, } [MethodImpl(MethodImplOptions.NoInlining)] public static void DoNotIgnore<T>(T value, int consumed) { } // // { text, start, length } triplets. A "-1" in start or length means "test the overload that doesn't have that parameter." // public static IEnumerable<object[]> StringSliceTestData { get { foreach (string text in new string[] { string.Empty, "012" }) { yield return new object[] { text, -1, -1 }; for (int start = 0; start <= text.Length; start++) { yield return new object[] { text, start, -1 }; for (int length = 0; length <= text.Length - start; length++) { yield return new object[] { text, start, length }; } } } } } public static IEnumerable<object[]> StringSlice2ArgTestOutOfRangeData { get { foreach (string text in new string[] { string.Empty, "012" }) { yield return new object[] { text, -1 }; yield return new object[] { text, int.MinValue }; yield return new object[] { text, text.Length + 1 }; yield return new object[] { text, int.MaxValue }; } } } public static IEnumerable<object[]> StringSlice3ArgTestOutOfRangeData { get { foreach (string text in new string[] { string.Empty, "012" }) { yield return new object[] { text, -1, 0 }; yield return new object[] { text, int.MinValue, 0 }; yield return new object[] { text, text.Length + 1, 0 }; yield return new object[] { text, int.MaxValue, 0 }; yield return new object[] { text, 0, -1 }; yield return new object[] { text, 0, int.MinValue }; yield return new object[] { text, 0, text.Length + 1 }; yield return new object[] { text, 0, int.MaxValue }; yield return new object[] { text, 1, text.Length }; yield return new object[] { text, 1, int.MaxValue }; yield return new object[] { text, text.Length - 1, 2 }; yield return new object[] { text, text.Length - 1, int.MaxValue }; yield return new object[] { text, text.Length, 1 }; yield return new object[] { text, text.Length, int.MaxValue }; } } } /// <summary>Creates a <see cref="Memory{T}"/> with the specified values in its backing field.</summary> public static Memory<T> DangerousCreateMemory<T>(object obj, int offset, int length) { Memory<T> mem = default; object boxedMemory = mem; typeof(Memory<T>).GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, obj); typeof(Memory<T>).GetField("_index", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, offset); typeof(Memory<T>).GetField("_length", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, length); return (Memory<T>)boxedMemory; } /// <summary>Creates a <see cref="ReadOnlyMemory{T}"/> with the specified values in its backing field.</summary> public static ReadOnlyMemory<T> DangerousCreateReadOnlyMemory<T>(object obj, int offset, int length) => DangerousCreateMemory<T>(obj, offset, length); public static TheoryData<string[], bool> ContainsNullData => new TheoryData<string[], bool>() { { new string[] { "1", null, "2" }, true}, { new string[] { "1", "3", "2" }, false}, { null, false}, { new string[] { "1", null, null }, true}, { new string[] { null, null, null }, true}, }; public static TheoryData<string[], string[], bool> SequenceEqualsNullData => new TheoryData<string[], string[], bool>() { { new string[] { "1", null, "2" }, new string[] { "1", null, "2" } , true}, { new string[] { "1", null, "2" }, new string[] { "1", "3", "2" } , false}, { new string[] { "1", null, "2" }, new string[] { null, "3", "2" } , false}, { new string[] { "1", null, "2" }, new string[] { null } , false}, { new string[] { "1", null, "2" }, null , false}, { new string[] { null, "2", "1" }, new string[] { null, "2" } , false}, { null, new string[] { null }, false}, { null, null , true}, { null, new string[] { "1", "3", "2" } , false}, { null, new string[] { "1", null, "2" } , false}, { new string[] { "1", null, null }, new string[] { "1", null, null }, true}, { new string[] { null, null, null }, new string[] { null, null, null }, true}, }; public static TheoryData<string[], int> IndexOfNullData => new TheoryData<string[], int>() { { new string[] { "1", null, "2" }, 1}, { new string[] { "1", "3", "2" }, -1}, { null, -1}, { new string[] { "1", null, null }, 1}, { new string[] { null, null, null }, 0}, }; public static TheoryData<string[], string[], int> IndexOfNullSequenceData => new TheoryData<string[], string[], int>() { { new string[] { "1", null, "2" }, new string[] { "1", null, "2" }, 0}, { new string[] { "1", null, "2" }, new string[] { null }, 1}, { new string[] { "1", null, "2" }, (string[])null, 0}, { new string[] { "1", "3", "2" }, new string[] { "1", null, "2" }, -1}, { new string[] { "1", "3", "2" }, new string[] { null }, -1}, { new string[] { "1", "3", "2" }, (string[])null, 0}, { null, new string[] { "1", null, "2" }, -1}, { new string[] { "1", null, null }, new string[] { null, null, "2" }, -1}, { new string[] { null, null, null }, new string[] { null, null }, 0}, }; public static TheoryData<string[], string[], int> IndexOfAnyNullSequenceData => new TheoryData<string[], string[], int>() { { new string[] { "1", null, "2" }, new string[] { "1", null, "2" }, 0}, { new string[] { "1", null, "2" }, new string[] { null, null }, 1}, { new string[] { "1", null, "2" }, new string[] { "3", null }, 1}, { new string[] { "1", null, "2" }, new string[] { "1", "2" }, 0}, { new string[] { "1", null, "2" }, new string[] { "3", "4" }, -1}, { new string[] { null, null, "2" }, new string[] { "3", null }, 0}, { new string[] { null, null, "2" }, new string[] { null, "1" }, 0}, { new string[] { null, null, "2" }, new string[] { null, "1" }, 0}, { new string[] { "1", "3", "2" }, new string[] { "1", null, "2" }, 0}, { new string[] { "1", "3", "2" }, new string[] { null, null }, -1}, { new string[] { "1", "3", "2" }, new string[] { null, "1" }, 0}, { null, new string[] { "1", null, "2" }, -1}, { new string[] { "1", null, null }, new string[] { null, null, "2" }, 1}, { new string[] { null, null, null }, new string[] { null, null }, 0}, { new string[] { "1", "3", "2" }, null, -1}, { new string[] { "1", null, "2" }, null, -1}, }; public static TheoryData<string[], int> LastIndexOfNullData => new TheoryData<string[], int>() { { new string[] { "1", null, "2" }, 1}, { new string[] { "1", "3", "2" }, -1}, { null, -1}, { new string[] { "1", null, null }, 2}, { new string[] { null, null, null }, 2}, { new string[] { null, null, "3" }, 1}, }; public static TheoryData<string[], string[], int> LastIndexOfNullSequenceData => new TheoryData<string[], string[], int>() { { new string[] { "1", null, "2" }, new string[] { "1", null, "2" }, 0}, { new string[] { "1", null, "2" }, new string[] { null }, 1}, { new string[] { "1", null, "2" }, (string[])null, 0}, { new string[] { "1", "3", "1" }, new string[] { "1", null, "2" }, -1}, { new string[] { "1", "3", "1" }, new string[] { "1" }, 2}, { new string[] { "1", "3", "1" }, new string[] { null }, -1}, { new string[] { "1", "3", "1" }, (string[])null, 0}, { null, new string[] { "1", null, "2" }, -1}, { new string[] { "1", null, null }, new string[] { null, null, "2" }, -1}, { new string[] { null, null, null }, new string[] { null, null }, 1}, }; public static TheoryData<string[], string[], int> LastIndexOfAnyNullSequenceData => new TheoryData<string[], string[], int>() { { new string[] { "1", null, "2" }, new string[] { "1", null, "3" }, 1}, { new string[] { "1", null, "2" }, new string[] { null, null }, 1}, { new string[] { "1", null, "2" }, new string[] { "3", "4" }, -1}, { new string[] { "1", null, "2" }, new string[] { "3", null }, 1}, { new string[] { "1", null, "2" }, new string[] { "1", null }, 1}, { new string[] { "1", null, "2" }, new string[] { null, null }, 1}, { new string[] { "1", null, "2" }, new string[] { "1", "2" }, 2}, { null, new string[] { "1", null, "2" }, -1}, { new string[] { null, null, "2" }, new string[] { "3", null }, 1}, { new string[] { null, null, "2" }, new string[] { null, "1" }, 1}, { new string[] { null, null, "2" }, new string[] { null, "1" }, 1}, { new string[] { "1", "3", "2" }, new string[] { null, "1" }, 0}, { new string[] { "1", "3", "2" }, new string[] { "1", "2", null }, 2}, { new string[] { "1", "3", "2" }, new string[] { null, null }, -1}, { null, new string[] { null, "1" }, -1}, { new string[] { "1", null, null }, new string[] { null, null, "2" }, 2}, { new string[] { null, null, null }, new string[] { null, null }, 2}, { new string[] { "1", null, "2" }, null, -1}, { new string[] { "1", "3", "2" }, null, -1}, }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using AutoMapper.Configuration; namespace AutoMapper { /// <summary> /// Contains cached reflection information for easy retrieval /// </summary> [DebuggerDisplay("{Type}")] public class TypeDetails { public TypeDetails(Type type, ProfileMap config) { Type = type; var membersToMap = MembersToMap(config.ShouldMapProperty, config.ShouldMapField); var publicReadableMembers = GetAllPublicReadableMembers(membersToMap); var publicWritableMembers = GetAllPublicWritableMembers(membersToMap); PublicReadAccessors = BuildPublicReadAccessors(publicReadableMembers); PublicWriteAccessors = BuildPublicAccessors(publicWritableMembers); PublicNoArgMethods = BuildPublicNoArgMethods(); Constructors = type.GetDeclaredConstructors().Where(ci => !ci.IsStatic).ToArray(); PublicNoArgExtensionMethods = BuildPublicNoArgExtensionMethods(config.SourceExtensionMethods); AllMembers = PublicReadAccessors.Concat(PublicNoArgMethods).Concat(PublicNoArgExtensionMethods).ToList(); DestinationMemberNames = AllMembers.Select(mi => new DestinationMemberName { Member = mi, Possibles = PossibleNames(mi.Name, config.Prefixes, config.Postfixes).ToArray() }); } private IEnumerable<string> PossibleNames(string memberName, IEnumerable<string> prefixes, IEnumerable<string> postfixes) { yield return memberName; if (!postfixes.Any()) { foreach (var withoutPrefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Select(prefix => memberName.Substring(prefix.Length))) { yield return withoutPrefix; } yield break; } foreach (var withoutPrefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Select(prefix => memberName.Substring(prefix.Length))) { yield return withoutPrefix; foreach (var s in PostFixes(postfixes, withoutPrefix)) yield return s; } foreach (var s in PostFixes(postfixes, memberName)) yield return s; } private static IEnumerable<string> PostFixes(IEnumerable<string> postfixes, string name) { return postfixes.Where(postfix => name.EndsWith(postfix, StringComparison.OrdinalIgnoreCase)) .Select(postfix => name.Remove(name.Length - postfix.Length)); } private static Func<MemberInfo, bool> MembersToMap(Func<PropertyInfo, bool> shouldMapProperty, Func<FieldInfo, bool> shouldMapField) { return m => { switch (m) { case PropertyInfo property: return !property.IsStatic() && shouldMapProperty(property); case FieldInfo field: return !field.IsStatic && shouldMapField(field); default: throw new ArgumentException("Should be a field or property."); } }; } public struct DestinationMemberName { public MemberInfo Member { get; set; } public string[] Possibles { get; set; } } public Type Type { get; } public IEnumerable<ConstructorInfo> Constructors { get; } public IEnumerable<MemberInfo> PublicReadAccessors { get; } public IEnumerable<MemberInfo> PublicWriteAccessors { get; } public IEnumerable<MethodInfo> PublicNoArgMethods { get; } public IEnumerable<MethodInfo> PublicNoArgExtensionMethods { get; } public IEnumerable<MemberInfo> AllMembers { get; } public IEnumerable<DestinationMemberName> DestinationMemberNames { get; set; } private IEnumerable<MethodInfo> BuildPublicNoArgExtensionMethods(IEnumerable<MethodInfo> sourceExtensionMethodSearch) { var explicitExtensionMethods = sourceExtensionMethodSearch.Where(method => method.GetParameters()[0].ParameterType == Type); var genericInterfaces = Type.GetTypeInfo().ImplementedInterfaces.Where(t => t.IsGenericType()); if (Type.IsInterface() && Type.IsGenericType()) { genericInterfaces = genericInterfaces.Union(new[] { Type }); } return explicitExtensionMethods.Union ( from genericMethod in sourceExtensionMethodSearch where genericMethod.IsGenericMethodDefinition from genericInterface in genericInterfaces let genericInterfaceArguments = genericInterface.GetTypeInfo().GenericTypeArguments where genericMethod.GetGenericArguments().Length == genericInterfaceArguments.Length let methodMatch = genericMethod.MakeGenericMethod(genericInterfaceArguments) where methodMatch.GetParameters()[0].ParameterType.GetTypeInfo().IsAssignableFrom(genericInterface.GetTypeInfo()) select methodMatch ).ToArray(); } private static MemberInfo[] BuildPublicReadAccessors(IEnumerable<MemberInfo> allMembers) { // Multiple types may define the same property (e.g. the class and multiple interfaces) - filter this to one of those properties var filteredMembers = allMembers .OfType<PropertyInfo>() .GroupBy(x => x.Name) // group properties of the same name together .Select(x => x.First()) .Concat(allMembers.Where(x => x is FieldInfo)); // add FieldInfo objects back return filteredMembers.ToArray(); } private static MemberInfo[] BuildPublicAccessors(IEnumerable<MemberInfo> allMembers) { // Multiple types may define the same property (e.g. the class and multiple interfaces) - filter this to one of those properties var filteredMembers = allMembers .OfType<PropertyInfo>() .GroupBy(x => x.Name) // group properties of the same name together .Select(x => x.Any(y => y.CanWrite && y.CanRead) ? // favor the first property that can both read & write - otherwise pick the first one x.First(y => y.CanWrite && y.CanRead) : x.First()) .Where(pi => pi.CanWrite || pi.PropertyType.IsListOrDictionaryType()) //.OfType<MemberInfo>() // cast back to MemberInfo so we can add back FieldInfo objects .Concat(allMembers.Where(x => x is FieldInfo)); // add FieldInfo objects back return filteredMembers.ToArray(); } private IEnumerable<MemberInfo> GetAllPublicReadableMembers(Func<MemberInfo, bool> membersToMap) => GetAllPublicMembers(PropertyReadable, FieldReadable, membersToMap); private IEnumerable<MemberInfo> GetAllPublicWritableMembers(Func<MemberInfo, bool> membersToMap) => GetAllPublicMembers(PropertyWritable, FieldWritable, membersToMap); private static bool PropertyReadable(PropertyInfo propertyInfo) => propertyInfo.CanRead; private static bool FieldReadable(FieldInfo fieldInfo) => true; private static bool PropertyWritable(PropertyInfo propertyInfo) { var propertyIsEnumerable = (typeof(string) != propertyInfo.PropertyType) && typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(propertyInfo.PropertyType.GetTypeInfo()); return propertyInfo.CanWrite || propertyIsEnumerable; } private static bool FieldWritable(FieldInfo fieldInfo) => !fieldInfo.IsInitOnly; private IEnumerable<MemberInfo> GetAllPublicMembers( Func<PropertyInfo, bool> propertyAvailableFor, Func<FieldInfo, bool> fieldAvailableFor, Func<MemberInfo, bool> memberAvailableFor) { var typesToScan = new List<Type>(); for (var t = Type; t != null; t = t.BaseType()) typesToScan.Add(t); if (Type.IsInterface()) typesToScan.AddRange(Type.GetTypeInfo().ImplementedInterfaces); // Scan all types for public properties and fields return typesToScan .Where(x => x != null) // filter out null types (e.g. type.BaseType == null) .SelectMany(x => x.GetDeclaredMembers() .Where(mi => mi.DeclaringType != null && mi.DeclaringType == x) .Where( m => m is FieldInfo && fieldAvailableFor((FieldInfo)m) || m is PropertyInfo && propertyAvailableFor((PropertyInfo)m) && !((PropertyInfo)m).GetIndexParameters().Any()) .Where(memberAvailableFor) ); } private MethodInfo[] BuildPublicNoArgMethods() { return Type.GetAllMethods() .Where(mi => mi.IsPublic && !mi.IsStatic && mi.DeclaringType != typeof(object)) .Where(m => (m.ReturnType != typeof(void)) && (m.GetParameters().Length == 0)) .ToArray(); } } }
// // Copyright (c) 2004-2018 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 System; using System.Globalization; using System.IO; using System.Linq; using Xunit; using NLog.Common; using System.Text; using NLog.Time; using Xunit.Extensions; namespace NLog.UnitTests.Common { public class InternalLoggerTests : NLogTestBase, IDisposable { /// <summary> /// Test the return values of all Is[Level]Enabled() methods. /// </summary> [Fact] public void IsEnabledTests() { // Setup LogLevel to minimum named level. InternalLogger.LogLevel = LogLevel.Trace; Assert.True(InternalLogger.IsTraceEnabled); Assert.True(InternalLogger.IsDebugEnabled); Assert.True(InternalLogger.IsInfoEnabled); Assert.True(InternalLogger.IsWarnEnabled); Assert.True(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Setup LogLevel to maximum named level. InternalLogger.LogLevel = LogLevel.Fatal; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Switch off the internal logging. InternalLogger.LogLevel = LogLevel.Off; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.False(InternalLogger.IsFatalEnabled); } [Fact] public void WriteToStringWriterTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, () => "WWW"); InternalLogger.Log(LogLevel.Error, () => "EEE"); InternalLogger.Log(LogLevel.Fatal, () => "FFF"); InternalLogger.Log(LogLevel.Trace, () => "TTT"); InternalLogger.Log(LogLevel.Debug, () => "DDD"); InternalLogger.Log(LogLevel.Info, () => "III"); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } [Fact] public void WriteToStringWriterWithArgsTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW {0}", 0); InternalLogger.Error("EEE {0}, {1}", 0, 1); InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Debug("DDD {0}, {1}", 0, 1); InternalLogger.Info("III {0}", 0); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0); InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Info, "III {0}", 0); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } /// <summary> /// Test output van een textwriter /// </summary> /// <param name="expected"></param> /// <param name="writer"></param> private static void TestWriter(string expected, StringWriter writer) { writer.Flush(); var writerOutput = writer.ToString(); Assert.Equal(expected, writerOutput); } [Fact] public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; using (var loggerScope = new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleOutWriter1); } // // Redirect the console output to another StringWriter. { StringWriter consoleOutWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleOutput(consoleOutWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleOutWriter2); } //lambdas { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, consoleOutWriter1); } } } [Fact] public void WriteToConsoleErrorTests() { using (var loggerScope = new InternalLoggerScope(true)) { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsoleError = true; { StringWriter consoleWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleError(consoleWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } { // // Redirect the console output to another StringWriter. StringWriter consoleWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleError(consoleWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } } } [Fact] public void WriteToFileTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; var tempFile = Path.GetTempFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogFile = tempFile; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFile, expected, Encoding.UTF8); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } } } /// <summary> /// <see cref="TimeSource"/> that returns always the same time, /// passed into object constructor. /// </summary> private class FixedTimeSource : TimeSource { private readonly DateTime _time; public FixedTimeSource(DateTime time) { _time = time; } public override DateTime Time => _time; public override DateTime FromSystemTime(DateTime systemTime) { return _time; } } [Fact] public void TimestampTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = true; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; // Set fixed time source to test time output TimeSource.Current = new FixedTimeSource(DateTime.Now); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); string expectedDateTime = TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var strings = consoleOutWriter.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in strings) { Assert.Contains(expectedDateTime + ".", str); } } } /// <summary> /// Test exception overloads /// </summary> [Fact] public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; { string expected = "Warn WWW1" + prefix + ex1 + Environment.NewLine + "Error EEE1" + prefix + ex2 + Environment.NewLine + "Fatal FFF1" + prefix + ex3 + Environment.NewLine + "Trace TTT1" + prefix + ex4 + Environment.NewLine + "Debug DDD1" + prefix + ex5 + Environment.NewLine + "Info III1" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW1"); InternalLogger.Error(ex2, "EEE1"); InternalLogger.Fatal(ex3, "FFF1"); InternalLogger.Trace(ex4, "TTT1"); InternalLogger.Debug(ex5, "DDD1"); InternalLogger.Info(ex6, "III1"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW2" + prefix + ex1 + Environment.NewLine + "Error EEE2" + prefix + ex2 + Environment.NewLine + "Fatal FFF2" + prefix + ex3 + Environment.NewLine + "Trace TTT2" + prefix + ex4 + Environment.NewLine + "Debug DDD2" + prefix + ex5 + Environment.NewLine + "Info III2" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, () => "WWW2"); InternalLogger.Error(ex2, () => "EEE2"); InternalLogger.Fatal(ex3, () => "FFF2"); InternalLogger.Trace(ex4, () => "TTT2"); InternalLogger.Debug(ex5, () => "DDD2"); InternalLogger.Info(ex6, () => "III2"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW3" + prefix + ex1 + Environment.NewLine + "Error EEE3" + prefix + ex2 + Environment.NewLine + "Fatal FFF3" + prefix + ex3 + Environment.NewLine + "Trace TTT3" + prefix + ex4 + Environment.NewLine + "Debug DDD3" + prefix + ex5 + Environment.NewLine + "Info III3" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, "WWW3"); InternalLogger.Log(ex2, LogLevel.Error, "EEE3"); InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3"); InternalLogger.Log(ex4, LogLevel.Trace, "TTT3"); InternalLogger.Log(ex5, LogLevel.Debug, "DDD3"); InternalLogger.Log(ex6, LogLevel.Info, "III3"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW4" + prefix + ex1 + Environment.NewLine + "Error EEE4" + prefix + ex2 + Environment.NewLine + "Fatal FFF4" + prefix + ex3 + Environment.NewLine + "Trace TTT4" + prefix + ex4 + Environment.NewLine + "Debug DDD4" + prefix + ex5 + Environment.NewLine + "Info III4" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4"); InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4"); InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4"); InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4"); InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4"); InternalLogger.Log(ex6, LogLevel.Info, () => "III4"); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_log(string rawLogLevel, int count) { Action log = () => { InternalLogger.Log(LogLevel.Fatal, "L1"); InternalLogger.Log(LogLevel.Error, "L2"); InternalLogger.Log(LogLevel.Warn, "L3"); InternalLogger.Log(LogLevel.Info, "L4"); InternalLogger.Log(LogLevel.Debug, "L5"); InternalLogger.Log(LogLevel.Trace, "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal("L1"); InternalLogger.Error("L2"); InternalLogger.Warn("L3"); InternalLogger.Info("L4"); InternalLogger.Debug("L5"); InternalLogger.Trace("L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_lambda(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal(() => "L1"); InternalLogger.Error(() => "L2"); InternalLogger.Warn(() => "L3"); InternalLogger.Info(() => "L4"); InternalLogger.Debug(() => "L5"); InternalLogger.Trace(() => "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } private static void TestMinLevelSwitch_inner(string rawLogLevel, int count, Action log) { try { //set minimal InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; var expected = ""; var logLevel = LogLevel.Fatal.Ordinal; for (int i = 0; i < count; i++, logLevel--) { expected += LogLevel.FromOrdinal(logLevel) + " L" + (i + 1) + ";"; } log(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } finally { InternalLogger.Reset(); } } [Theory] [InlineData("trace", true)] [InlineData("debug", true)] [InlineData("info", true)] [InlineData("warn", true)] [InlineData("error", true)] [InlineData("fatal", true)] [InlineData("off", false)] public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory) { var tempPath = Path.GetTempPath(); var tempFileName = Path.GetRandomFileName(); var randomSubDirectory = Path.Combine(tempPath, Path.GetRandomFileName()); string tempFile = Path.Combine(randomSubDirectory, tempFileName); try { InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } Assert.False(Directory.Exists(randomSubDirectory)); // Set the log file, which will only create the needed directories InternalLogger.LogFile = tempFile; Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory); Assert.False(File.Exists(tempFile)); InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created."); Assert.Equal(File.Exists(tempFile), shouldCreateDirectory); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } } } [Fact] public void CreateFileInCurrentDirectoryTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; // Store off the previous log file string previousLogFile = InternalLogger.LogFile; var tempFileName = Path.GetRandomFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; Assert.False(File.Exists(tempFileName)); // Set the log file, which only has a filename InternalLogger.LogFile = tempFileName; Assert.False(File.Exists(tempFileName)); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFileName, expected, Encoding.UTF8); Assert.True(File.Exists(tempFileName)); } finally { InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; using Microsoft.Xna.Framework; namespace tests { public class OrientationTest : CCLayer { static int MAX_LAYER = 1; static int sceneIdx = -1; public static CCDisplayOrientation s_currentOrientation = CCDisplayOrientation.LandscapeLeft; public OrientationTest() { InitOrientationTest(); } public static CCLayer CreateTestCaseLayer(int index) { switch (index) { case 0: { Orientation1 pRet = new Orientation1(); return pRet; } default: return null; } } public static CCLayer NextOrientationTestCase() { sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; return CreateTestCaseLayer(sceneIdx); } public static CCLayer BackOrientationTestCase() { sceneIdx--; if (sceneIdx < 0) sceneIdx += MAX_LAYER; return CreateTestCaseLayer(sceneIdx); } public static CCLayer RestartOrientationTestCase() { return CreateTestCaseLayer(sceneIdx); } private bool InitOrientationTest () { bool bRet = false; do { CCSize s = Layer.VisibleBoundsWorldspace.Size; var label = new CCLabel(title(), "Arial", 26, CCLabelFormat.SpriteFont); AddChild(label, 1); label.Position = new CCPoint(s.Width / 2, s.Height - 50); string sSubtitle = subtitle(); if (sSubtitle.Length > 0) { var l = new CCLabel(sSubtitle, "Arial", 16, CCLabelFormat.SpriteFont); AddChild(l, 1); l.Position = new CCPoint(s.Width / 2, s.Height - 80); } CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, BackCallback); CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, RestartCallback); CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, NextCallback); CCMenu menu = new CCMenu(item1, item2, item3); menu.Position = new CCPoint(); item1.Position = new CCPoint(s.Width / 2 - 100, 30); item2.Position = new CCPoint(s.Width / 2, 30); item3.Position = new CCPoint(s.Width / 2 + 100, 30); bRet = true; } while (false); return bRet; } public void RestartCallback(object pSender) { CCScene s = new OrientationTestScene(); s.AddChild(RestartOrientationTestCase()); Scene.Director.ReplaceScene(s); } public void NextCallback(object pSender) { CCScene s = new OrientationTestScene(); s.AddChild(NextOrientationTestCase()); Scene.Director.ReplaceScene(s); } public void BackCallback(object pSender) { CCScene s = new OrientationTestScene(); s.AddChild(BackOrientationTestCase()); Scene.Director.ReplaceScene(s); } public virtual string title() { return "No title"; } public virtual string subtitle() { return ""; } } public class Orientation1 : OrientationTest { public Orientation1() { InitOrientation1(); } private bool InitOrientation1() { bool bRet = false; do { // Register Touch Event var touchListener = new CCEventListenerTouchAllAtOnce(); touchListener.OnTouchesEnded = onTouchesEnded; AddEventListener(touchListener); CCSize s = Layer.VisibleBoundsWorldspace.Size; CCMenuItem item = new CCMenuItemFont("Rotate Device", RotateDevice); CCMenu menu = new CCMenu(item); menu.Position = new CCPoint(s.Width / 2, s.Height / 2); AddChild(menu); bRet = true; } while (false); return bRet; } public void NewOrientation() { switch (s_currentOrientation) { case CCDisplayOrientation.LandscapeLeft: s_currentOrientation = CCDisplayOrientation.Portrait; break; case CCDisplayOrientation.Portrait: s_currentOrientation = CCDisplayOrientation.LandscapeRight; break; case CCDisplayOrientation.LandscapeRight: s_currentOrientation = CCDisplayOrientation.LandscapeLeft; break; } // CCDrawManager.SharedDrawManager.SetOrientation(s_currentOrientation); } public void RotateDevice(object pSender) { NewOrientation(); RestartCallback(null); } void onTouchesEnded(List<CCTouch> touches, CCEvent touchEvent) { foreach (CCTouch touch in touches) { if (touch == null) break; CCPoint a = touch.LocationOnScreen; //CCLog("(%d,%d) == (%d,%d)", (int) a.x, (int)a.y, (int)b.x, (int)b.y ); //CCLog.Log("({0},{1}) == ({2},{3})", (int)a.X, (int)a.Y, (int)b.X, (int)b.Y); } } public override string title() { return "Testing conversion"; } public override string subtitle() { return "Tap screen and see the debug console"; } } public class OrientationTestScene : TestScene { protected override void NextTestCase() { } protected override void PreviousTestCase() { } protected override void RestTestCase() { } public override void runThisTest() { OrientationTest.s_currentOrientation = CCDisplayOrientation.LandscapeLeft; CCLayer pLayer = OrientationTest.NextOrientationTestCase(); AddChild(pLayer); Scene.Director.ReplaceScene(this); } public override void MainMenuCallback(object pSender) { //CCDrawManager.SharedDrawManager.GraphicsDevice.PresentationParameters.DisplayOrientation = DisplayOrientation.LandscapeLeft; base.MainMenuCallback(pSender); } } }