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. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { internal const int GENERIC_READ = unchecked((int)0x80000000); public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.Errors.ERROR_SUCCESS) { string fileName = destFullPath; if (errorCode != Interop.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.Kernel32.UnsafeCreateFile(sourceFullPath, GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { int flags = Interop.Kernel32.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS; } if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; string errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { string name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(string fullPath) { bool r = Interop.Kernel32.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(string path, out int lastError) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, returnErrorOnNotFound: true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } /// <summary> /// Returns 0 on success, otherwise a Win32 error code. Note that /// classes should use -1 as the uninitialized state for dataInitialized. /// </summary> /// <param name="returnErrorOnNotFound">Return the error code for not found errors?</param> [System.Security.SecurityCritical] internal static int FillAttributeInfo(string path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool returnErrorOnNotFound) { int errorCode = Interop.Errors.ERROR_SUCCESS; // Neither GetFileAttributes or FindFirstFile like trailing separators path = path.TrimEnd(PathHelpers.DirectorySeparatorChars); using (new DisableMediaInsertionPrompt()) { if (!Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { // Files that are marked for deletion will not let you GetFileAttributes, // ERROR_ACCESS_DENIED is given back without filling out the data struct. // FindFirstFile, however, will. Historically we always gave back attributes // for marked-for-deletion files. var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (handle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); } else { errorCode = Interop.Errors.ERROR_SUCCESS; data.PopulateFrom(ref findData); } } } } } if (errorCode != Interop.Errors.ERROR_SUCCESS && !returnErrorOnNotFound) { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: case Interop.Errors.ERROR_PATH_NOT_FOUND: case Interop.Errors.ERROR_NOT_READY: // Removable media not ready // Return default value for backward compatibility data.fileAttributes = -1; return Interop.Errors.ERROR_SUCCESS; } } return errorCode; } public override bool FileExists(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1); if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); string currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (i.e. by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.Kernel32.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.Kernel32.MAX_PATH) errorCode = Interop.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.Kernel32.SafeCreateFile( fullPath, Interop.Kernel32.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) { // Ensure we throw a DirectoryNotFoundException. if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) recursive = false; // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) RemoveDirectoryHelper(PathInternal.EnsureExtendedPrefix(fullPath), recursive, true); } [System.Security.SecurityCritical] // auto-generated private static void RemoveDirectoryHelper(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound) { bool r; int errorCode; Exception ex = null; // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. // Note the logic to check whether fullPath is a reparse point is // in Delete(string, string, bool), and will set "recursive" to false. // Note that Win32's DeleteFile and RemoveDirectory will just delete // the reparse point itself. if (recursive) { Interop.Kernel32.WIN32_FIND_DATA data = new Interop.Kernel32.WIN32_FIND_DATA(); // Open a Find handle using (SafeFindHandle hnd = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref data)) { if (hnd.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { bool isDir = (0 != (data.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY)); if (isDir) { // Skip ".", "..". if (data.cFileName.Equals(".") || data.cFileName.Equals("..")) continue; // Recurse for all directories, unless they are // reparse points. Do not follow mount points nor // symbolic links, but do delete the reparse point // itself. bool shouldRecurse = (0 == (data.dwFileAttributes & (int)FileAttributes.ReparsePoint)); if (shouldRecurse) { string newFullPath = Path.Combine(fullPath, data.cFileName); try { RemoveDirectoryHelper(newFullPath, recursive, false); } catch (Exception e) { if (ex == null) ex = e; } } else { // Check to see if this is a mount point, and // unmount it. if (data.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Use full path plus a trailing '\' string mountPoint = Path.Combine(fullPath, data.cFileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } // RemoveDirectory on a symbolic link will // remove the link itself. string reparsePoint = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.RemoveDirectory(reparsePoint); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } else { string fileName = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.DeleteFile(fileName); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } while (Interop.Kernel32.FindNextFile(hnd, ref data)); // Make sure we quit with a sensible error. errorCode = Marshal.GetLastWin32Error(); } if (ex != null) throw ex; if (errorCode != 0 && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } r = Interop.Kernel32.RemoveDirectory(fullPath); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) // A dubious error code. errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // don't throw the DirectoryNotFoundException since this is a subdir and // there could be a race condition between two Directory.Delete callers if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound) return; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.Kernel32.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using DevExpress.CodeRush.Core; using DevExpress.CodeRush.Diagnostics; using DevExpress.CodeRush.Diagnostics.General; using DevExpress.DXCore.Controls.XtraTreeList; using DevExpress.DXCore.Controls.XtraTreeList.Nodes; using DevExpress.DXCore.Controls.XtraTreeList.Columns; using DevExpress.CodeRush.PlugInCore; using DevExpress.DXCore.Controls.XtraTab; namespace CR_XkeysEngine { public class frmFind: DXCoreForm { #region Private fields ... private TreeList _List; private CustomInputShortcut _CustomInputShortcut; private CustomInputShortcut _OldCustomInputShortcut; private string _OldFolderName; private string _OldCommandName; private int _FoldersActiveNumber; private int _CustomInputBindingsActiveNumber; private int _CommandActiveNumber; private ArrayList _Folders; private ArrayList _CustomInputBindings; private ArrayList _CommandBindings; #endregion #region private fields ... private XkeysEditControl edCustomInput; private XtraTabControl tabControl; private XtraTabPage tabFolder; private XtraTabPage tabCustomInputShortcut; private System.Windows.Forms.Label label1; private DevExpress.DXCore.Controls.XtraEditors.TextEdit edFolderName; private DevExpress.DXCore.Controls.XtraEditors.SimpleButton btnFindNext; private DevExpress.DXCore.Controls.XtraEditors.SimpleButton btnFind; private XtraTabPage tabCommand; private System.Windows.Forms.Label label2; private DevExpress.DXCore.Controls.XtraEditors.ComboBoxEdit cmbCommands; private System.ComponentModel.Container components = null; #endregion // constructors ... #region frmFind public frmFind() { InitializeComponent(); InitializeVariables(); } #endregion //VS generated code ... #region Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { CleanUpVariables(); if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tabControl = new DevExpress.DXCore.Controls.XtraTab.XtraTabControl(); this.tabCustomInputShortcut = new DevExpress.DXCore.Controls.XtraTab.XtraTabPage(); this.edCustomInput = new CR_XkeysEngine.XkeysEditControl(); this.tabFolder = new DevExpress.DXCore.Controls.XtraTab.XtraTabPage(); this.edFolderName = new DevExpress.DXCore.Controls.XtraEditors.TextEdit(); this.label1 = new System.Windows.Forms.Label(); this.tabCommand = new DevExpress.DXCore.Controls.XtraTab.XtraTabPage(); this.cmbCommands = new DevExpress.DXCore.Controls.XtraEditors.ComboBoxEdit(); this.label2 = new System.Windows.Forms.Label(); this.btnFindNext = new DevExpress.DXCore.Controls.XtraEditors.SimpleButton(); this.btnFind = new DevExpress.DXCore.Controls.XtraEditors.SimpleButton(); ((System.ComponentModel.ISupportInitialize)(this.Images16x16)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tabControl)).BeginInit(); this.tabControl.SuspendLayout(); this.tabCustomInputShortcut.SuspendLayout(); this.tabFolder.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.edFolderName.Properties)).BeginInit(); this.tabCommand.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cmbCommands.Properties)).BeginInit(); this.SuspendLayout(); // // tabControl // this.tabControl.Location = new System.Drawing.Point(-4, 0); this.tabControl.Margin = new System.Windows.Forms.Padding(0); this.tabControl.Name = "tabControl"; this.tabControl.SelectedTabPage = this.tabCustomInputShortcut; this.tabControl.Size = new System.Drawing.Size(316, 217); this.tabControl.TabIndex = 0; this.tabControl.TabPages.AddRange(new DevExpress.DXCore.Controls.XtraTab.XtraTabPage[] { this.tabFolder, this.tabCustomInputShortcut, this.tabCommand}); // // tabCustomInputShortcut // this.tabCustomInputShortcut.Controls.Add(this.edCustomInput); this.tabCustomInputShortcut.Name = "tabCustomInputShortcut"; this.tabCustomInputShortcut.Size = new System.Drawing.Size(314, 192); this.tabCustomInputShortcut.Text = "X-keys"; // // edCustomInput // this.edCustomInput.AltKeyDown = false; this.edCustomInput.AnyShiftModifier = false; this.edCustomInput.CtrlKeyDown = false; this.edCustomInput.Location = new System.Drawing.Point(8, 9); this.edCustomInput.Name = "edCustomInput"; this.edCustomInput.ShiftKeyDown = false; this.edCustomInput.Size = new System.Drawing.Size(288, 180); this.edCustomInput.TabIndex = 17; this.edCustomInput.CustomInputChanged += new CR_XkeysEngine.CustomInputChangedEventHandler(this.edCustomInput_CustomInputChanged); // // tabFolder // this.tabFolder.Controls.Add(this.edFolderName); this.tabFolder.Controls.Add(this.label1); this.tabFolder.Margin = new System.Windows.Forms.Padding(0); this.tabFolder.Name = "tabFolder"; this.tabFolder.Size = new System.Drawing.Size(314, 192); this.tabFolder.Text = "Folder"; // // edFolderName // this.edFolderName.EditValue = ""; this.edFolderName.Location = new System.Drawing.Point(84, 16); this.edFolderName.Name = "edFolderName"; this.edFolderName.Size = new System.Drawing.Size(213, 20); this.edFolderName.TabIndex = 1; // // label1 // this.label1.Location = new System.Drawing.Point(8, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 25); this.label1.TabIndex = 0; this.label1.Text = "Folder name"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tabCommand // this.tabCommand.Controls.Add(this.cmbCommands); this.tabCommand.Controls.Add(this.label2); this.tabCommand.Name = "tabCommand"; this.tabCommand.Size = new System.Drawing.Size(314, 192); this.tabCommand.Text = "Command"; // // cmbCommands // this.cmbCommands.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cmbCommands.EditValue = ""; this.cmbCommands.Location = new System.Drawing.Point(76, 10); this.cmbCommands.Name = "cmbCommands"; this.cmbCommands.Properties.Buttons.AddRange(new DevExpress.DXCore.Controls.XtraEditors.Controls.EditorButton[] { new DevExpress.DXCore.Controls.XtraEditors.Controls.EditorButton(DevExpress.DXCore.Controls.XtraEditors.Controls.ButtonPredefines.Combo)}); this.cmbCommands.Properties.CycleOnDblClick = false; this.cmbCommands.Properties.DropDownRows = 24; this.cmbCommands.Size = new System.Drawing.Size(228, 20); this.cmbCommands.TabIndex = 9; // // label2 // this.label2.Location = new System.Drawing.Point(8, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 24); this.label2.TabIndex = 2; this.label2.Text = "Command"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnFindNext // this.btnFindNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnFindNext.ImageIndex = 387; this.btnFindNext.ImageList = this.Images16x16; this.btnFindNext.Location = new System.Drawing.Point(211, 220); this.btnFindNext.Name = "btnFindNext"; this.btnFindNext.Size = new System.Drawing.Size(88, 25); this.btnFindNext.TabIndex = 2; this.btnFindNext.Text = "&Find Next"; this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click); // // btnFind // this.btnFind.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnFind.ImageIndex = 388; this.btnFind.ImageList = this.Images16x16; this.btnFind.Location = new System.Drawing.Point(139, 220); this.btnFind.Name = "btnFind"; this.btnFind.Size = new System.Drawing.Size(68, 25); this.btnFind.TabIndex = 3; this.btnFind.Text = "&Find"; this.btnFind.Click += new System.EventHandler(this.btnFind_Click); // // frmFind // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(306, 251); this.Controls.Add(this.btnFind); this.Controls.Add(this.btnFindNext); this.Controls.Add(this.tabControl); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmFind"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Find"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.frmFind_KeyDown); ((System.ComponentModel.ISupportInitialize)(this.Images16x16)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tabControl)).EndInit(); this.tabControl.ResumeLayout(false); this.tabCustomInputShortcut.ResumeLayout(false); this.tabFolder.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.edFolderName.Properties)).EndInit(); this.tabCommand.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.cmbCommands.Properties)).EndInit(); this.ResumeLayout(false); } #endregion // private methods .. private void CleanUpVariables() { _List = null; _OldFolderName = ""; _OldCustomInputShortcut = null; _OldCommandName = ""; _CustomInputShortcut = null; _FoldersActiveNumber = -1; _CustomInputBindingsActiveNumber = -1; _CommandActiveNumber = -1; _Folders = null; _CustomInputBindings = null; _CommandBindings = null; } #region InitializeVariables private void InitializeVariables() { CleanUpVariables(); _Folders = new ArrayList(); _CustomInputBindings = new ArrayList(); _CommandBindings = new ArrayList(); tabControl.SelectedTabPageIndex = 1; LoadCommands(); } #endregion #region LoadCommands private void LoadCommands() { cmbCommands.Properties.Items.Clear(); string[] lCommands = new string[CodeRush.Actions.Count]; for(int i = 0; i < CodeRush.Actions.Count; i++) lCommands[i] = CodeRush.Actions[i].ActionName; Array.Sort(lCommands); for(int i = 0; i < lCommands.Length; i++) cmbCommands.Properties.Items.Add(lCommands[i]); } #endregion private void SetTargetTreeList(TreeList list) { _List = list; } #region ClearFolders private void ClearFolders() { if (_Folders == null) _Folders = new ArrayList(); if (_Folders.Count > 0) _Folders.Clear(); } #endregion #region ClearMouseBindings private void ClearCustomInputBindings() { if (_CustomInputBindings == null) _CustomInputBindings = new ArrayList(); if (_CustomInputBindings.Count > 0) _CustomInputBindings.Clear(); } #endregion #region ClearCommands private void ClearCommands() { if (_CommandBindings == null) _CommandBindings = new ArrayList(); if (_CommandBindings.Count > 0) _CommandBindings.Clear(); } #endregion #region FillFoldersRecursive private void FillFoldersRecursive(TreeListNodes nodes) { if (nodes == null || nodes.Count == 0) return; for (int i = 0; i < nodes.Count; i++) { if (!(nodes[i].Tag is CommandKeyFolder)) continue; CommandKeyFolder lFolder = nodes[i].Tag as CommandKeyFolder; if (FolderName.Length > 0 && lFolder.Name == FolderName) _Folders.Add(nodes[i]); FillFoldersRecursive(nodes[i].Nodes); } } #endregion #region FillCustomDataBindingsRecursive private void FillCustomDataBindingsRecursive(TreeListNodes nodes) { if (nodes == null || nodes.Count == 0 || _CustomInputShortcut == null) return; for (int i = 0; i < nodes.Count; i++) { if (nodes[i].Tag is CommandKeyFolder) FillCustomDataBindingsRecursive(nodes[i].Nodes); else { CommandKeyBinding binding = nodes[i].Tag as CommandKeyBinding; if (binding == null) continue; if (binding.Matches(_CustomInputShortcut) == MatchQuality.FullMatch) _CustomInputBindings.Add(nodes[i]); } } } #endregion #region FillCommandsRecursive private void FillCommandsRecursive(TreeListNodes nodes) { if (nodes == null || nodes.Count == 0) return; for (int i = 0; i < nodes.Count; i++) { if (nodes[i].Tag is CommandKeyFolder) FillCommandsRecursive(nodes[i].Nodes); else { CommandKeyBinding lBinding = nodes[i].Tag as CommandKeyBinding; if (lBinding == null) continue; if (lBinding.Command != null && lBinding.Command == CommandName) _CommandBindings.Add(nodes[i]); } } } #endregion #region CompareCustomInputShortcuts private bool CompareCustomInputShortcuts() { if (_OldCustomInputShortcut == null || _CustomInputShortcut == null) return false; if (_OldCustomInputShortcut.DisplayName != _CustomInputShortcut.DisplayName) return false; return true; } #endregion #region CompareCommands private bool CompareCommands() { if (_OldCommandName == null || CommandName == null) return false; return (_OldCommandName == CommandName); } #endregion #region RefreshFolders private void RefreshFolders() { if (_OldFolderName != FolderName) try { ClearFolders(); FillFoldersRecursive(_List.Nodes); } finally { _FoldersActiveNumber = -1; _OldFolderName = FolderName; } } #endregion #region RefreshCustomInputBindings private void RefreshCustomInputBindings() { if (!CompareCustomInputShortcuts()) try { ClearCustomInputBindings(); FillCustomDataBindingsRecursive(_List.Nodes); } finally { _CustomInputBindingsActiveNumber = -1; _OldCustomInputShortcut = _CustomInputShortcut; } } #endregion #region RefreshCommands private void RefreshCommands() { if (!CompareCommands()) try { ClearCommands(); FillCommandsRecursive(_List.Nodes); } finally { _CustomInputBindingsActiveNumber = -1; _OldCustomInputShortcut = _CustomInputShortcut; } } #endregion #region FindCustomNode private bool FindCustomNode(int folderNumber, ArrayList nodes) { if (nodes == null || nodes.Count == 0) { if (_List.Nodes.Count > 0) _List.FocusedNode = _List.Nodes[0]; MessageBox.Show("No items were found!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } try { TreeListNode lNode = nodes[folderNumber] as TreeListNode; _List.FocusedNode = lNode; _List.MakeNodeVisible(lNode); lNode.Expanded = true; _List.Refresh(); return true; } catch { Log.SendError("Shortcuts : can not make the node visible"); return false; } } #endregion #region FindFirstFolder private void FindFirstFolder() { RefreshFolders(); _FoldersActiveNumber = 0; FindCustomNode(_FoldersActiveNumber, _Folders); } #endregion #region FindFirstCustomInputBinding private void FindFirstCustomInputBinding() { RefreshCustomInputBindings(); _CustomInputBindingsActiveNumber = 0; FindCustomNode(_CustomInputBindingsActiveNumber, _CustomInputBindings); } #endregion #region FindFirstCommand private void FindFirstCommand() { RefreshCommands(); _CommandActiveNumber = 0; FindCustomNode(_CommandActiveNumber, _CommandBindings); } #endregion #region FindNextFolder private void FindNextFolder() { RefreshFolders(); if (_Folders == null || _Folders.Count == 0) return; _FoldersActiveNumber++; if (_FoldersActiveNumber >= _Folders.Count) _FoldersActiveNumber = 0; FindCustomNode(_FoldersActiveNumber, _Folders); } #endregion #region FindNextMouseBinding private void FindNextCustomInputBinding() { RefreshCustomInputBindings(); if (_CustomInputBindings == null || _CustomInputBindings.Count == 0) return; _CustomInputBindingsActiveNumber++; if (_CustomInputBindingsActiveNumber >= _CustomInputBindings.Count) _CustomInputBindingsActiveNumber = 0; FindCustomNode(_CustomInputBindingsActiveNumber, _CustomInputBindings); } #endregion #region FindNextCommand private void FindNextCommand() { RefreshCommands(); if (_CommandBindings == null || _CommandBindings.Count == 0) return; _CommandActiveNumber++; if (_CommandActiveNumber >= _CommandBindings.Count) _CommandActiveNumber = 0; FindCustomNode(_CommandActiveNumber, _CommandBindings); } #endregion // event handlers #region btnFind_Click private void btnFind_Click(object sender, System.EventArgs e) { switch (tabControl.SelectedTabPageIndex) { case 0: FindFirstFolder(); break; case 1: FindFirstCustomInputBinding(); break; case 2: FindFirstCommand(); break; } } #endregion #region btnFindNext_Click private void btnFindNext_Click(object sender, System.EventArgs e) { switch (tabControl.SelectedTabPageIndex) { case 0: FindNextFolder(); break; case 1: FindNextCustomInputBinding(); break; case 2: FindNextCommand(); break; } } #endregion #region frmFind_KeyDown private void frmFind_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { switch (e.KeyData) { case Keys.Escape: DialogResult = DialogResult.Cancel; break; } } #endregion #region edKeyEdit_KeyChanged private void edCustomInput_CustomInputChanged(object sender, CR_XkeysEngine.CustomInputChangedEventArgs ea) { _CustomInputShortcut = ea.Shortcut; } #endregion // public methods ... #region Execute public static void Execute(TreeList list) { if (list == null) return; using (frmFind lForm = new frmFind()) { lForm.SetTargetTreeList(list); lForm.ShowDialog(); } } #endregion // private properties ... #region FolderName private string FolderName { get { return edFolderName.Text; } set { edFolderName.Text = value; } } #endregion #region CommandsName private string CommandName { get { return cmbCommands.Text; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using VersionOne.SDK.APIClient; using System.Net; using VersionOne.VisualStudio.DataLayer.Entities; using VersionOne.VisualStudio.DataLayer.Logging; using VersionOne.VisualStudio.DataLayer.Settings; namespace VersionOne.VisualStudio.DataLayer { public class ApiDataLayer : IDataLayerInternal { #region Private fields private readonly VersionOneConnector connector = new VersionOneConnector(); private readonly static IList<AttributeInfo> AttributesToQuery = new List<AttributeInfo>(); private RequiredFieldsValidator requiredFieldsValidator; public IDictionary<string, IAssetType> Types { get; private set; } public IAssetType ProjectType { get; private set; } public IAssetType TaskType { get; private set; } public IAssetType TestType { get; private set; } public IAssetType DefectType { get; private set; } public IAssetType StoryType { get; private set; } private IAssetType workitemType; private IAssetType primaryWorkitemType; private IAssetType effortType; private IDictionary<string, PropertyValues> listPropertyValues; private ILogger logger; #endregion public Oid MemberOid { get; private set; } public ILoggerFactory LoggerFactory { get; set; } public ApiDataLayer() { var prefixes = new[] { Entity.TaskType, Entity.DefectType, Entity.StoryType, Entity.TestType }; foreach(var prefix in prefixes) { AttributesToQuery.Add(new AttributeInfo("CheckQuickClose", prefix, false)); AttributesToQuery.Add(new AttributeInfo("CheckQuickSignup", prefix, false)); } AttributesToQuery.Add(new AttributeInfo("Schedule.EarliestActiveTimebox", Entity.ProjectType, false)); } public ILogger Logger { get { return logger ?? (logger = LoggerFactory == null ? new BlackholeLogger() : LoggerFactory.GetLogger("DataLayer")); } } public string ApiVersion { get { return connector.ApiVersion; } set { connector.ApiVersion = value; } } public string NullProjectToken { get { return Oid.Null.Token; } } public string CurrentProjectId { get; set; } public Project CurrentProject { get { if (CurrentProjectId == Oid.Null.Token || string.IsNullOrEmpty(CurrentProjectId)) { CurrentProjectId = "Scope:0"; } return GetProjectById(CurrentProjectId); } set { CurrentProjectId = value.Id; } } public bool ShowAllTasks { get; set; } public void CommitChanges(IAssetCache assetCache) { if(!connector.IsConnected) { Logger.Error("Not connected to VersionOne."); } try { var validationResult = new Dictionary<Asset, List<RequiredFieldsDto>>(); var internalCache = assetCache.ToInternalCache(); var workitems = assetCache.GetWorkitems(true); foreach(var item in workitems) { if(!ValidateWorkitemAndCommitOnSuccess(item, internalCache.Efforts, validationResult)) { continue; } foreach(var child in item.Children) { ValidateWorkitemAndCommitOnSuccess(child, internalCache.Efforts, validationResult); } } if(validationResult.Count > 0) { throw new ValidatorException(requiredFieldsValidator.CreateErrorMessage(validationResult)); } } catch(APIException ex) { Logger.Error("Failed to commit changes.", ex); } } private bool ValidateWorkitemAndCommitOnSuccess(Workitem item, IDictionary<Asset, double> efforts, IDictionary<Asset, List<RequiredFieldsDto>> validationResults) { var itemValidationResult = requiredFieldsValidator.Validate(item.Asset); if(itemValidationResult.Count == 0) { item.CommitChanges(); //TODO do we really need 2 commits effort? in item.ComitChanges() effort already commited CommitEffort(efforts, item.Asset); return true; } validationResults.Add(item.Asset, itemValidationResult); return false; } private IFilterTerm GetScopeFilter(IAssetType assetType) { var terms = new List<FilterTerm>(4); var term = new FilterTerm(assetType.GetAttributeDefinition("Scope.AssetState")); term.NotEqual(AssetState.Closed); terms.Add(term); term = new FilterTerm(assetType.GetAttributeDefinition("Scope.ParentMeAndUp")); term.Equal(CurrentProjectId); terms.Add(term); term = new FilterTerm(assetType.GetAttributeDefinition("Timebox.State.Code")); term.Equal("ACTV"); terms.Add(term); term = new FilterTerm(assetType.GetAttributeDefinition("AssetState")); term.NotEqual(AssetState.Closed); terms.Add(term); return new AndFilterTerm(terms.Cast<IFilterTerm>().ToArray()); } #region Effort tracking public IEffortTracking EffortTracking { get; private set; } private void InitEffortTracking() { EffortTracking = new EffortTracking(connector); EffortTracking.Init(); } #endregion private void AddSelection(Query query, string typePrefix) { foreach (var attrInfo in AttributesToQuery.Where(attrInfo => attrInfo.Prefix == typePrefix)) { try { var def = Types[attrInfo.Prefix].GetAttributeDefinition(attrInfo.Attr); query.Selection.Add(def); } catch(MetaException ex) { Logger.Warn("Wrong attribute: " + attrInfo, ex); } } if(requiredFieldsValidator.GetFields(typePrefix) == null) { return; } foreach(var field in requiredFieldsValidator.GetFields(typePrefix)) { try { var def = Types[typePrefix].GetAttributeDefinition(field.Name); query.Selection.Add(def); } catch(MetaException ex) { Logger.Warn("Wrong attribute: " + field.Name, ex); } } } private Project GetProjectById(string id) { if(!connector.IsConnected) { return null; } if(CurrentProjectId == null) { Logger.Error("Current project is not selected"); throw new DataLayerException("Current project is not selected"); } var query = new Query(Oid.FromToken(id, connector.MetaModel)); AddSelection(query, Entity.ProjectType); try { var result = connector.Services.Retrieve(query); return result.TotalAvaliable == 1 ? WorkitemFactory.CreateProject(result.Assets[0], null) : null; } catch(MetaException ex) { connector.IsConnected = false; throw new DataLayerException("Unable to get projects", ex); } catch(Exception ex) { throw new DataLayerException("Unable to get projects", ex); } } public void GetWorkitems(IAssetCache assetCache) { if(!connector.IsConnected) { Logger.Error("Not connected to VersionOne."); } if(CurrentProjectId == null) { throw new DataLayerException("Current project is not selected"); } if(assetCache.IsSet) { return; } try { var parentDef = workitemType.GetAttributeDefinition("Parent"); var query = new Query(workitemType, parentDef); AddSelection(query, Entity.TaskType); AddSelection(query, Entity.StoryType); AddSelection(query, Entity.DefectType); AddSelection(query, Entity.TestType); query.Filter = GetScopeFilter(workitemType); query.OrderBy.MajorSort(primaryWorkitemType.DefaultOrderBy, OrderBy.Order.Ascending); query.OrderBy.MinorSort(workitemType.DefaultOrderBy, OrderBy.Order.Ascending); var assetList = connector.Services.Retrieve(query); assetCache.ToInternalCache().Set(assetList.Assets); } catch(MetaException ex) { Logger.Error("Unable to get workitems.", ex); } catch(WebException ex) { connector.IsConnected = false; Logger.Error("Unable to get workitems.", ex); } catch(Exception ex) { Logger.Error("Unable to get workitems.", ex); } } /// <summary> /// Check if asset should be used when Show My Tasks filter is on /// </summary> /// <param name="asset">Story, Task, Defect or Test</param> /// <returns>true if current user is owner of asset, false - otherwise</returns> public bool AssetPassesShowMyTasksFilter(Asset asset) { if(asset.HasChanged || asset.Oid.IsNull) { return true; } var definition = workitemType.GetAttributeDefinition(Entity.OwnersProperty); var attribute = asset.GetAttribute(definition); var owners = attribute.Values; if(owners.Cast<Oid>().Any(oid => oid == MemberOid)) { return true; } return asset.Children != null && asset.Children.Any(AssetPassesShowMyTasksFilter); } public IList<Project> GetProjectTree() { try { var scopeQuery = new Query(ProjectType, ProjectType.GetAttributeDefinition("Parent")); var stateTerm = new FilterTerm(ProjectType.GetAttributeDefinition("AssetState")); stateTerm.NotEqual(AssetState.Closed); scopeQuery.Filter = stateTerm; AddSelection(scopeQuery, Entity.ProjectType); var result = connector.Services.Retrieve(scopeQuery); var roots = result.Assets.Select(asset => WorkitemFactory.CreateProject(asset, null)).ToList(); return roots; } catch(WebException ex) { connector.IsConnected = false; Logger.Error("Can't get projects list.", ex); return null; } catch(Exception ex) { Logger.Error("Can't get projects list.", ex); return null; } } public IAssetCache CreateAssetCache() { return new AssetCache(this); } public void CheckConnection(VersionOneSettings settings) { try { connector.CheckConnection(settings); } catch(Exception ex) { logger.Error("Cannot connect to V1 server.", ex); throw new DataLayerException("Cannot connect to VersionOne server.", ex); } } public bool Connect(VersionOneSettings settings) { connector.IsConnected = false; try { connector.Connect(settings); Types = new Dictionary<string, IAssetType>(5); ProjectType = GetAssetType(Entity.ProjectType); TaskType = GetAssetType(Entity.TaskType); TestType = GetAssetType(Entity.TestType); DefectType = GetAssetType(Entity.DefectType); StoryType = GetAssetType(Entity.StoryType); workitemType = connector.MetaModel.GetAssetType("Workitem"); primaryWorkitemType = connector.MetaModel.GetAssetType("PrimaryWorkitem"); InitEffortTracking(); MemberOid = connector.Services.LoggedIn; // This method creates the list values needed to popuplate the combo lists components. UpdateListPropertyValues(); requiredFieldsValidator = new RequiredFieldsValidator(connector.MetaModel, connector.Services, this); connector.IsConnected = true; return true; } catch(MetaException ex) { Logger.Error("Cannot connect to V1 server.", ex); return false; } catch(WebException ex) { connector.IsConnected = false; Logger.Error("Cannot connect to V1 server.", ex); return false; } catch(Exception ex) { Logger.Error("Cannot connect to V1 server.", ex); return false; } } // TODO try to find out why SecurityException might occur here private IAssetType GetAssetType(string token) { var type = connector.MetaModel.GetAssetType(token); Types.Add(token, type); return type; } private static string ResolvePropertyKey(string propertyAlias) { switch(propertyAlias) { case "DefectStatus": return "StoryStatus"; case "DefectSource": return "StorySource"; case "ScopeBuildProjects": return "BuildProject"; case "TaskOwners": case "StoryOwners": case "DefectOwners": case "TestOwners": return "Member"; } return propertyAlias; } public void UpdateListPropertyValues() { if (listPropertyValues == null) { listPropertyValues = new Dictionary<string, PropertyValues>(AttributesToQuery.Count); } else { listPropertyValues.Clear(); } foreach(var attrInfo in AttributesToQuery) { if(!attrInfo.IsList) { continue; } var propertyAlias = attrInfo.Prefix + attrInfo.Attr; if (listPropertyValues.ContainsKey(propertyAlias)) { continue; } var propertyName = ResolvePropertyKey(propertyAlias); PropertyValues values; if (listPropertyValues.ContainsKey(propertyName)) { values = listPropertyValues[propertyName]; } else { values = QueryPropertyValues(propertyName); listPropertyValues.Add(propertyName, values); } if (!listPropertyValues.ContainsKey(propertyAlias)) { listPropertyValues.Add(propertyAlias, values); } } } private PropertyValues QueryPropertyValues(string propertyName) { var res = new PropertyValues(); var assetType = connector.MetaModel.GetAssetType(propertyName); IAttributeDefinition nameDef = null; if (propertyName == "Member") { nameDef = assetType.GetAttributeDefinition("Nickname"); } else { nameDef = assetType.GetAttributeDefinition("Name"); } IAttributeDefinition inactiveDef; assetType.TryGetAttributeDefinition("Inactive", out inactiveDef); var query = new Query(assetType); query.Selection.Add(nameDef); if (inactiveDef != null) { query.Selection.Add(inactiveDef); } /* if(assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) { var filter = new FilterTerm(inactiveDef); filter.Equal("False"); query.Filter = filter; } */ query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending); res.Add(new ValueId()); // which is the aim of this? having a blank item at the begining of the combo? foreach(var asset in connector.Services.Retrieve(query).Assets) { var name = asset.GetAttribute(nameDef).Value as string; var inactive = false; if (inactiveDef != null) { inactive = (bool)asset.GetAttribute(inactiveDef).Value; } res.Add(new ValueId(asset.Oid, name, inactive)); } return res; } #region Localizer public string LocalizerResolve(string key) { try { return connector.Localizer.Resolve(key); } catch(Exception ex) { throw new DataLayerException("Failed to resolve key.", ex); } } public bool TryLocalizerResolve(string key, out string result) { result = null; try { if(connector.Localizer != null) { result = connector.Localizer.Resolve(key); return true; } } catch(V1Exception) { Logger.Debug(string.Format("Failed to resolve localized string by key '{0}'", key)); } return false; } #endregion public bool IsConnected { get { return connector.IsConnected; } } /// <exception cref="KeyNotFoundException">If there are no values for this property.</exception> public PropertyValues GetListPropertyValues(string propertyName) { var propertyKey = ResolvePropertyKey(propertyName); return listPropertyValues.ContainsKey(propertyName) ? listPropertyValues[propertyKey] : null; } public void CommitAsset(IDictionary<Asset, double> efforts, Asset asset) { try { var requiredData = requiredFieldsValidator.Validate(asset); if(requiredData.Count > 0) { var message = requiredFieldsValidator.GetMessageOfUnfilledFieldsList(requiredData, Environment.NewLine, ", "); throw new ValidatorException(message); } } catch(APIException ex) { Logger.Error("Cannot validate required fields.", ex); } connector.Services.Save(asset); CommitEffort(efforts, asset); } /// <summary> /// Commit efforts. /// </summary> /// <param name="efforts">Recorded Effort collection</param> /// <param name="asset">Specific asset to commit related effort value.</param> private void CommitEffort(IDictionary<Asset, double> efforts, Asset asset) { if(!efforts.ContainsKey(asset)) { return; } var effortValue = efforts[asset]; CreateEffort(asset, effortValue); efforts.Remove(asset); } private void CreateEffort(Asset asset, double effortValue) { effortType = connector.MetaModel.GetAssetType("Actual"); var effort = connector.Services.New(effortType, asset.Oid); effort.SetAttributeValue(effortType.GetAttributeDefinition("Value"), effortValue); effort.SetAttributeValue(effortType.GetAttributeDefinition("Date"), DateTime.Now); connector.Services.Save(effort); } public void AddProperty(string attr, string prefix, bool isList) { AttributesToQuery.Add(new AttributeInfo(attr, prefix, isList)); } public void ExecuteOperation(Asset asset, IOperation operation) { connector.Services.ExecuteOperation(operation, asset.Oid); } /// <summary> /// Refreshes data for Asset wrapped by specified Workitem. /// </summary> // TODO refactor public Asset RefreshAsset(Workitem workitem, IList<Asset> containingAssetCollection) { try { var stateDef = workitem.Asset.AssetType.GetAttributeDefinition("AssetState"); var query = new Query(workitem.Asset.Oid.Momentless, false); AddSelection(query, workitem.TypePrefix); query.Selection.Add(stateDef); var newAssets = connector.Services.Retrieve(query); var containedIn = workitem.Parent == null ? containingAssetCollection : workitem.Parent.Asset.Children; if(newAssets.TotalAvaliable != 1) { containedIn.Remove(workitem.Asset); return null; } var newAsset = newAssets.Assets[0]; var newAssetState = (AssetState) newAsset.GetAttribute(stateDef).Value; if(newAssetState == AssetState.Closed) { containedIn.Remove(workitem.Asset); return null; } containedIn[containedIn.IndexOf(workitem.Asset)] = newAsset; newAsset.Children.AddRange(workitem.Asset.Children); return newAsset; } catch(MetaException ex) { Logger.Error("Unable to get workitems.", ex); return null; } catch(WebException ex) { connector.IsConnected = false; Logger.Error("Unable to get workitems.", ex); return null; } catch(Exception ex) { Logger.Error("Unable to get workitems.", ex); return null; } } public Workitem CreateWorkitem(string assetType, Workitem parent, IEntityContainer entityContainer) { var assetFactory = new AssetFactory(this, CurrentProject, LoggerFactory, AttributesToQuery); return WorkitemFactory.CreateWorkitem(assetFactory, assetType, parent, entityContainer); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_LABAddRJ : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiLAB"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListJenisPenjamin(); GetListHubungan(); GetListStatus(); GetListPangkat(); GetListAgama(); GetListPendidikan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); GetNomorRegistrasi(); GetNomorTunggu(); GetListKelompokPemeriksaan(); GetListSatuanKerjaPenjamin(); } } //========= public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPenjamin.Items.Clear(); int i = 0; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkat() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); DataTable dt = myObj.GetList(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgamaPenjamin.Items.Clear(); int i = 0; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgamaPenjamin.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikanPenjamin.Items.Clear(); int i = 0; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikanPenjamin.SelectedIndex = i; i++; } } //========== public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 42;//LAB myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 42;//LAB myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); lblNoRegistrasi.Text = txtNoRegistrasi.Text; } public void GetListKelompokPemeriksaan() { SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan(); myObj.JenisPemeriksaanId = 1;//Laboratorium DataTable dt = myObj.GetListByJenisPemeriksaanId(); cmbKelompokPemeriksaan.Items.Clear(); int i = 0; //cmbKelompokPemeriksaan.Items.Add(""); //cmbKelompokPemeriksaan.Items[i].Text = ""; //cmbKelompokPemeriksaan.Items[i].Value = ""; //i++; foreach (DataRow dr in dt.Rows) { cmbKelompokPemeriksaan.Items.Add(""); cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString(); i++; } cmbKelompokPemeriksaan.SelectedIndex = 0; GetListPemeriksaan(); } public DataSet GetDataPemeriksaan() { DataSet ds = new DataSet(); if (Session["dsLayananLAB"] != null) ds = (DataSet)Session["dsLayananLAB"]; else { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.PoliklinikId = 42;//Polklinik LAB DataTable myData = myObj.SelectAllWPoliklinikIdLogic(); ds.Tables.Add(myData); Session.Add("dsLayananLAB", ds); } return ds; } public void GetListPemeriksaan() { DataSet ds = new DataSet(); ds = GetDataPemeriksaan(); lstRefPemeriksaan.DataTextField = "Nama"; lstRefPemeriksaan.DataValueField = "Id"; DataView dv = ds.Tables[0].DefaultView; dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value; lstRefPemeriksaan.DataSource = dv; lstRefPemeriksaan.DataBind(); } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } if (txtPasienId.Text == "") { lblError.Text = "Data Pasien Belum dipilih !"; return; } int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbStatusPenjamin.SelectedIndex > 0) myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = Int64.Parse(txtPasienId.Text); GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.AsalPasienId = Int64.Parse(txtRegistrasiId.Text); myRJ.PoliklinikId = 42;//LAB myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "") myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Keterangan = txtKeterangan.Text; myRJ.Status = 0;//Baru daftar myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); ////Input Data Layanan SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan(); SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan(); if (lstPemeriksaan.Items.Count > 0) { string[] kellay; string[] Namakellay; DataTable dt; for (int i = 0; i < lstPemeriksaan.Items.Count; i++) { myLayanan.RJLayananId = 0; myLayanan.RawatJalanId = myRJ.RawatJalanId; myLayanan.JenisLayananId = 3; kellay = lstPemeriksaan.Items[i].Value.Split('|'); Namakellay = lstPemeriksaan.Items[i].Text.Split(':'); myLayanan.KelompokLayananId = 2; myLayanan.LayananId = int.Parse(kellay[1]); myLayanan.NamaLayanan = Namakellay[1]; myTarif.Id = int.Parse(kellay[1]); dt = myTarif.GetTarifRIByLayananId(0); if (dt.Rows.Count > 0) myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0; else myLayanan.Tarif = 0; myLayanan.JumlahSatuan = double.Parse("1"); myLayanan.Discount = 0; myLayanan.BiayaTambahan = 0; myLayanan.JumlahTagihan = myLayanan.Tarif; myLayanan.Keterangan = ""; myLayanan.CreatedBy = UserId; myLayanan.CreatedDate = DateTime.Now; myLayanan.Insert(); } } //================= string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("LABView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("LABList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPenjamin.Text = row["Nama"].ToString(); cmbHubungan.SelectedValue = row["HubunganId"].ToString(); txtUmurPenjamin.Text = row["Umur"].ToString(); txtAlamatPenjamin.Text = row["Alamat"].ToString(); txtTeleponPenjamin.Text = row["Telepon"].ToString(); cmbAgamaPenjamin.SelectedValue = row["AgamaId"].ToString(); cmbPendidikanPenjamin.SelectedValue = row["PendidikanId"].ToString(); cmbStatusPenjamin.SelectedValue = row["StatusId"].ToString(); cmbPangkatPenjamin.SelectedValue = row["PangkatId"].ToString(); txtNoKTPPenjamin.Text = row["NoKTP"].ToString(); txtGolDarahPenjamin.Text = row["GolDarah"].ToString(); txtNRPPenjamin.Text = row["NRP"].ToString(); //cmbSatuanKerjaPenjamin.Text = row["Kesatuan"].ToString(); txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString(); txtKeteranganPenjamin.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPerusahaan.Text = row["Nama"].ToString(); txtNamaKontak.Text = row["NamaKontak"].ToString(); txtAlamatPerusahaan.Text = row["Alamat"].ToString(); txtTeleponPerusahaan.Text = row["Telepon"].ToString(); txtFAXPerusahaan.Text = row["Fax"].ToString(); txtKeteranganPerusahaan.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void btnSearch_Click(object sender, EventArgs e) { GetListPasien(); EmptyFormPasien(); } public DataView GetResultSearch() { DataSet ds = new DataSet(); DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.JenisPoliklinikId = 1; // RawatJalan if (txtNoRMSearch.Text != "") myObj.NoRM = txtNoRMSearch.Text; if (txtNamaSearch.Text != "") myObj.Nama = txtNamaSearch.Text; if (txtNRPSearch.Text != "") myObj.NRP = txtNRPSearch.Text; myData = myObj.SelectAllFilter(); DataView dv = myData.DefaultView; return dv; } public void GetListPasien() { GridViewPasien.SelectedIndex = -1; // Re-binds the grid GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); } protected void GridViewPasien_SelectedIndexChanged(object sender, EventArgs e) { Int64 RawatJalanId = (Int64)GridViewPasien.SelectedValue; UpdateFormPasien(RawatJalanId); EmptyFormPejamin(); } public void UpdateFormPasien(Int64 RawatJalanId) { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = RawatJalanId; DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtPasienId.Text = row["PasienId"].ToString(); txtRawatJalanId.Text = row["RawatJalanId"].ToString(); txtRegistrasiId.Text = row["RegistrasiId"].ToString(); lblNoRMHeader.Text = row["NoRM"].ToString(); lblNoRM.Text = row["NoRM"].ToString(); lblNamaPasienHeader.Text = row["Nama"].ToString(); lblNamaPasien.Text = row["Nama"].ToString(); lblStatus.Text = row["StatusNama"].ToString(); lblPangkat.Text = row["PangkatNama"].ToString(); lblNoAskes.Text = row["NoAskes"].ToString(); lblNoKTP.Text = row["NoKTP"].ToString(); lblGolDarah.Text = row["GolDarah"].ToString(); lblNRP.Text = row["NRP"].ToString(); lblKesatuan.Text = row["Kesatuan"].ToString(); lblTempatLahir.Text = row["TempatLahir"].ToString() == "" ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : row["TempatLahir"].ToString(); lblTanggalLahir.Text = row["TanggalLahir"].ToString() != "" ? ((DateTime)row["TanggalLahir"]).ToString("dd MMMM yyyy"):""; lblAlamat.Text = row["Alamat"].ToString(); lblTelepon.Text = row["Telepon"].ToString(); lblJenisKelamin.Text = row["JenisKelamin"].ToString(); lblStatusPerkawinan.Text = row["StatusPerkawinanNama"].ToString(); lblAgama.Text = row["AgamaNama"].ToString(); lblPendidikan.Text = row["PendidikanNama"].ToString(); lblPekerjaan.Text = row["Pekerjaan"].ToString(); lblAlamatKantor.Text = row["AlamatKantor"].ToString(); lblTeleponKantor.Text = row["TeleponKantor"].ToString(); lblKeterangan.Text = row["Keterangan"].ToString(); if (row["PoliklinikNama"].ToString() != "") txtKeterangan.Text = "Pasien Rawa Jalan: Dari " + row["PoliklinikNama"].ToString(); if (row["DokterNama"].ToString() != "") txtKeterangan.Text += " Dokter " + row["DokterNama"].ToString(); } else { EmptyFormPasien(); } SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.PasienId = Int64.Parse(txtPasienId.Text); DataTable dTbl = myReg.SelectOne_ByPasienId(); if (dTbl.Rows.Count > 0) { DataRow rs = dTbl.Rows[0]; txtPenjaminId.Text = rs["PenjaminId"].ToString(); } } public void EmptyFormPasien() { txtPasienId.Text = ""; txtRawatJalanId.Text = ""; txtRegistrasiId.Text = ""; lblNoRMHeader.Text = ""; lblNoRM.Text = ""; lblNamaPasien.Text = ""; lblNamaPasienHeader.Text = ""; lblStatus.Text = ""; lblPangkat.Text = ""; lblNoAskes.Text = ""; lblNoKTP.Text = ""; lblGolDarah.Text = ""; lblNRP.Text = ""; lblKesatuan.Text = ""; lblTempatLahir.Text = ""; lblTanggalLahir.Text = ""; lblAlamat.Text = ""; lblTelepon.Text = ""; lblJenisKelamin.Text = ""; lblStatusPerkawinan.Text = ""; lblAgama.Text = ""; lblPendidikan.Text = ""; lblPekerjaan.Text = ""; lblAlamatKantor.Text = ""; lblTeleponKantor.Text = ""; lblKeterangan.Text = ""; txtKeterangan.Text = ""; } protected void GridViewPasien_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridViewPasien.SelectedIndex = -1; GridViewPasien.PageIndex = e.NewPageIndex; GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); EmptyFormPasien(); } protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e) { GetListPemeriksaan(); } protected void btnAddPemeriksaan_Click(object sender, EventArgs e) { if (lstRefPemeriksaan.SelectedIndex != -1) { int i = lstPemeriksaan.Items.Count; bool exist = false; string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; for (int j = 0; j < i; j++) { if (lstPemeriksaan.Items[j].Value == selectValue) { exist = true; break; } } if (!exist) { ListItem newItem = new ListItem(); newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text; newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; lstPemeriksaan.Items.Add(newItem); } } } protected void btnRemovePemeriksaan_Click(object sender, EventArgs e) { if (lstPemeriksaan.SelectedIndex != -1) { lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex); } } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerjaPenjamin.SelectedIndex = i; i++; } } public void EmptyFormPejamin() { txtNamaPenjamin.Text = ""; cmbHubungan.SelectedValue = ""; txtUmurPenjamin.Text = ""; txtAlamatPenjamin.Text = ""; txtTeleponPenjamin.Text = ""; cmbAgamaPenjamin.SelectedIndex = 0; cmbPendidikanPenjamin.SelectedIndex = 0; cmbStatusPenjamin.SelectedIndex = 0; //cmbPangkatPenjamin.SelectedIndex = 0; txtNoKTPPenjamin.Text = ""; txtGolDarahPenjamin.Text = ""; txtNRPPenjamin.Text = ""; cmbSatuanKerjaPenjamin.SelectedIndex = 0; txtAlamatKesatuanPenjamin.Text = ""; txtKeteranganPenjamin.Text = ""; txtNamaPerusahaan.Text = ""; txtNamaKontak.Text = ""; txtAlamatPerusahaan.Text = ""; txtTeleponPerusahaan.Text = ""; txtFAXPerusahaan.Text = ""; txtKeteranganPerusahaan.Text = ""; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Graphics; using Microsoft.Xna.Framework.Graphics; using FlatRedBall; using Microsoft.Xna.Framework; using FlatRedBall.Content; using FlatRedBall.Content.Scene; using FlatRedBall.IO; using FlatRedBall.Input; using FlatRedBall.Debugging; using FlatRedBall.Math; using TMXGlueLib.DataTypes; namespace FlatRedBall.TileGraphics { public enum SortAxis { None, X, Y } public class MapDrawableBatch : PositionedObject, IVisible, IDrawableBatch { #region Fields protected Tileset mTileset; #region XML Docs /// <summary> /// The effect used to draw. Shared by all instances for performance reasons /// </summary> #endregion private static BasicEffect mBasicEffect; private static AlphaTestEffect mAlphaTestEffect; /// <summary> /// The vertices used to draw the map. /// </summary> /// <remarks> /// Coordinate order is: /// 3 2 /// /// 0 1 /// </remarks> protected VertexPositionTexture[] mVertices; protected Texture2D mTexture; #region XML Docs /// <summary> /// The indices to draw the shape /// </summary> #endregion protected int[] mIndices; Dictionary<string, List<int>> mNamedTileOrderedIndexes = new Dictionary<string, List<int>>(); private int mCurrentNumberOfTiles = 0; private SortAxis mSortAxis; #endregion #region Properties public List<TMXGlueLib.DataTypes.NamedValue> Properties { get; private set; } = new List<TMXGlueLib.DataTypes.NamedValue>(); public SortAxis SortAxis { get { return mSortAxis; } set { mSortAxis = value; } } #region XML Docs /// <summary> /// Here we tell the engine if we want this batch /// updated every frame. Since we have no updating to /// do though, we will set this to false /// </summary> #endregion public bool UpdateEveryFrame { get { return true; } } public float RenderingScale { get; set; } public Dictionary<string, List<int>> NamedTileOrderedIndexes { get { return mNamedTileOrderedIndexes; } } public bool Visible { get; set; } public bool ZBuffered { get; set; } public int QuadCount { get { return mVertices.Length / 4; } } public VertexPositionTexture[] Vertices { get { return mVertices; } } public Texture2D Texture { get { return mTexture; } } // Doing these properties this way lets me avoid a computational step of 1 - ParallaxMultiplier in the Update() function // To explain the get & set values, algebra: // if _parallaxMultiplier = 1 - value (set) // then _parallaxMultiplier - 1 = -value // so -(_parallaxMultiplier - 1) = value // thus -_parallaxMultiplier + 1 = value (get) private float _parallaxMultiplierX; public float ParallaxMultiplierX { get { return -_parallaxMultiplierX + 1; } set { _parallaxMultiplierX = 1 - value; } } private float _parallaxMultiplierY; public float ParallaxMultiplierY { get { return -_parallaxMultiplierY + 1; } set { _parallaxMultiplierY = 1 - value; } } #endregion #region Constructor / Initialization // this exists purely for Clone public MapDrawableBatch() { } public MapDrawableBatch(int numberOfTiles, Texture2D texture) : base() { if (texture == null) throw new ArgumentNullException("texture"); Visible = true; InternalInitialize(); mTexture = texture; mVertices = new VertexPositionTexture[4 * numberOfTiles]; mIndices = new int[6 * numberOfTiles]; } #region XML Docs /// <summary> /// Create and initialize all assets /// </summary> #endregion public MapDrawableBatch(int numberOfTiles, int textureTileDimensionWidth, int textureTileDimensionHeight, Texture2D texture) : base() { if (texture == null) throw new ArgumentNullException("texture"); Visible = true; InternalInitialize(); mTexture = texture; mVertices = new VertexPositionTexture[4 * numberOfTiles]; mIndices = new int[6 * numberOfTiles]; mTileset = new Tileset(texture, textureTileDimensionWidth, textureTileDimensionHeight); } //public MapDrawableBatch(int mapWidth, int mapHeight, float mapTileDimension, int textureTileDimension, string tileSetFilename) // : base() //{ // InternalInitialize(); // mTileset = new Tileset(tileSetFilename, textureTileDimension); // mMapWidth = mapWidth; // mMapHeight = mapHeight; // int numberOfTiles = mapWidth * mapHeight; // // the number of vertices is 4 times the number of tiles (each tile gets 4 vertices) // mVertices = new VertexPositionTexture[4 * numberOfTiles]; // // the number of indices is 6 times the number of tiles // mIndices = new short[6 * numberOfTiles]; // for(int i = 0; i < mapHeight; i++) // { // for (int j = 0; j < mapWidth; j++) // { // int currentTile = mapHeight * i + j; // int currentVertex = currentTile * 4; // float xOffset = j * mapTileDimension; // float yOffset = i * mapTileDimension; // int currentIndex = currentTile * 6; // 6 indices per tile // // TEMP // Vector2[] coords = mTileset.GetTextureCoordinateVectorsOfTextureIndex(new Random().Next()%4); // // END TEMP // // create vertices // mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, 0f), coords[0]); // mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + 0f, 0f), coords[1]); // mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + mapTileDimension, 0f), coords[2]); // mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + mapTileDimension, 0f), coords[3]); // // create indices // mIndices[currentIndex + 0] = (short)(currentVertex + 0); // mIndices[currentIndex + 1] = (short)(currentVertex + 1); // mIndices[currentIndex + 2] = (short)(currentVertex + 2); // mIndices[currentIndex + 3] = (short)(currentVertex + 0); // mIndices[currentIndex + 4] = (short)(currentVertex + 2); // mIndices[currentIndex + 5] = (short)(currentVertex + 3); // mCurrentNumberOfTiles++; // } // } // mTexture = FlatRedBallServices.Load<Texture2D>(@"content/tiles"); //} void InternalInitialize() { // We're going to share these because creating effects is slow... // But is this okay if we tombstone? if (mBasicEffect == null) { mBasicEffect = new BasicEffect(FlatRedBallServices.GraphicsDevice); mBasicEffect.VertexColorEnabled = false; mBasicEffect.TextureEnabled = true; } if (mAlphaTestEffect == null) { mAlphaTestEffect = new AlphaTestEffect(FlatRedBallServices.GraphicsDevice); mAlphaTestEffect.Alpha = 1; mAlphaTestEffect.VertexColorEnabled = false; } RenderingScale = 1; } #endregion #region Methods public void AddToManagers() { SpriteManager.AddDrawableBatch(this); //SpriteManager.AddPositionedObject(mMapBatch); } public void AddToManagers(Layer layer) { SpriteManager.AddToLayer(this, layer); } public static MapDrawableBatch FromScnx(string sceneFileName, string contentManagerName, bool verifySameTexturePerLayer) { // TODO: This line crashes when the path is already absolute! string absoluteFileName = FileManager.MakeAbsolute(sceneFileName); // TODO: The exception doesn't make sense when the file type is wrong. SceneSave saveInstance = SceneSave.FromFile(absoluteFileName); int startingIndex = 0; string oldRelativeDirectory = FileManager.RelativeDirectory; FileManager.RelativeDirectory = FileManager.GetDirectory(absoluteFileName); // get the list of sprites from our map file List<SpriteSave> spriteSaveList = saveInstance.SpriteList; // we use the sprites as defined in the scnx file to create and draw the map. MapDrawableBatch mMapBatch = FromSpriteSaves(spriteSaveList, startingIndex, spriteSaveList.Count, contentManagerName, verifySameTexturePerLayer); FileManager.RelativeDirectory = oldRelativeDirectory; // temp //mMapBatch = new MapDrawableBatch(32, 32, 32f, 64, @"content/tiles"); return mMapBatch; } /* This creates a MapDrawableBatch (MDB) from the list of sprites provided to us by the FlatRedBall (FRB) Scene XML (scnx) file. */ public static MapDrawableBatch FromSpriteSaves(List<SpriteSave> spriteSaveList, int startingIndex, int count, string contentManagerName, bool verifySameTexturesPerLayer) { #if DEBUG if (verifySameTexturesPerLayer) { VerifySingleTexture(spriteSaveList, startingIndex, count); } #endif // We got it! We are going to make some assumptions: // First we need the texture. We'll assume all Sprites // use the same texture: // TODO: I (Bryan) really HATE this assumption. But it will work for now. SpriteSave firstSprite = spriteSaveList[startingIndex]; // This is the file name of the texture, but the file name is relative to the .scnx location string textureRelativeToScene = firstSprite.Texture; // so we load the texture Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureRelativeToScene, contentManagerName); if (!MathFunctions.IsPowerOfTwo(texture.Width) || !MathFunctions.IsPowerOfTwo(texture.Height)) { throw new Exception("The dimensions of the texture file " + texture.Name + " are not power of 2!"); } // Assume all the dimensions of the textures are the same. I.e. all tiles use the same texture width and height. // This assumption is safe for Iso and Ortho tile maps. int tileFileDimensionsWidth = 0; int tileFileDimensionsHeight = 0; if (spriteSaveList.Count > startingIndex) { SpriteSave s = spriteSaveList[startingIndex]; // deduce the dimensionality of the tile from the texture coordinates tileFileDimensionsWidth = (int)System.Math.Round((double)((s.RightTextureCoordinate - s.LeftTextureCoordinate) * texture.Width)); tileFileDimensionsHeight = (int)System.Math.Round((double)((s.BottomTextureCoordinate - s.TopTextureCoordinate) * texture.Height)); } // alas, we create the MDB MapDrawableBatch mMapBatch = new MapDrawableBatch(count, tileFileDimensionsWidth, tileFileDimensionsHeight, texture); int lastIndexExclusive = startingIndex + count; for (int i = startingIndex; i < lastIndexExclusive; i++) { SpriteSave spriteSave = spriteSaveList[i]; // We don't want objects within the IDB to have a different Z than the IDB itself // (if possible) because that makes the IDB behave differently when using sorting vs. // the zbuffer. const bool setZTo0 = true; mMapBatch.Paste(spriteSave, setZTo0); } return mMapBatch; } public MapDrawableBatch Clone() { return base.Clone<MapDrawableBatch>(); } // Bring the texture coordinates in to adjust for rendering issues on dx9/ogl public const float CoordinateAdjustment = .00002f; internal static MapDrawableBatch FromReducedLayer(TMXGlueLib.DataTypes.ReducedLayerInfo reducedLayerInfo, LayeredTileMap owner, TMXGlueLib.DataTypes.ReducedTileMapInfo rtmi, string contentManagerName) { int tileDimensionWidth = reducedLayerInfo.TileWidth; int tileDimensionHeight = reducedLayerInfo.TileHeight; float quadWidth = reducedLayerInfo.TileWidth; float quadHeight = reducedLayerInfo.TileHeight; string textureName = reducedLayerInfo.Texture; #if IOS || ANDROID textureName = textureName.ToLowerInvariant(); #endif Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureName, contentManagerName); MapDrawableBatch toReturn = new MapDrawableBatch(reducedLayerInfo.Quads.Count, tileDimensionWidth, tileDimensionHeight, texture); toReturn.Name = reducedLayerInfo.Name; Vector3 position = new Vector3(); Vector2 tileDimensions = new Vector2(quadWidth, quadHeight); IEnumerable<TMXGlueLib.DataTypes.ReducedQuadInfo> quads = null; if (rtmi.NumberCellsWide > rtmi.NumberCellsTall) { quads = reducedLayerInfo.Quads.OrderBy(item => item.LeftQuadCoordinate).ToList(); toReturn.mSortAxis = SortAxis.X; } else { quads = reducedLayerInfo.Quads.OrderBy(item => item.BottomQuadCoordinate).ToList(); toReturn.mSortAxis = SortAxis.Y; } foreach (var quad in quads) { position.X = quad.LeftQuadCoordinate; position.Y = quad.BottomQuadCoordinate; // The Z of the quad should be relative to this layer, not absolute Z values. // A multi-layer map will offset the individual layer Z values, the quads should have a Z of 0. // position.Z = reducedLayerInfo.Z; var textureValues = new Vector4(); // The purpose of CoordinateAdjustment is to bring the texture values "in", to reduce the chance of adjacent // tiles drawing on a given tile quad. If we don't do this, we can get slivers of adjacent colors appearing, causing // lines or grid patterns. // To bring the values "in" we have to consider rotated quads. textureValues.X = CoordinateAdjustment + (float)quad.LeftTexturePixel / (float)texture.Width; // Left textureValues.Y = -CoordinateAdjustment + (float)(quad.LeftTexturePixel + tileDimensionWidth) / (float)texture.Width; // Right textureValues.Z = CoordinateAdjustment + (float)quad.TopTexturePixel / (float)texture.Height; // Top textureValues.W = -CoordinateAdjustment + (float)(quad.TopTexturePixel + tileDimensionHeight) / (float)texture.Height; // Bottom // pad before doing any rotations/flipping const bool pad = true; if (pad) { const float amountToAdd = .0000001f; textureValues.X += amountToAdd; // Left textureValues.Y -= amountToAdd; // Right textureValues.Z += amountToAdd; // Top textureValues.W -= amountToAdd; // Bottom } if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag) { var temp = textureValues.Y; textureValues.Y = textureValues.X; textureValues.X = temp; } if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag) { var temp = textureValues.Z; textureValues.Z = textureValues.W; textureValues.W = temp; } int tileIndex = toReturn.AddTile(position, tileDimensions, //quad.LeftTexturePixel, quad.TopTexturePixel, quad.LeftTexturePixel + tileDimensionWidth, quad.TopTexturePixel + tileDimensionHeight); textureValues); if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag) { toReturn.ApplyDiagonalFlip(tileIndex); } // This was moved to outside of this conversion, to support shaps //if (quad.QuadSpecificProperties != null) //{ // var listToAdd = quad.QuadSpecificProperties.ToList(); // listToAdd.Add(new NamedValue { Name = "Name", Value = quad.Name }); // owner.Properties.Add(quad.Name, listToAdd); //} if (quad.RotationDegrees != 0) { // Tiled rotates clockwise :( var rotationRadians = -MathHelper.ToRadians(quad.RotationDegrees); Vector3 bottomLeftPos = toReturn.Vertices[tileIndex * 4].Position; Vector3 vertPos = toReturn.Vertices[tileIndex * 4 + 1].Position; MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians); toReturn.Vertices[tileIndex * 4 + 1].Position = vertPos; vertPos = toReturn.Vertices[tileIndex * 4 + 2].Position; MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians); toReturn.Vertices[tileIndex * 4 + 2].Position = vertPos; vertPos = toReturn.Vertices[tileIndex * 4 + 3].Position; MathFunctions.RotatePointAroundPoint(bottomLeftPos, ref vertPos, rotationRadians); toReturn.Vertices[tileIndex * 4 + 3].Position = vertPos; } toReturn.RegisterName(quad.Name, tileIndex); } return toReturn; } public void Paste(Sprite sprite) { Paste(sprite, false); } public int Paste(Sprite sprite, bool setZTo0) { // here we have the Sprite's X and Y in absolute coords as well as its texture coords // NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the // TMX->SCNX tool sets all z to zero. // The AddTile method expects the bottom-left corner float x = sprite.X - sprite.ScaleX; float y = sprite.Y - sprite.ScaleY; float z = sprite.Z; if (setZTo0) { z = 0; } float width = 2f * sprite.ScaleX; // w float height = 2f * sprite.ScaleY; // z float topTextureCoordinate = sprite.TopTextureCoordinate; float bottomTextureCoordinate = sprite.BottomTextureCoordinate; float leftTextureCoordinate = sprite.LeftTextureCoordinate; float rightTextureCoordinate = sprite.RightTextureCoordinate; int tileIndex = mCurrentNumberOfTiles; RegisterName(sprite.Name, tileIndex); // add the textured tile to our map so that we may draw it. return AddTile(new Vector3(x, y, z), new Vector2(width, height), new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate)); } public void Paste(SpriteSave spriteSave) { Paste(spriteSave, false); } public int Paste(SpriteSave spriteSave, bool setZTo0) { // here we have the Sprite's X and Y in absolute coords as well as its texture coords // NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the // TMX->SCNX tool sets all z to zero. // The AddTile method expects the bottom-left corner float x = spriteSave.X - spriteSave.ScaleX; float y = spriteSave.Y - spriteSave.ScaleY; float z = spriteSave.Z; if (setZTo0) { z = 0; } float width = 2f * spriteSave.ScaleX; // w float height = 2f * spriteSave.ScaleY; // z float topTextureCoordinate = spriteSave.TopTextureCoordinate; float bottomTextureCoordinate = spriteSave.BottomTextureCoordinate; float leftTextureCoordinate = spriteSave.LeftTextureCoordinate; float rightTextureCoordinate = spriteSave.RightTextureCoordinate; int tileIndex = mCurrentNumberOfTiles; RegisterName(spriteSave.Name, tileIndex); // add the textured tile to our map so that we may draw it. return AddTile(new Vector3(x, y, z), new Vector2(width, height), new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate)); } private static void VerifySingleTexture(List<SpriteSave> spriteSaveList, int startingIndex, int count) { // Every Sprite should either have the same texture if (spriteSaveList.Count != 0) { string texture = spriteSaveList[startingIndex].Texture; for (int i = startingIndex + 1; i < startingIndex + count; i++) { SpriteSave ss = spriteSaveList[i]; if (ss.Texture != texture) { float leftOfSprite = ss.X - ss.ScaleX; float indexX = leftOfSprite / (ss.ScaleX * 2); float topOfSprite = ss.Y + ss.ScaleY; float indexY = (0 - topOfSprite) / (ss.ScaleY * 2); throw new Exception("All Sprites do not have the same texture"); } } } } private void RegisterName(string name, int tileIndex) { int throwaway; if (!string.IsNullOrEmpty(name) && !int.TryParse(name, out throwaway)) { // TEMPORARY: // The tmx converter // names all Sprites with // a number if their name is // not explicitly set. Therefore // we have to ignore those and look // for explicit names (names not numbers). // Will talk to Domenic about this to fix it. if (!mNamedTileOrderedIndexes.ContainsKey(name)) { mNamedTileOrderedIndexes.Add(name, new List<int>()); } mNamedTileOrderedIndexes[name].Add(tileIndex); } } Vector2[] coords = new Vector2[4]; /// <summary> /// Paints a texture on a tile. This method takes the index of the Sprite in the order it was added /// to the MapDrawableBatch, so it supports any configuration including non-rectangular maps and maps with /// gaps. /// </summary> /// <param name="orderedTileIndex">The index of the tile to paint - this matches the index of the tile as it was added.</param> /// <param name="newTextureId"></param> public void PaintTile(int orderedTileIndex, int newTextureId) { int currentVertex = orderedTileIndex * 4; // 4 vertices per tile // Reusing the coords array saves us on allocation mTileset.GetTextureCoordinateVectorsOfTextureIndex(newTextureId, coords); // Coords are // 3 2 // // 0 1 mVertices[currentVertex + 0].TextureCoordinate = coords[0]; mVertices[currentVertex + 1].TextureCoordinate = coords[1]; mVertices[currentVertex + 2].TextureCoordinate = coords[2]; mVertices[currentVertex + 3].TextureCoordinate = coords[3]; } /// <summary> /// Sets the left and top texture coordiantes of the tile represented by orderedTileIndex. The right and bottom texture coordaintes /// are set automatically according to the tileset dimensions. /// </summary> /// <param name="orderedTileIndex">The ordered tile index.</param> /// <param name="textureXCoordinate">The left texture coordiante (in UV coordinates)</param> /// <param name="textureYCoordinate">The top texture coordainte (in UV coordinates)</param> public void PaintTileTextureCoordinates(int orderedTileIndex, float textureXCoordinate, float textureYCoordinate) { int currentVertex = orderedTileIndex * 4; // 4 vertices per tile mTileset.GetCoordinatesForTile(coords, textureXCoordinate, textureYCoordinate); mVertices[currentVertex + 0].TextureCoordinate = coords[0]; mVertices[currentVertex + 1].TextureCoordinate = coords[1]; mVertices[currentVertex + 2].TextureCoordinate = coords[2]; mVertices[currentVertex + 3].TextureCoordinate = coords[3]; } public void PaintTileTextureCoordinates(int orderedTileIndex, float leftCoordinate, float topCoordinate, float rightCoordinate, float bottomCoordinate) { int currentVertex = orderedTileIndex * 4; // 4 vertices per tile // Coords are // 3 2 // // 0 1 mVertices[currentVertex + 0].TextureCoordinate.X = leftCoordinate; mVertices[currentVertex + 0].TextureCoordinate.Y = bottomCoordinate; mVertices[currentVertex + 1].TextureCoordinate.X = rightCoordinate; mVertices[currentVertex + 1].TextureCoordinate.Y = bottomCoordinate; mVertices[currentVertex + 2].TextureCoordinate.X = rightCoordinate; mVertices[currentVertex + 2].TextureCoordinate.Y = topCoordinate; mVertices[currentVertex + 3].TextureCoordinate.X = leftCoordinate; mVertices[currentVertex + 3].TextureCoordinate.Y = topCoordinate; } // Swaps the top-right for the bottom-left verts public void ApplyDiagonalFlip(int orderedTileIndex) { int currentVertex = orderedTileIndex * 4; // 4 vertices per tile // Coords are // 3 2 // // 0 1 var old0 = mVertices[currentVertex + 0].TextureCoordinate; mVertices[currentVertex + 0].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate; mVertices[currentVertex + 2].TextureCoordinate = old0; } public void RotateTextureCoordinatesCounterclockwise(int orderedTileIndex) { int currentVertex = orderedTileIndex * 4; // 4 vertices per tile // Coords are // 3 2 // // 0 1 var old3 = mVertices[currentVertex + 3].TextureCoordinate; mVertices[currentVertex + 3].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate; mVertices[currentVertex + 2].TextureCoordinate = mVertices[currentVertex + 1].TextureCoordinate; mVertices[currentVertex + 1].TextureCoordinate = mVertices[currentVertex + 0].TextureCoordinate; mVertices[currentVertex + 0].TextureCoordinate = old3; } public void GetTextureCoordiantesForOrderedTile(int orderedTileIndex, out float textureX, out float textureY) { // The order is: // 3 2 // // 0 1 // So we want to add 3 to the index to get the top-left vert, then use // the texture coordinates there to get the Vector2 vector = mVertices[(orderedTileIndex * 4) + 3].TextureCoordinate; textureX = vector.X; textureY = vector.Y; } public void GetBottomLeftWorldCoordinateForOrderedTile(int orderedTileIndex, out float x, out float y) { // The order is: // 3 2 // // 0 1 // So we just need to mutiply by 4 and not add anything Vector3 vector = mVertices[(orderedTileIndex * 4)].Position; x = vector.X; y = vector.Y; } /// <summary> /// Adds a tile to the tile map /// </summary> /// <param name="bottomLeftPosition"></param> /// <param name="dimensions"></param> /// <param name="texture"> /// 4 points defining the boundaries in the texture for the tile. /// (X = left, Y = right, Z = top, W = bottom) /// </param> public int AddTile(Vector3 bottomLeftPosition, Vector2 dimensions, Vector4 texture) { int toReturn = mCurrentNumberOfTiles; int currentVertex = mCurrentNumberOfTiles * 4; int currentIndex = mCurrentNumberOfTiles * 6; // 6 indices per tile (there are mVertices.Length/4 tiles) float xOffset = bottomLeftPosition.X; float yOffset = bottomLeftPosition.Y; float zOffset = bottomLeftPosition.Z; float width = dimensions.X; float height = dimensions.Y; // create vertices mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, zOffset), new Vector2(texture.X, texture.W)); mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + 0f, zOffset), new Vector2(texture.Y, texture.W)); mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + height, zOffset), new Vector2(texture.Y, texture.Z)); mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + height, zOffset), new Vector2(texture.X, texture.Z)); // create indices mIndices[currentIndex + 0] = currentVertex + 0; mIndices[currentIndex + 1] = currentVertex + 1; mIndices[currentIndex + 2] = currentVertex + 2; mIndices[currentIndex + 3] = currentVertex + 0; mIndices[currentIndex + 4] = currentVertex + 2; mIndices[currentIndex + 5] = currentVertex + 3; mCurrentNumberOfTiles++; return toReturn; } /// <summary> /// Add a tile to the map /// </summary> /// <param name="bottomLeftPosition"></param> /// <param name="tileDimensions"></param> /// <param name="textureTopLeftX">Top left X coordinate in the core texture</param> /// <param name="textureTopLeftY">Top left Y coordinate in the core texture</param> /// <param name="textureBottomRightX">Bottom right X coordinate in the core texture</param> /// <param name="textureBottomRightY">Bottom right Y coordinate in the core texture</param> public int AddTile(Vector3 bottomLeftPosition, Vector2 tileDimensions, int textureTopLeftX, int textureTopLeftY, int textureBottomRightX, int textureBottomRightY) { // Form vector4 for AddTile overload var textureValues = new Vector4(); textureValues.X = (float)textureTopLeftX / (float)mTexture.Width; // Left textureValues.Y = (float)textureBottomRightX / (float)mTexture.Width; // Right textureValues.Z = (float)textureTopLeftY / (float)mTexture.Height; // Top textureValues.W = (float)textureBottomRightY / (float)mTexture.Height; // Bottom return AddTile(bottomLeftPosition, tileDimensions, textureValues); } #region XML Docs /// <summary> /// Custom drawing technique - sets graphics states and /// draws the custom shape /// </summary> /// <param name="camera">The currently drawing camera</param> #endregion public void Draw(Camera camera) { ////////////////////Early Out/////////////////// if (!AbsoluteVisible) { return; } if (mVertices.Length == 0) { return; } //////////////////End Early Out///////////////// int firstVertIndex; int lastVertIndex; int indexStart; int numberOfTriangles; GetRenderingIndexValues(camera, out firstVertIndex, out lastVertIndex, out indexStart, out numberOfTriangles); if (numberOfTriangles != 0) { TextureAddressMode oldTextureAddressMode; Effect effectTouse = PrepareRenderingStates(camera, out oldTextureAddressMode); foreach (EffectPass pass in effectTouse.CurrentTechnique.Passes) { // Start each pass pass.Apply(); int numberVertsToDraw = lastVertIndex - firstVertIndex; // Right now this uses the (slower) DrawUserIndexedPrimitives // It could use DrawIndexedPrimitives instead for much faster performance, // but to do that we'd have to keep VB's around and make sure to re-create them // whenever the graphics device is lost. FlatRedBallServices.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>( PrimitiveType.TriangleList, mVertices, firstVertIndex, numberVertsToDraw, mIndices, indexStart, numberOfTriangles); } Renderer.TextureAddressMode = oldTextureAddressMode; if (ZBuffered) { FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; } } } private Effect PrepareRenderingStates(Camera camera, out TextureAddressMode oldTextureAddressMode) { // Set graphics states FlatRedBallServices.GraphicsDevice.RasterizerState = RasterizerState.CullNone; FlatRedBall.Graphics.Renderer.BlendOperation = BlendOperation.Regular; Effect effectTouse = null; if (ZBuffered) { FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.Default; camera.SetDeviceViewAndProjection(mAlphaTestEffect, false); mAlphaTestEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix; mAlphaTestEffect.Texture = mTexture; effectTouse = mAlphaTestEffect; } else { camera.SetDeviceViewAndProjection(mBasicEffect, false); mBasicEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix; mBasicEffect.Texture = mTexture; effectTouse = mBasicEffect; } // We won't need to use any other kind of texture // address mode besides clamp, and clamp is required // on the "Reach" profile when the texture is not power // of two. Let's set it to clamp here so that we don't crash // on non-power-of-two textures. oldTextureAddressMode = Renderer.TextureAddressMode; Renderer.TextureAddressMode = TextureAddressMode.Clamp; return effectTouse; } private void GetRenderingIndexValues(Camera camera, out int firstVertIndex, out int lastVertIndex, out int indexStart, out int numberOfTriangles) { firstVertIndex = 0; lastVertIndex = mVertices.Length; float tileWidth = mVertices[1].Position.X - mVertices[0].Position.X; if (mSortAxis == SortAxis.X) { float minX = camera.AbsoluteLeftXEdgeAt(this.Z); float maxX = camera.AbsoluteRightXEdgeAt(this.Z); minX -= this.X; maxX -= this.X; firstVertIndex = GetFirstAfterX(mVertices, minX - tileWidth); lastVertIndex = GetFirstAfterX(mVertices, maxX) + 4; } else if (mSortAxis == SortAxis.Y) { float minY = camera.AbsoluteBottomYEdgeAt(this.Z); float maxY = camera.AbsoluteTopYEdgeAt(this.Z); minY -= this.Y; maxY -= this.Y; firstVertIndex = GetFirstAfterY(mVertices, minY - tileWidth); lastVertIndex = GetFirstAfterY(mVertices, maxY) + 4; } lastVertIndex = System.Math.Min(lastVertIndex, mVertices.Length); indexStart = 0;// (firstVertIndex * 3) / 2; int indexEndExclusive = ((lastVertIndex - firstVertIndex) * 3) / 2; numberOfTriangles = (indexEndExclusive - indexStart) / 3; } public static int GetFirstAfterX(VertexPositionTexture[] list, float xGreaterThan) { int min = 0; int originalMax = list.Length / 4; int max = list.Length / 4; int mid = (max + min) / 2; while (min < max) { mid = (max + min) / 2; float midItem = list[mid * 4].Position.X; if (midItem > xGreaterThan) { // Is this the last one? // Not sure why this is here, because if we have just 2 items, // this will always return a value of 1 instead //if (mid * 4 + 4 >= list.Length) //{ // return mid * 4; //} // did we find it? if (mid > 0 && list[(mid - 1) * 4].Position.X <= xGreaterThan) { return mid * 4; } else { max = mid - 1; } } else if (midItem <= xGreaterThan) { if (mid == 0) { return mid * 4; } else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.X > xGreaterThan) { return (mid + 1) * 4; } else { min = mid + 1; } } } if (min == 0) { return 0; } else { return list.Length; } } public static int GetFirstAfterY(VertexPositionTexture[] list, float yGreaterThan) { int min = 0; int originalMax = list.Length / 4; int max = list.Length / 4; int mid = (max + min) / 2; while (min < max) { mid = (max + min) / 2; float midItem = list[mid * 4].Position.Y; if (midItem > yGreaterThan) { // Is this the last one? // See comment in GetFirstAfterX //if (mid * 4 + 4 >= list.Length) //{ // return mid * 4; //} // did we find it? if (mid > 0 && list[(mid - 1) * 4].Position.Y <= yGreaterThan) { return mid * 4; } else { max = mid - 1; } } else if (midItem <= yGreaterThan) { if (mid == 0) { return mid * 4; } else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.Y > yGreaterThan) { return (mid + 1) * 4; } else { min = mid + 1; } } } if (min == 0) { return 0; } else { return list.Length; } } #region XML Docs /// <summary> /// Here we update our batch - but this batch doesn't /// need to be updated /// </summary> #endregion public void Update() { float leftView = Camera.Main.AbsoluteLeftXEdgeAt(0); float topView = Camera.Main.AbsoluteTopYEdgeAt(0); float cameraOffsetX = leftView - CameraOriginX; float cameraOffsetY = topView - CameraOriginY; this.RelativeX = cameraOffsetX * _parallaxMultiplierX; this.RelativeY = cameraOffsetY * _parallaxMultiplierY; this.TimedActivity(TimeManager.SecondDifference, TimeManager.SecondDifferenceSquaredDividedByTwo, TimeManager.LastSecondDifference); // The MapDrawableBatch may be attached to a LayeredTileMap (the container of all layers) // If so, the player may move the LayeredTileMap and expect all contained layers to move along // with it. To allow this, we need to have dependencies updated. We'll do this by simply updating // dependencies here, although I don't know at this point if there's a better way - like if we should // be adding this to the SpriteManager's PositionedObjectList. This is an improvement so we'll do it for // now and revisit this in case there's a problem in the future. this.UpdateDependencies(TimeManager.CurrentTime); } // TODO: I would like to somehow make this a property on the LayeredTileMap, but right now it is easier to put them here public float CameraOriginY { get; set; } public float CameraOriginX { get; set; } IVisible IVisible.Parent { get { return this.Parent as IVisible; } } public bool AbsoluteVisible { get { if (this.Visible) { var parentAsIVisible = this.Parent as IVisible; if (parentAsIVisible == null || IgnoresParentVisibility) { return true; } else { // this is true, so return if the parent is visible: return parentAsIVisible.AbsoluteVisible; } } else { return false; } } } public bool IgnoresParentVisibility { get; set; } #region XML Docs /// <summary> /// Don't call this, instead call SpriteManager.RemoveDrawableBatch /// </summary> #endregion public void Destroy() { this.RemoveSelfFromListsBelongingTo(); } public void MergeOntoThis(IEnumerable<MapDrawableBatch> mapDrawableBatches) { int quadsToAdd = 0; int quadsOnThis = QuadCount; foreach (var mdb in mapDrawableBatches) { quadsToAdd += mdb.QuadCount; } int totalNumberOfVerts = 4 * (this.QuadCount + quadsToAdd); int totalNumberOfIndexes = 6 * (this.QuadCount + quadsToAdd); var oldVerts = mVertices; var oldIndexes = mIndices; mVertices = new VertexPositionTexture[totalNumberOfVerts]; mIndices = new int[totalNumberOfIndexes]; oldVerts.CopyTo(mVertices, 0); oldIndexes.CopyTo(mIndices, 0); int currentQuadIndex = quadsOnThis; int index = 0; foreach (var mdb in mapDrawableBatches) { int startVert = currentQuadIndex * 4; int startIndex = currentQuadIndex * 6; int numberOfIndices = mdb.mIndices.Length; int numberOfNewVertices = mdb.mVertices.Length; mdb.mVertices.CopyTo(mVertices, startVert); mdb.mIndices.CopyTo(mIndices, startIndex); for (int i = startIndex; i < startIndex + numberOfIndices; i++) { mIndices[i] += startVert; } for (int i = startVert; i < startVert + numberOfNewVertices; i++) { mVertices[i].Position.Z += index + 1; } foreach (var kvp in mdb.mNamedTileOrderedIndexes) { string key = kvp.Key; List<int> toAddTo; if (mNamedTileOrderedIndexes.ContainsKey(key)) { toAddTo = mNamedTileOrderedIndexes[key]; } else { toAddTo = new List<int>(); mNamedTileOrderedIndexes[key] = toAddTo; } foreach (var namedIndex in kvp.Value) { toAddTo.Add(namedIndex + currentQuadIndex); } } currentQuadIndex += mdb.QuadCount; index++; } } public void RemoveQuads(IEnumerable<int> quadIndexes) { var vertList = mVertices.ToList(); // Reverse - go from biggest to smallest foreach (var indexToRemove in quadIndexes.Distinct().OrderBy(item => -item)) { // and go from biggest to smallest here too vertList.RemoveAt(indexToRemove * 4 + 3); vertList.RemoveAt(indexToRemove * 4 + 2); vertList.RemoveAt(indexToRemove * 4 + 1); vertList.RemoveAt(indexToRemove * 4 + 0); } mVertices = vertList.ToArray(); // The mNamedTileOrderedIndexes is a dictionary that stores which indexes are stored // with which tiles. For example, the key in the dictionary may be "Lava", in which case // the value is the indexes of the tiles that use the Lava tile. // If we do end up removing any quads, then all following quads will shift, so we need to // adjust the indexes so the naming works correctly List<int> orderedInts = quadIndexes.OrderBy(item => item).Distinct().ToList(); int numberOfRemovals = 0; foreach (var kvp in mNamedTileOrderedIndexes) { var ints = kvp.Value; numberOfRemovals = 0; for (int i = 0; i < ints.Count; i++) { // Nothing left to test, so subtract and move on.... if (numberOfRemovals == orderedInts.Count) { ints[i] -= numberOfRemovals; } else if (ints[i] == orderedInts[numberOfRemovals]) { ints.Clear(); break; } else if (ints[i] < orderedInts[numberOfRemovals]) { ints[i] -= numberOfRemovals; } else { while (numberOfRemovals < orderedInts.Count && ints[i] > orderedInts[numberOfRemovals]) { numberOfRemovals++; } if (numberOfRemovals < orderedInts.Count && ints[i] == orderedInts[numberOfRemovals]) { ints.Clear(); break; } ints[i] -= numberOfRemovals; } } } } #endregion } public static class MapDrawableBatchExtensionMethods { } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ /*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; // Visual Studio Platform using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Package; // Unit Test Framework using Microsoft.VsSDK.UnitTestLibrary; using Microsoft.Samples.VisualStudio.IronPythonConsole; using Microsoft.Samples.VisualStudio.IronPythonInterfaces; namespace Microsoft.Samples.VisualStudio.IronPythonConsole.UnitTest { internal static class MockFactories { private static GenericMockFactory dteFactory; public static GenericMockFactory DTEFactory { get { if (null == dteFactory) { Type[] dteInterfaces = new Type[]{ typeof(EnvDTE._DTE), }; dteFactory = new GenericMockFactory("MockDTE", dteInterfaces); } return dteFactory; } } private static GenericMockFactory engineFactory; public static GenericMockFactory EngineFactory { get { if (null == engineFactory) { Type[] interfaces = new Type[] { typeof(IEngine) }; engineFactory = new GenericMockFactory("EngineMock", interfaces); } return engineFactory; } } public static BaseMock CreateStandardEngine() { BaseMock mock = EngineFactory.GetInstance(); mock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IEngine), "get_Version"), new object[] { new Version(1, 1, 1) }); return mock; } private static GenericMockFactory engineProviderFactory; public static GenericMockFactory EngineProviderFactory { get { if (null == engineProviderFactory) { Type[] interfaces = new Type[] { typeof(IPythonEngineProvider) }; engineProviderFactory = new GenericMockFactory("EngineProviderMock", interfaces); } return engineProviderFactory; } } private static GenericMockFactory textBufferFactory; public static GenericMockFactory TextBufferFactory { get { if (null == textBufferFactory) { Type[] textBufferInterfaces = new Type[] { typeof(IVsTextLines), typeof(IObjectWithSite), typeof(IVsTextColorState), typeof(IVsExpansion), typeof(IConnectionPointContainer) }; textBufferFactory = new GenericMockFactory("EmptyTextLinesMock", textBufferInterfaces); } return textBufferFactory; } } private static void CreateMarkerCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; IVsTextLineMarker[] markers = (IVsTextLineMarker[])args.GetParameter(6); BaseMock markerMock = (BaseMock)mock["LineMarker"]; TextSpan span = new TextSpan(); span.iStartLine = (int)args.GetParameter(1); span.iStartIndex = (int)args.GetParameter(2); span.iEndLine = (int)args.GetParameter(3); span.iEndIndex = (int)args.GetParameter(4); markerMock["Span"] = span; markers[0] = (IVsTextLineMarker)markerMock; args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } private static void StandardMarkerResetSpanCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; TextSpan span = new TextSpan(); span.iStartLine = (int)args.GetParameter(0); span.iStartIndex = (int)args.GetParameter(1); span.iEndLine = (int)args.GetParameter(2); span.iEndIndex = (int)args.GetParameter(3); mock["Span"] = span; args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } private static void StandardMarkerGetCurrentSpanCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; TextSpan[] spans = (TextSpan[])args.GetParameter(0); spans[0] = (TextSpan)mock["Span"]; args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } public static BaseMock CreateBufferWithMarker() { BaseMock bufferMock = TextBufferFactory.GetInstance(); BaseMock markerMock = TextLineMarkerFactory.GetInstance(); markerMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLineMarker).FullName, "ResetSpan"), new EventHandler<CallbackArgs>(StandardMarkerResetSpanCallback)); markerMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLineMarker).FullName, "GetCurrentSpan"), new EventHandler<CallbackArgs>(StandardMarkerGetCurrentSpanCallback)); bufferMock["LineMarker"] = markerMock; bufferMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "CreateLineMarker"), new EventHandler<CallbackArgs>(CreateMarkerCallback)); return bufferMock; } private static GenericMockFactory textLineMarkerFactory; public static GenericMockFactory TextLineMarkerFactory { get { if (null == textLineMarkerFactory) { textLineMarkerFactory = new GenericMockFactory("EmptyTextMarker", new Type[] { typeof(IVsTextLineMarker) }); } return textLineMarkerFactory; } } private static GenericMockFactory textViewFactory; public static GenericMockFactory TextViewFactory { get { if (null == textViewFactory) { Type[] textViewInterfaces = new Type[] { typeof(IVsTextView), typeof(IVsWindowPane), typeof(IObjectWithSite), typeof(IConnectionPointContainer) }; textViewFactory = new GenericMockFactory("EmptyTextViewMock", textViewInterfaces); } return textViewFactory; } } private static GenericMockFactory uiShellFactory; public static GenericMockFactory UIShellFactory { get { if (null == uiShellFactory) { uiShellFactory = new GenericMockFactory("EmptyUISHellMock", new Type[] { typeof(IVsUIShell) }); } return uiShellFactory; } } private static GenericMockFactory windowFrameFactory; public static GenericMockFactory WindowFrameFactory { get { if (null == windowFrameFactory) { windowFrameFactory = new GenericMockFactory("EmptyWindowFrameMock", new Type[] { typeof(IVsWindowFrame) }); } return windowFrameFactory; } } private static GenericMockFactory consoleTextFactory; public static GenericMockFactory ConsoleTextFactory { get { if (null == consoleTextFactory) { consoleTextFactory = new GenericMockFactory("EmptyConsoleTextMock", new Type[] { typeof(IConsoleText) }); } return consoleTextFactory; } } private static GenericMockFactory scannerFactory; public static GenericMockFactory ScannerFactory { get { if (null == scannerFactory) { scannerFactory = new GenericMockFactory("EmptyScannerMock", new Type[] { typeof(IScanner) }); } return scannerFactory; } } private static GenericMockFactory methodTipFactory; public static GenericMockFactory MethodTipFactory { get { if (null == methodTipFactory) { methodTipFactory = new GenericMockFactory("EmptyMethodTipWindowMock", new Type[] { typeof(IVsMethodTipWindow) }); } return methodTipFactory; } } private static GenericMockFactory expansionManagerFactory; public static GenericMockFactory ExpansionManagerFactory { get { if (null == expansionManagerFactory) { Type[] interfaces = new Type[] { typeof(IVsExpansionManager), typeof(IConnectionPointContainer) }; expansionManagerFactory = new GenericMockFactory("EmptyExpansionManager", interfaces); } return expansionManagerFactory; } } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[] _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access) : this(handle, access, true, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) : this(handle, access, ownsHandle, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) : this(handle, access, ownsHandle, bufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync) { SafeFileHandle safeHandle = new SafeFileHandle(handle, ownsHandle: ownsHandle); try { ValidateAndInitFromHandle(safeHandle, access, bufferSize, isAsync); } catch { // We don't want to take ownership of closing passed in handles // *unless* the constructor completes successfully. GC.SuppressFinalize(safeHandle); // This would also prevent Close from being called, but is unnecessary // as we've removed the object from the finalizer queue. // // safeHandle.SetHandleAsInvalid(); throw; } // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = safeHandle; } public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } private void ValidateAndInitFromHandle(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _exposedHandle = true; _bufferLength = bufferSize; InitFromHandle(handle, access, isAsync); } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { ValidateAndInitFromHandle(handle, access, bufferSize, isAsync); // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = handle; } public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null; throw; } } private static bool GetDefaultIsAsync(SafeFileHandle handle) { // This will eventually get more complicated as we can actually check the underlying handle type on Windows return handle.IsAsync.HasValue ? handle.IsAsync.Value : false; } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API 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 virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <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(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(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 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(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual 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 (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <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 && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(_fileHandle, 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>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // 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>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); 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(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; /// <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); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <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() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(_fileHandle, rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } private int ReadByteCore() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); _readLength = ReadNative(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } private void WriteByteCore(byte value) { 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 (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!IsAsync) return base.BeginRead(array, offset, numBytes, callback, state); else return TaskToApm.Begin(ReadAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (!IsAsync) return base.BeginWrite(array, offset, numBytes, callback, state); else return TaskToApm.Begin(WriteAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) return base.EndRead(asyncResult); else return TaskToApm.End<int>(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) base.EndWrite(asyncResult); else TaskToApm.End(asyncResult); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Session Hijacking Event Store ///<para>SObject Name: SessionHijackingEventStore</para> ///<para>Custom Object: False</para> ///</summary> public class SfSessionHijackingEventStore : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "SessionHijackingEventStore"; } } ///<summary> /// Session Hijacking Event Store ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Event Name /// <para>Name: SessionHijackingEventNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "sessionHijackingEventNumber")] [Updateable(false), Createable(false)] public string SessionHijackingEventNumber { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Event ID /// <para>Name: EventIdentifier</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "eventIdentifier")] [Updateable(false), Createable(false)] public string EventIdentifier { get; set; } ///<summary> /// User ID /// <para>Name: UserId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "userId")] [Updateable(false), Createable(false)] public string UserId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: User</para> ///</summary> [JsonProperty(PropertyName = "user")] [Updateable(false), Createable(false)] public SfUser User { get; set; } ///<summary> /// Username /// <para>Name: Username</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "username")] [Updateable(false), Createable(false)] public string Username { get; set; } ///<summary> /// Event Date /// <para>Name: EventDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "eventDate")] [Updateable(false), Createable(false)] public DateTimeOffset? EventDate { get; set; } ///<summary> /// Session Key /// <para>Name: SessionKey</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sessionKey")] [Updateable(false), Createable(false)] public string SessionKey { get; set; } ///<summary> /// Login Key /// <para>Name: LoginKey</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "loginKey")] [Updateable(false), Createable(false)] public string LoginKey { get; set; } ///<summary> /// Source IP Address /// <para>Name: SourceIp</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sourceIp")] [Updateable(false), Createable(false)] public string SourceIp { get; set; } ///<summary> /// Transaction Security Policy ID /// <para>Name: PolicyId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "policyId")] [Updateable(false), Createable(false)] public string PolicyId { get; set; } ///<summary> /// ReferenceTo: TransactionSecurityPolicy /// <para>RelationshipName: Policy</para> ///</summary> [JsonProperty(PropertyName = "policy")] [Updateable(false), Createable(false)] public SfTransactionSecurityPolicy Policy { get; set; } ///<summary> /// Policy Outcome /// <para>Name: PolicyOutcome</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "policyOutcome")] [Updateable(false), Createable(false)] public string PolicyOutcome { get; set; } ///<summary> /// Evaluation Time /// <para>Name: EvaluationTime</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "evaluationTime")] [Updateable(false), Createable(false)] public double? EvaluationTime { get; set; } ///<summary> /// Score /// <para>Name: Score</para> /// <para>SF Type: double</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "score")] [Updateable(false), Createable(false)] public double? Score { get; set; } ///<summary> /// Current IP Address /// <para>Name: CurrentIp</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "currentIp")] [Updateable(false), Createable(false)] public string CurrentIp { get; set; } ///<summary> /// Previous IP Address /// <para>Name: PreviousIp</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "previousIp")] [Updateable(false), Createable(false)] public string PreviousIp { get; set; } ///<summary> /// Current Platform /// <para>Name: CurrentPlatform</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "currentPlatform")] [Updateable(false), Createable(false)] public string CurrentPlatform { get; set; } ///<summary> /// Previous Platform /// <para>Name: PreviousPlatform</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "previousPlatform")] [Updateable(false), Createable(false)] public string PreviousPlatform { get; set; } ///<summary> /// Current Screen /// <para>Name: CurrentScreen</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "currentScreen")] [Updateable(false), Createable(false)] public string CurrentScreen { get; set; } ///<summary> /// Previous Screen /// <para>Name: PreviousScreen</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "previousScreen")] [Updateable(false), Createable(false)] public string PreviousScreen { get; set; } ///<summary> /// Current Window /// <para>Name: CurrentWindow</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "currentWindow")] [Updateable(false), Createable(false)] public string CurrentWindow { get; set; } ///<summary> /// Previous Window /// <para>Name: PreviousWindow</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "previousWindow")] [Updateable(false), Createable(false)] public string PreviousWindow { get; set; } ///<summary> /// Current User Agent /// <para>Name: CurrentUserAgent</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "currentUserAgent")] [Updateable(false), Createable(false)] public string CurrentUserAgent { get; set; } ///<summary> /// Previous User Agent /// <para>Name: PreviousUserAgent</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "previousUserAgent")] [Updateable(false), Createable(false)] public string PreviousUserAgent { get; set; } ///<summary> /// Event Data /// <para>Name: SecurityEventData</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "securityEventData")] [Updateable(false), Createable(false)] public string SecurityEventData { get; set; } ///<summary> /// Summary /// <para>Name: Summary</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "summary")] [Updateable(false), Createable(false)] public string Summary { get; set; } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace VSSolutionBuilder { /// <summary> /// Class representing the builder meta data. /// Although this is project related data, it needs to be named after the builder /// </summary> class VSSolutionMeta : Bam.Core.IBuildModeMetaData { /// <summary> /// Pre-execute step /// </summary> public static void PreExecution() { Bam.Core.Graph.Instance.MetaData = new VSSolution(); } private static string PrettyPrintXMLDoc( System.Xml.XmlDocument document) { var content = new System.Text.StringBuilder(); var settings = new System.Xml.XmlWriterSettings { Indent = true, NewLineChars = System.Environment.NewLine, Encoding = new System.Text.UTF8Encoding(false) // no BOM }; using (var writer = System.Xml.XmlWriter.Create(content, settings)) { document.Save(writer); } return content.ToString(); } private static bool AreTextFilesIdentical( string targetPath, string tempPath) { var targetSize = new System.IO.FileInfo(targetPath).Length; var tempSize = new System.IO.FileInfo(targetPath).Length; if (targetSize != tempSize) { return false; } using (System.IO.TextReader targetReader = new System.IO.StreamReader(targetPath)) { using (System.IO.TextReader tempReader = new System.IO.StreamReader(tempPath)) { var targetContents = targetReader.ReadToEnd(); var tempContents = tempReader.ReadToEnd(); if (0 != System.String.Compare(targetContents, tempContents, false)) { return false; } } } return true; } private static void WriteXMLIfDifferent( string targetPath, System.Xml.XmlWriterSettings settings, System.Xml.XmlDocument document) { var targetExists = System.IO.File.Exists(targetPath); var writePath = targetExists ? Bam.Core.IOWrapper.CreateTemporaryFile() : targetPath; using (var xmlwriter = System.Xml.XmlWriter.Create(writePath, settings)) { document.WriteTo(xmlwriter); } Bam.Core.Log.DebugMessage(PrettyPrintXMLDoc(document)); if (targetExists) { if (AreTextFilesIdentical(targetPath, writePath)) { // delete temporary System.IO.File.Delete(writePath); } else { Bam.Core.Log.DebugMessage($"\tXML has changed, moving {writePath} to {targetPath}"); System.IO.File.Delete(targetPath); System.IO.File.Move(writePath, targetPath); } } } private static void WriteSolutionFileIfDifferent( string targetPath, System.Text.StringBuilder contents) { var targetExists = System.IO.File.Exists(targetPath); var writePath = targetExists ? Bam.Core.IOWrapper.CreateTemporaryFile() : targetPath; using (var writer = new System.IO.StreamWriter(writePath)) { writer.Write(contents); } Bam.Core.Log.DebugMessage(contents.ToString()); if (targetExists) { if (AreTextFilesIdentical(targetPath, writePath)) { // delete temporary System.IO.File.Delete(writePath); } else { Bam.Core.Log.DebugMessage($"\tText has changed, moving {writePath} to {targetPath}"); System.IO.File.Delete(targetPath); System.IO.File.Move(writePath, targetPath); } } } /// <summary> /// Post execute step. /// </summary> public static void PostExecution() { var graph = Bam.Core.Graph.Instance; var solution = graph.MetaData as VSSolution; if (0 == solution.Projects.Count()) { throw new Bam.Core.Exception("No projects were generated"); } var xmlWriterSettings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = false, Encoding = new System.Text.UTF8Encoding(false), // no BOM (Byte Ordering Mark) NewLineChars = System.Environment.NewLine, Indent = true }; foreach (var project in solution.Projects) { var projectPathDir = System.IO.Path.GetDirectoryName(project.ProjectPath); Bam.Core.IOWrapper.CreateDirectoryIfNotExists(projectPathDir); WriteXMLIfDifferent(project.ProjectPath, xmlWriterSettings, project.Serialize()); WriteXMLIfDifferent(project.ProjectPath + ".filters", xmlWriterSettings, project.Filter.Serialize()); WriteXMLIfDifferent(project.ProjectPath + ".user", xmlWriterSettings, project.SerializeUserSettings()); } var solutionPathTS = Bam.Core.TokenizedString.Create("$(buildroot)/$(masterpackagename).sln", null); solutionPathTS.Parse(); var solutionPath = solutionPathTS.ToString(); WriteSolutionFileIfDifferent(solutionPath, solution.Serialize(solutionPath)); Bam.Core.Log.Info($"Successfully created Visual Studio solution for package '{graph.MasterPackage.Name}'"); Bam.Core.Log.Info($"\t{solutionPath}"); } Bam.Core.TokenizedString Bam.Core.IBuildModeMetaData.ModuleOutputDirectory( Bam.Core.Module currentModule, Bam.Core.Module encapsulatingModule) { var outputDir = System.IO.Path.Combine(encapsulatingModule.GetType().Name, currentModule.BuildEnvironment.Configuration.ToString()); var moduleSubDir = currentModule.CustomOutputSubDirectory; if (null != moduleSubDir) { outputDir = System.IO.Path.Combine(outputDir, moduleSubDir); } return Bam.Core.TokenizedString.CreateVerbatim(outputDir); } bool Bam.Core.IBuildModeMetaData.PublishBesideExecutable { get { return true; } } bool Bam.Core.IBuildModeMetaData.CanCreatePrebuiltProjectForAssociatedFiles { get { return true; } } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { internal delegate void WriteMapDelegate( TextWriter writer, object oMap, WriteObjectDelegate writeKeyFn, WriteObjectDelegate writeValueFn); internal static class WriteDictionary<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); internal class MapKey { internal Type KeyType; internal Type ValueType; public MapKey(Type keyType, Type valueType) { KeyType = keyType; ValueType = valueType; } public bool Equals(MapKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.KeyType, KeyType) && Equals(other.ValueType, ValueType); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(MapKey)) return false; return Equals((MapKey)obj); } public override int GetHashCode() { unchecked { return ((KeyType != null ? KeyType.GetHashCode() : 0) * 397) ^ (ValueType != null ? ValueType.GetHashCode() : 0); } } } static Dictionary<MapKey, WriteMapDelegate> CacheFns = new Dictionary<MapKey, WriteMapDelegate>(); public static Action<TextWriter, object, WriteObjectDelegate, WriteObjectDelegate> GetWriteGenericDictionary(Type keyType, Type valueType) { WriteMapDelegate writeFn; var mapKey = new MapKey(keyType, valueType); if (CacheFns.TryGetValue(mapKey, out writeFn)) return writeFn.Invoke; var genericType = typeof(ToStringDictionaryMethods<,,>).MakeGenericType(keyType, valueType, typeof(TSerializer)); var mi = genericType.GetMethod("WriteIDictionary", BindingFlags.Static | BindingFlags.Public); writeFn = (WriteMapDelegate)Delegate.CreateDelegate(typeof(WriteMapDelegate), mi); Dictionary<MapKey, WriteMapDelegate> snapshot, newCache; do { snapshot = CacheFns; newCache = new Dictionary<MapKey, WriteMapDelegate>(CacheFns); newCache[mapKey] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref CacheFns, newCache, snapshot), snapshot)); return writeFn.Invoke; } public static void WriteIDictionary(TextWriter writer, object oMap) { WriteObjectDelegate writeKeyFn = null; WriteObjectDelegate writeValueFn = null; writer.Write(JsWriter.MapStartChar); var encodeMapKey = false; var map = (IDictionary)oMap; var ranOnce = false; foreach (var key in map.Keys) { var dictionaryValue = map[key]; var isNull = (dictionaryValue == null); if (isNull && !Serializer.IncludeNullValues) continue; if (writeKeyFn == null) { var keyType = key.GetType(); writeKeyFn = Serializer.GetWriteFn(keyType); encodeMapKey = Serializer.GetTypeInfo(keyType).EncodeMapKey; } if (writeValueFn == null) writeValueFn = Serializer.GetWriteFn(dictionaryValue.GetType()); JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); JsState.WritingKeyCount++; JsState.IsWritingValue = false; if (encodeMapKey) { JsState.IsWritingValue = true; //prevent ""null"" writer.Write(JsWriter.QuoteChar); writeKeyFn(writer, key); writer.Write(JsWriter.QuoteChar); } else { writeKeyFn(writer, key); } JsState.WritingKeyCount--; writer.Write(JsWriter.MapKeySeperator); if (isNull) { writer.Write(JsonUtils.Null); } else { JsState.IsWritingValue = true; writeValueFn(writer, dictionaryValue); JsState.IsWritingValue = false; } } writer.Write(JsWriter.MapEndChar); } } internal static class ToStringDictionaryMethods<TKey, TValue, TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); public static void WriteIDictionary( TextWriter writer, object oMap, WriteObjectDelegate writeKeyFn, WriteObjectDelegate writeValueFn) { if (writer == null) return; //AOT WriteGenericIDictionary(writer, (IDictionary<TKey, TValue>)oMap, writeKeyFn, writeValueFn); } public static void WriteGenericIDictionary( TextWriter writer, IDictionary<TKey, TValue> map, WriteObjectDelegate writeKeyFn, WriteObjectDelegate writeValueFn) { if (map == null) { writer.Write(JsonUtils.Null); return; } writer.Write(JsWriter.MapStartChar); var encodeMapKey = Serializer.GetTypeInfo(typeof(TKey)).EncodeMapKey; var ranOnce = false; foreach (var kvp in map) { var isNull = (kvp.Value == null); if (isNull && !Serializer.IncludeNullValues) continue; JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); JsState.WritingKeyCount++; JsState.IsWritingValue = false; if (encodeMapKey) { JsState.IsWritingValue = true; //prevent ""null"" writer.Write(JsWriter.QuoteChar); writeKeyFn(writer, kvp.Key); writer.Write(JsWriter.QuoteChar); } else { writeKeyFn(writer, kvp.Key); } JsState.WritingKeyCount--; writer.Write(JsWriter.MapKeySeperator); if (isNull) { writer.Write(JsonUtils.Null); } else { JsState.IsWritingValue = true; writeValueFn(writer, kvp.Value); JsState.IsWritingValue = false; } } writer.Write(JsWriter.MapEndChar); } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 3763 $</version> // </file> using System; using System.IO; using NUnit.Framework; using ICSharpCode.NRefactory.Parser; using ICSharpCode.NRefactory.Ast; using ICSharpCode.NRefactory.PrettyPrinter; namespace ICSharpCode.NRefactory.Tests.PrettyPrinter { [TestFixture] public class CSharpOutputTest { void TestProgram(string program) { IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(program)); parser.Parse(); Assert.AreEqual("", parser.Errors.ErrorOutput); CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(); outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null); Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); Assert.AreEqual(StripWhitespace(program), StripWhitespace(outputVisitor.Text)); } internal static string StripWhitespace(string text) { return text.Trim().Replace("\t", "").Replace("\r", "").Replace("\n", " ").Replace(" ", " "); } void TestTypeMember(string program) { TestProgram("class A { " + program + " }"); } void TestStatement(string statement) { TestTypeMember("void Method() { " + statement + " }"); } void TestExpression(string expression) { // SEMICOLON HACK : without a trailing semicolon, parsing expressions does not work correctly IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(expression + ";")); Expression e = parser.ParseExpression(); Assert.AreEqual("", parser.Errors.ErrorOutput); Assert.IsNotNull(e, "ParseExpression returned null"); CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(); e.AcceptVisitor(outputVisitor, null); Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); Assert.AreEqual(StripWhitespace(expression), StripWhitespace(outputVisitor.Text)); } [Test] public void Namespace() { TestProgram("namespace System { }"); } [Test] public void CustomEvent() { TestTypeMember("public event EventHandler Click {" + " add { obj.Click += value; }" + " remove { obj.Click -= value; } " + "}"); } [Test] public void EventWithInitializer() { TestTypeMember("public event EventHandler Click = delegate { };"); } [Test] public void Field() { TestTypeMember("int a;"); } [Test] public void Method() { TestTypeMember("void Method() { }"); } [Test] public void StaticMethod() { TestTypeMember("static void Method() { }"); } [Test] public void PartialModifier() { TestProgram("public partial class Foo { }"); } [Test] public void GenericClassDefinition() { TestProgram("public class Foo<T> where T : IDisposable, ICloneable { }"); } [Test] public void InterfaceWithOutParameters() { TestProgram("public interface ITest { void Method(out int a, ref double b); }"); } [Test] public void GenericClassDefinitionWithBaseType() { TestProgram("public class Foo<T> : BaseClass where T : IDisposable, ICloneable { }"); } [Test] public void GenericMethodDefinition() { TestTypeMember("public void Foo<T>(T arg) where T : IDisposable, ICloneable { }"); } [Test] public void ArrayRank() { TestStatement("object[,,] a = new object[1, 2, 3];"); } [Test] public void JaggedArrayRank() { TestStatement("object[,][,,] a = new object[1, 2][,,];"); } [Test] public void ArrayInitializer() { TestStatement("object[] a = new object[] { 1, 2, 3 };"); } [Test] public void IfStatement() { TestStatement("if (a) { m1(); } else { m2(); }"); TestStatement("if (a) m1(); else m2(); "); TestStatement("if (a) {\n" + "\tm1();\n" + "} else if (b) {\n" + "\tm2();\n" + "} else {\n" + "\tm3();\n" + "}"); } [Test] public void Assignment() { TestExpression("a = b"); } [Test] public void UnaryOperator() { TestExpression("a = -b"); } [Test] public void BlockStatements() { TestStatement("checked { }"); TestStatement("unchecked { }"); TestStatement("unsafe { }"); } [Test] public void ExceptionHandling() { TestStatement("try { throw new Exception(); } " + "catch (FirstException e) { } " + "catch (SecondException) { } " + "catch { throw; } " + "finally { }"); } [Test] public void LoopStatements() { TestStatement("foreach (Type var in col) { }"); TestStatement("while (true) { }"); TestStatement("do { } while (true);"); } [Test] public void Switch() { TestStatement("switch (a) {" + " case 0:" + " case 1:" + " break;" + " case 2:" + " return;" + " default:" + " throw new Exception(); " + "}"); } [Test] public void MultipleVariableForLoop() { TestStatement("for (int a = 0, b = 0; b < 100; ++b,a--) { }"); } [Test] public void SizeOf() { TestExpression("sizeof(IntPtr)"); } [Test] public void ParenthesizedExpression() { TestExpression("(a)"); } [Test] public void MethodOnGenericClass() { TestExpression("Container<string>.CreateInstance()"); } [Test] public void EmptyStatement() { TestStatement(";"); } [Test] public void Yield() { TestStatement("yield break;"); TestStatement("yield return null;"); } [Test] public void Integer() { TestExpression("16"); } [Test] public void HexadecimalInteger() { TestExpression("0x10"); } [Test] public void LongInteger() { TestExpression("12L"); } [Test] public void LongUnsignedInteger() { TestExpression("12uL"); } [Test] public void UnsignedInteger() { TestExpression("12u"); } [Test] public void Double() { TestExpression("12.5"); TestExpression("12.0"); } [Test] public void StringWithUnicodeLiteral() { TestExpression(@"""\u0001"""); } [Test] public void GenericMethodInvocation() { TestExpression("GenericMethod<T>(arg)"); } [Test] public void Cast() { TestExpression("(T)a"); } [Test] public void AsCast() { TestExpression("a as T"); } [Test] public void NullCoalescing() { TestExpression("a ?? b"); } [Test] public void SpecialIdentifierName() { TestExpression("@class"); } [Test] public void InnerClassTypeReference() { TestExpression("typeof(List<string>.Enumerator)"); } [Test] public void GenericDelegate() { TestProgram("public delegate void Predicate<T>(T item) where T : IDisposable, ICloneable;"); } [Test] public void Enum() { TestProgram("enum MyTest { Red, Green, Blue, Yellow }"); } [Test] public void EnumWithInitializers() { TestProgram("enum MyTest { Red = 1, Green = 2, Blue = 4, Yellow = 8 }"); } [Test] public void SyncLock() { TestStatement("lock (a) { Work(); }"); } [Test] public void Using() { TestStatement("using (A a = new A()) { a.Work(); }"); } [Test] public void AbstractProperty() { TestTypeMember("public abstract bool ExpectsValue { get; set; }"); TestTypeMember("public abstract bool ExpectsValue { get; }"); TestTypeMember("public abstract bool ExpectsValue { set; }"); } [Test] public void SetOnlyProperty() { TestTypeMember("public bool ExpectsValue { set { DoSomething(value); } }"); } [Test] public void AbstractMethod() { TestTypeMember("public abstract void Run();"); TestTypeMember("public abstract bool Run();"); } [Test] public void AnonymousMethod() { TestStatement("Func b = delegate { return true; };"); TestStatement("Func a = delegate() { return false; };"); } [Test] public void Interface() { TestProgram("interface ITest {" + " bool GetterAndSetter { get; set; }" + " bool GetterOnly { get; }" + " bool SetterOnly { set; }" + " void InterfaceMethod();" + " string InterfaceMethod2();\n" + "}"); } [Test] public void IndexerDeclaration() { TestTypeMember("public string this[int index] { get { return index.ToString(); } set { } }"); TestTypeMember("public string IList.this[int index] { get { return index.ToString(); } set { } }"); } [Test] public void OverloadedConversionOperators() { TestTypeMember("public static explicit operator TheBug(XmlNode xmlNode) { }"); TestTypeMember("public static implicit operator XmlNode(TheBug bugNode) { }"); } [Test] public void OverloadedTrueFalseOperators() { TestTypeMember("public static bool operator true(TheBug bugNode) { }"); TestTypeMember("public static bool operator false(TheBug bugNode) { }"); } [Test] public void OverloadedOperators() { TestTypeMember("public static TheBug operator +(TheBug bugNode, TheBug bugNode2) { }"); TestTypeMember("public static TheBug operator >>(TheBug bugNode, int b) { }"); } [Test] public void PropertyWithAccessorAccessModifiers() { TestTypeMember("public bool ExpectsValue {\n" + "\tinternal get {\n" + "\t}\n" + "\tprotected set {\n" + "\t}\n" + "}"); } [Test] public void UsingStatementForExistingVariable() { TestStatement("using (obj) {\n}"); } [Test] public void NewConstraint() { TestProgram("public struct Rational<T, O> where O : IRationalMath<T>, new()\n{\n}"); } [Test] public void StructConstraint() { TestProgram("public struct Rational<T, O> where O : struct\n{\n}"); } [Test] public void ClassConstraint() { TestProgram("public struct Rational<T, O> where O : class\n{\n}"); } [Test] public void ExtensionMethod() { TestTypeMember("public static T[] Slice<T>(this T[] source, int index, int count)\n{ }"); } [Test] public void FixedStructField() { TestProgram(@"unsafe struct CrudeMessage { public fixed byte data[256]; }"); } [Test] public void FixedStructField2() { TestProgram(@"unsafe struct CrudeMessage { fixed byte data[4 * sizeof(int)], data2[10]; }"); } [Test] public void ImplicitlyTypedLambda() { TestExpression("x => x + 1"); } [Test] public void ImplicitlyTypedLambdaWithBody() { TestExpression("x => { return x + 1; }"); TestStatement("Func<int, int> f = x => { return x + 1; };"); } [Test] public void ExplicitlyTypedLambda() { TestExpression("(int x) => x + 1"); } [Test] public void ExplicitlyTypedLambdaWithBody() { TestExpression("(int x) => { return x + 1; }"); } [Test] public void LambdaMultipleParameters() { TestExpression("(x, y) => x * y"); TestExpression("(x, y) => { return x * y; }"); TestExpression("(int x, int y) => x * y"); TestExpression("(int x, int y) => { return x * y; }"); } [Test] public void LambdaNoParameters() { TestExpression("() => Console.WriteLine()"); TestExpression("() => { Console.WriteLine(); }"); } [Test] public void ObjectInitializer() { TestExpression("new Point { X = 0, Y = 1 }"); TestExpression("new Rectangle { P1 = new Point { X = 0, Y = 1 }, P2 = new Point { X = 2, Y = 3 } }"); TestExpression("new Rectangle(arguments) { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } }"); } [Test] public void CollectionInitializer() { TestExpression("new List<int> { 0, 1, 2, 3, 4, 5 }"); TestExpression(@"new List<Contact> { new Contact { Name = ""Chris Smith"", PhoneNumbers = { ""206-555-0101"", ""425-882-8080"" } }, new Contact { Name = ""Bob Harris"", PhoneNumbers = { ""650-555-0199"" } } }"); } [Test] public void AnonymousTypeCreation() { TestExpression("new { obj.Name, Price = 26.9, ident }"); } [Test] public void ImplicitlyTypedArrayCreation() { TestExpression("new[] { 1, 10, 100, 1000 }"); } [Test] public void QuerySimpleWhere() { TestExpression("from n in numbers where n < 5 select n"); } [Test] public void QueryMultipleFrom() { TestExpression("from c in customers" + " where c.Region == \"WA\"" + " from o in c.Orders" + " where o.OrderDate >= cutoffDate" + " select new { c.CustomerID, o.OrderID }"); } [Test] public void QuerySimpleOrdering() { TestExpression("from w in words" + " orderby w" + " select w"); } [Test] public void QueryComplexOrdering() { TestExpression("from w in words" + " orderby w.Length descending, w ascending" + " select w"); } [Test] public void QueryGroupInto() { TestExpression("from n in numbers" + " group n by n % 5 into g" + " select new { Remainder = g.Key, Numbers = g }"); } [Test] public void ExternAlias() { TestProgram("extern alias Name;"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel { using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime; using System.ServiceModel.Channels; using Microsoft.Xml; public class EndpointAddress { private static Uri s_anonymousUri; private static Uri s_noneUri; private static EndpointAddress s_anonymousAddress; /* Conceptually, the agnostic EndpointAddress class represents all of UNION(v200408,v10) data thusly: - Address Uri (both versions - the Address) - AddressHeaderCollection (both versions - RefProp&RefParam both project into here) - PSP blob (200408 - this is PortType, ServiceName, Policy, it is not surfaced in OM) - metadata (both versions, but weird semantics in 200408) - identity (both versions, this is the one 'extension' that we know about) - extensions (both versions, the "any*" stuff at the end) When reading from 200408: - Address is projected into Uri - both RefProps and RefParams are projected into AddressHeaderCollection, they (internally) remember 'which kind' they are - PortType, ServiceName, Policy are projected into the (internal) PSP blob - if we see a wsx:metadata element next, we project that element and that element only into the metadata reader - we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader When reading from 10: - Address is projected into Uri - RefParams are projected into AddressHeaderCollection; they (internally) remember 'which kind' they are - nothing is projected into the (internal) PSP blob (it's empty) - if there's a wsa10:metadata element, everything inside it projects into metadatareader - we read the rest, recognizing and fishing out identity if there, projecting rest to extensions reader When writing to 200408: - Uri is written as Address - AddressHeaderCollection is written as RefProps & RefParams, based on what they internally remember selves to be - PSP blob is written out verbatim (will have: PortType?, ServiceName?, Policy?) - metadata reader is written out verbatim - identity is written out as extension - extension reader is written out verbatim When writing to 10: - Uri is written as Address - AddressHeaderCollection is all written as RefParams, regardless of what they internally remember selves to be - PSP blob is ignored - if metadata reader is non-empty, we write its value out verbatim inside a wsa10:metadata element - identity is written out as extension - extension reader is written out verbatim EndpointAddressBuilder: - you can set metadata to any value you like; we don't (cannot) validate because 10 allows anything - you can set any extensions you like Known Weirdnesses: - PSP blob does not surface in OM - it can only roundtrip 200408wire->OM->200408wire - RefProperty distinction does not surface in OM - it can only roundtrip 200408wire->OM->200408wire - regardless of what metadata in reader, when you roundtrip OM->200408wire->OM, only wsx:metadata as first element after PSP will stay in metadata, anything else gets dumped in extensions - PSP blob is lost when doing OM->10wire->OM - RefProps turn into RefParams when doing OM->10wire->OM - Identity is always shuffled to front of extensions when doing anyWire->OM->anyWire */ private AddressingVersion _addressingVersion; private AddressHeaderCollection _headers; private EndpointIdentity _identity; private Uri _uri; private XmlBuffer _buffer; // invariant: each section in the buffer will start with a dummy wrapper element private int _extensionSection; private int _metadataSection; private int _pspSection; private bool _isAnonymous; private bool _isNone; // these are the element name/namespace for the dummy wrapper element that wraps each buffer section internal const string DummyName = "Dummy"; internal const string DummyNamespace = "http://Dummy"; private EndpointAddress(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { Init(version, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } public EndpointAddress(string uri) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri"); } Uri u = new Uri(uri); Init(u, (EndpointIdentity)null, (AddressHeaderCollection)null, null, -1, -1, -1); } public EndpointAddress(Uri uri, params AddressHeader[] addressHeaders) : this(uri, (EndpointIdentity)null, addressHeaders) { } public EndpointAddress(Uri uri, EndpointIdentity identity, params AddressHeader[] addressHeaders) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri"); } Init(uri, identity, addressHeaders); } public EndpointAddress(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri"); } Init(uri, identity, headers, null, -1, -1, -1); } internal EndpointAddress(Uri newUri, EndpointAddress oldEndpointAddress) { Init(oldEndpointAddress._addressingVersion, newUri, oldEndpointAddress._identity, oldEndpointAddress._headers, oldEndpointAddress._buffer, oldEndpointAddress._metadataSection, oldEndpointAddress._extensionSection, oldEndpointAddress._pspSection); } internal EndpointAddress(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlDictionaryReader metadataReader, XmlDictionaryReader extensionReader, XmlDictionaryReader pspReader) { if (uri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri"); } XmlBuffer buffer = null; PossiblyPopulateBuffer(metadataReader, ref buffer, out _metadataSection); EndpointIdentity ident2; int extSection; buffer = ReadExtensions(extensionReader, null, buffer, out ident2, out extSection); if (identity != null && ident2 != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SRServiceModel.MultipleIdentities, "extensionReader")); } PossiblyPopulateBuffer(pspReader, ref buffer, out _pspSection); if (buffer != null) { buffer.Close(); } Init(uri, identity ?? ident2, headers, buffer, _metadataSection, extSection, _pspSection); } // metadataReader and extensionReader are assumed to not have a starting dummy wrapper element public EndpointAddress(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlDictionaryReader metadataReader, XmlDictionaryReader extensionReader) : this(uri, identity, headers, metadataReader, extensionReader, null) { } private void Init(Uri uri, EndpointIdentity identity, AddressHeader[] headers) { if (headers == null || headers.Length == 0) { Init(uri, identity, (AddressHeaderCollection)null, null, -1, -1, -1); } else { Init(uri, identity, new AddressHeaderCollection(headers), null, -1, -1, -1); } } private void Init(Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { Init(null, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } private void Init(AddressingVersion version, Uri uri, EndpointIdentity identity, AddressHeaderCollection headers, XmlBuffer buffer, int metadataSection, int extensionSection, int pspSection) { if (!uri.IsAbsoluteUri) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("uri", SRServiceModel.UriMustBeAbsolute); _addressingVersion = version; _uri = uri; _identity = identity; _headers = headers; _buffer = buffer; _metadataSection = metadataSection; _extensionSection = extensionSection; _pspSection = pspSection; if (version != null) { _isAnonymous = uri == version.AnonymousUri; _isNone = uri == version.NoneUri; } else { _isAnonymous = object.ReferenceEquals(uri, AnonymousUri) || uri == AnonymousUri; _isNone = object.ReferenceEquals(uri, NoneUri) || uri == NoneUri; } if (_isAnonymous) { _uri = AnonymousUri; } if (_isNone) { _uri = NoneUri; } } internal static EndpointAddress AnonymousAddress { get { if (s_anonymousAddress == null) s_anonymousAddress = new EndpointAddress(AnonymousUri); return s_anonymousAddress; } } public static Uri AnonymousUri { get { if (s_anonymousUri == null) s_anonymousUri = new Uri(AddressingStrings.AnonymousUri); return s_anonymousUri; } } public static Uri NoneUri { get { if (s_noneUri == null) s_noneUri = new Uri(AddressingStrings.NoneUri); return s_noneUri; } } internal XmlBuffer Buffer { get { return _buffer; } } public AddressHeaderCollection Headers { get { if (_headers == null) { _headers = new AddressHeaderCollection(); } return _headers; } } public EndpointIdentity Identity { get { return _identity; } } public bool IsAnonymous { get { return _isAnonymous; } } public bool IsNone { get { return _isNone; } } public Uri Uri { get { return _uri; } } public void ApplyTo(Message message) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); Uri uri = this.Uri; if (IsAnonymous) { #pragma warning disable 56506 if (message.Version.Addressing == AddressingVersion.WSAddressing10) { message.Headers.To = null; } else if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004) { #pragma warning disable 56506 message.Headers.To = message.Version.Addressing.AnonymousUri; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(string.Format(SRServiceModel.AddressingVersionNotSupported, message.Version.Addressing))); } } else if (IsNone) { message.Headers.To = message.Version.Addressing.NoneUri; } else { message.Headers.To = uri; } message.Properties.Via = message.Headers.To; if (_headers != null) { _headers.AddHeadersTo(message); } } // NOTE: UserInfo, Query, and Fragment are ignored when comparing Uris as addresses // this is the WCF logic for comparing Uris that represent addresses // this method must be kept in sync with UriGetHashCode internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison) { return UriEquals(u1, u2, ignoreCase, includeHostInComparison, true); } internal static bool UriEquals(Uri u1, Uri u2, bool ignoreCase, bool includeHostInComparison, bool includePortInComparison) { // PERF: Equals compares everything but UserInfo and Fragments. It's more strict than // we are, and faster, so it is done first. if (u1.Equals(u2)) { return true; } if (u1.Scheme != u2.Scheme) // Uri.Scheme is always lowercase { return false; } if (includePortInComparison) { if (u1.Port != u2.Port) { return false; } } if (includeHostInComparison) { if (string.Compare(u1.Host, u2.Host, StringComparison.OrdinalIgnoreCase) != 0) { return false; } } if (string.Compare(u1.AbsolutePath, u2.AbsolutePath, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0) { return true; } // Normalize for trailing slashes string u1Path = u1.GetComponents(UriComponents.Path, UriFormat.Unescaped); string u2Path = u2.GetComponents(UriComponents.Path, UriFormat.Unescaped); int u1Len = (u1Path.Length > 0 && u1Path[u1Path.Length - 1] == '/') ? u1Path.Length - 1 : u1Path.Length; int u2Len = (u2Path.Length > 0 && u2Path[u2Path.Length - 1] == '/') ? u2Path.Length - 1 : u2Path.Length; if (u2Len != u1Len) { return false; } return string.Compare(u1Path, 0, u2Path, 0, u1Len, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0; } // this method must be kept in sync with UriEquals internal static int UriGetHashCode(Uri uri, bool includeHostInComparison) { return UriGetHashCode(uri, includeHostInComparison, true); } internal static int UriGetHashCode(Uri uri, bool includeHostInComparison, bool includePortInComparison) { UriComponents components = UriComponents.Scheme | UriComponents.Path; if (includePortInComparison) { components = components | UriComponents.Port; } if (includeHostInComparison) { components = components | UriComponents.Host; } // Normalize for trailing slashes string uriString = uri.GetComponents(components, UriFormat.Unescaped); if (uriString.Length > 0 && uriString[uriString.Length - 1] != '/') uriString = string.Concat(uriString, "/"); return StringComparer.OrdinalIgnoreCase.GetHashCode(uriString); } internal bool EndpointEquals(EndpointAddress endpointAddress) { if (endpointAddress == null) { return false; } if (object.ReferenceEquals(this, endpointAddress)) { return true; } Uri thisTo = this.Uri; Uri otherTo = endpointAddress.Uri; if (!UriEquals(thisTo, otherTo, false /* ignoreCase */, true /* includeHostInComparison */)) { return false; } if (this.Identity == null) { if (endpointAddress.Identity != null) { return false; } } else if (!this.Identity.Equals(endpointAddress.Identity)) { return false; } if (!this.Headers.IsEquivalent(endpointAddress.Headers)) { return false; } return true; } public override bool Equals(object obj) { if (object.ReferenceEquals(obj, this)) { return true; } if (obj == null) { return false; } EndpointAddress address = obj as EndpointAddress; if (address == null) { return false; } return EndpointEquals(address); } public override int GetHashCode() { return UriGetHashCode(_uri, true /* includeHostInComparison */); } // returns reader without starting dummy wrapper element internal XmlDictionaryReader GetReaderAtPsp() { return GetReaderAtSection(_buffer, _pspSection); } // returns reader without starting dummy wrapper element public XmlDictionaryReader GetReaderAtMetadata() { return GetReaderAtSection(_buffer, _metadataSection); } // returns reader without starting dummy wrapper element public XmlDictionaryReader GetReaderAtExtensions() { return GetReaderAtSection(_buffer, _extensionSection); } private static XmlDictionaryReader GetReaderAtSection(XmlBuffer buffer, int section) { if (buffer == null || section < 0) return null; XmlDictionaryReader reader = buffer.GetReader(section); reader.MoveToContent(); Fx.Assert(reader.Name == DummyName, "EndpointAddress: Expected dummy element not found"); reader.Read(); // consume the dummy wrapper element return reader; } private void PossiblyPopulateBuffer(XmlDictionaryReader reader, ref XmlBuffer buffer, out int section) { if (reader == null) { section = -1; } else { if (buffer == null) { buffer = new XmlBuffer(short.MaxValue); } section = buffer.SectionCount; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); writer.WriteStartElement(DummyName, DummyNamespace); Copy(writer, reader); buffer.CloseSection(); } } public static EndpointAddress ReadFrom(XmlDictionaryReader reader) { AddressingVersion dummyVersion; return ReadFrom(reader, out dummyVersion); } internal static EndpointAddress ReadFrom(XmlDictionaryReader reader, out AddressingVersion version) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); reader.ReadFullStartElement(); reader.MoveToContent(); if (reader.IsNamespaceUri(AddressingVersion.WSAddressing10.DictionaryNamespace)) { version = AddressingVersion.WSAddressing10; } else if (reader.IsNamespaceUri(AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { version = AddressingVersion.WSAddressingAugust2004; } else if (reader.NodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", SRServiceModel.CannotDetectAddressingVersion); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", string.Format(SRServiceModel.AddressingVersionNotSupported, reader.NamespaceURI)); } EndpointAddress ea = ReadFromDriver(version, reader); reader.ReadEndElement(); return ea; } public static EndpointAddress ReadFrom(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { AddressingVersion version; return ReadFrom(reader, localName, ns, out version); } internal static EndpointAddress ReadFrom(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns, out AddressingVersion version) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); reader.ReadFullStartElement(localName, ns); reader.MoveToContent(); if (reader.IsNamespaceUri(AddressingVersion.WSAddressing10.DictionaryNamespace)) { version = AddressingVersion.WSAddressing10; } else if (reader.IsNamespaceUri(AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { version = AddressingVersion.WSAddressingAugust2004; } else if (reader.NodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", string.Format(SRServiceModel.CannotDetectAddressingVersion)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "reader", string.Format(SRServiceModel.AddressingVersionNotSupported, reader.NamespaceURI)); } EndpointAddress ea = ReadFromDriver(version, reader); reader.ReadEndElement(); return ea; } public static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlReader reader) { return ReadFrom(addressingVersion, XmlDictionaryReader.CreateDictionaryReader(reader)); } public static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlReader reader, string localName, string ns) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); XmlDictionaryReader dictReader = XmlDictionaryReader.CreateDictionaryReader(reader); dictReader.ReadFullStartElement(localName, ns); EndpointAddress ea = ReadFromDriver(addressingVersion, dictReader); reader.ReadEndElement(); return ea; } public static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlDictionaryReader reader) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); reader.ReadFullStartElement(); EndpointAddress ea = ReadFromDriver(addressingVersion, reader); reader.ReadEndElement(); return ea; } private static EndpointAddress ReadFrom(AddressingVersion addressingVersion, XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); if (addressingVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); reader.ReadFullStartElement(localName, ns); EndpointAddress ea = ReadFromDriver(addressingVersion, reader); reader.ReadEndElement(); return ea; } private static EndpointAddress ReadFromDriver(AddressingVersion addressingVersion, XmlDictionaryReader reader) { AddressHeaderCollection headers; EndpointIdentity identity; Uri uri; XmlBuffer buffer; bool isAnonymous; int extensionSection; int metadataSection; int pspSection = -1; if (addressingVersion == AddressingVersion.WSAddressing10) { isAnonymous = ReadContentsFrom10(reader, out uri, out headers, out identity, out buffer, out metadataSection, out extensionSection); } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { isAnonymous = ReadContentsFrom200408(reader, out uri, out headers, out identity, out buffer, out metadataSection, out extensionSection, out pspSection); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", string.Format(SRServiceModel.AddressingVersionNotSupported, addressingVersion)); } if (isAnonymous && headers == null && identity == null && buffer == null) { return AnonymousAddress; } else { return new EndpointAddress(addressingVersion, uri, identity, headers, buffer, metadataSection, extensionSection, pspSection); } } internal static XmlBuffer ReadExtensions(XmlDictionaryReader reader, AddressingVersion version, XmlBuffer buffer, out EndpointIdentity identity, out int section) { if (reader == null) { identity = null; section = -1; return buffer; } // EndpointIdentity and extensions identity = null; XmlDictionaryWriter bufferWriter = null; reader.MoveToContent(); while (reader.IsStartElement()) { if (reader.IsStartElement(XD.AddressingDictionary.Identity, XD.AddressingDictionary.IdentityExtensionNamespace)) { if (identity != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.UnexpectedDuplicateElement, XD.AddressingDictionary.Identity.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value))); identity = EndpointIdentity.ReadIdentity(reader); } else if (version != null && reader.NamespaceURI == version.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } else { if (bufferWriter == null) { if (buffer == null) buffer = new XmlBuffer(short.MaxValue); bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } reader.MoveToContent(); } if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); section = buffer.SectionCount - 1; } else { section = -1; } return buffer; } private static bool ReadContentsFrom200408(XmlDictionaryReader reader, out Uri uri, out AddressHeaderCollection headers, out EndpointIdentity identity, out XmlBuffer buffer, out int metadataSection, out int extensionSection, out int pspSection) { buffer = null; headers = null; extensionSection = -1; metadataSection = -1; pspSection = -1; // Cache address string reader.MoveToContent(); if (!reader.IsStartElement(XD.AddressingDictionary.Address, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.UnexpectedElementExpectingElement, reader.LocalName, reader.NamespaceURI, XD.AddressingDictionary.Address.Value, XD.Addressing200408Dictionary.Namespace.Value))); } string address = reader.ReadElementContentAsString(); // ReferenceProperites reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ReferenceProperties, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { headers = AddressHeaderCollection.ReadServiceParameters(reader, true); } // ReferenceParameters reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ReferenceParameters, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (headers != null) { List<AddressHeader> headerList = new List<AddressHeader>(); foreach (AddressHeader ah in headers) { headerList.Add(ah); } AddressHeaderCollection tmp = AddressHeaderCollection.ReadServiceParameters(reader); foreach (AddressHeader ah in tmp) { headerList.Add(ah); } headers = new AddressHeaderCollection(headerList); } else { headers = AddressHeaderCollection.ReadServiceParameters(reader); } } XmlDictionaryWriter bufferWriter = null; // PortType reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.PortType, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (bufferWriter == null) { if (buffer == null) buffer = new XmlBuffer(short.MaxValue); bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // ServiceName reader.MoveToContent(); if (reader.IsStartElement(XD.AddressingDictionary.ServiceName, AddressingVersion.WSAddressingAugust2004.DictionaryNamespace)) { if (bufferWriter == null) { if (buffer == null) buffer = new XmlBuffer(short.MaxValue); bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // Policy reader.MoveToContent(); while (reader.IsNamespaceUri(XD.PolicyDictionary.Namespace)) { if (bufferWriter == null) { if (buffer == null) buffer = new XmlBuffer(short.MaxValue); bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); reader.MoveToContent(); } // Finish PSP if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); pspSection = buffer.SectionCount - 1; bufferWriter = null; } else { pspSection = -1; } // Metadata if (reader.IsStartElement(System.ServiceModel.Description.MetadataStrings.MetadataExchangeStrings.Metadata, System.ServiceModel.Description.MetadataStrings.MetadataExchangeStrings.Namespace)) { if (bufferWriter == null) { if (buffer == null) buffer = new XmlBuffer(short.MaxValue); bufferWriter = buffer.OpenSection(reader.Quotas); bufferWriter.WriteStartElement(DummyName, DummyNamespace); } bufferWriter.WriteNode(reader, true); } // Finish metadata if (bufferWriter != null) { bufferWriter.WriteEndElement(); buffer.CloseSection(); metadataSection = buffer.SectionCount - 1; bufferWriter = null; } else { metadataSection = -1; } // Extensions reader.MoveToContent(); buffer = ReadExtensions(reader, AddressingVersion.WSAddressingAugust2004, buffer, out identity, out extensionSection); // Finished reading if (buffer != null) buffer.Close(); // Process Address if (address == Addressing200408Strings.Anonymous) { uri = AddressingVersion.WSAddressingAugust2004.AnonymousUri; if (headers == null && identity == null) return true; } else { if (!Uri.TryCreate(address, UriKind.Absolute, out uri)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.InvalidUriValue, address, XD.AddressingDictionary.Address.Value, AddressingVersion.WSAddressingAugust2004.Namespace))); } return false; } private static bool ReadContentsFrom10(XmlDictionaryReader reader, out Uri uri, out AddressHeaderCollection headers, out EndpointIdentity identity, out XmlBuffer buffer, out int metadataSection, out int extensionSection) { buffer = null; extensionSection = -1; metadataSection = -1; // Cache address string if (!reader.IsStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.UnexpectedElementExpectingElement, reader.LocalName, reader.NamespaceURI, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value))); string address = reader.ReadElementContentAsString(); // Headers if (reader.IsStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace)) { headers = AddressHeaderCollection.ReadServiceParameters(reader); } else { headers = null; } // Metadata if (reader.IsStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace)) { reader.ReadFullStartElement(); // the wsa10:Metadata element is never stored in the buffer buffer = new XmlBuffer(short.MaxValue); metadataSection = 0; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); writer.WriteStartElement(DummyName, DummyNamespace); while (reader.NodeType != XmlNodeType.EndElement && !reader.EOF) { writer.WriteNode(reader, true); } writer.Flush(); buffer.CloseSection(); reader.ReadEndElement(); } // Extensions buffer = ReadExtensions(reader, AddressingVersion.WSAddressing10, buffer, out identity, out extensionSection); if (buffer != null) { buffer.Close(); } // Process Address if (address == Addressing10Strings.Anonymous) { uri = AddressingVersion.WSAddressing10.AnonymousUri; if (headers == null && identity == null) { return true; } } else if (address == Addressing10Strings.NoneAddress) { uri = AddressingVersion.WSAddressing10.NoneUri; return false; } else { if (!Uri.TryCreate(address, UriKind.Absolute, out uri)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.InvalidUriValue, address, XD.AddressingDictionary.Address.Value, XD.Addressing10Dictionary.Namespace.Value))); } } return false; } private static XmlException CreateXmlException(XmlDictionaryReader reader, string message) { IXmlLineInfo lineInfo = reader as IXmlLineInfo; if (lineInfo != null) { return new XmlException(message, (Exception)null, lineInfo.LineNumber, lineInfo.LinePosition); } return new XmlException(message); } // this function has a side-effect on the reader (MoveToContent) private static bool Done(XmlDictionaryReader reader) { reader.MoveToContent(); return (reader.NodeType == XmlNodeType.EndElement || reader.EOF); } // copy all of reader to writer static internal void Copy(XmlDictionaryWriter writer, XmlDictionaryReader reader) { while (!Done(reader)) { writer.WriteNode(reader, true); } } public override string ToString() { return _uri.ToString(); } public void WriteContentsTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); } if (addressingVersion == AddressingVersion.WSAddressing10) { WriteContentsTo10(writer); } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { WriteContentsTo200408(writer); } else if (addressingVersion == AddressingVersion.None) { WriteContentsToNone(writer); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", string.Format(SRServiceModel.AddressingVersionNotSupported, addressingVersion)); } } private void WriteContentsToNone(XmlDictionaryWriter writer) { writer.WriteString(this.Uri.AbsoluteUri); } private void WriteContentsTo200408(XmlDictionaryWriter writer) { // Address writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing200408Dictionary.Namespace); if (_isAnonymous) { writer.WriteString(XD.Addressing200408Dictionary.Anonymous); } else if (_isNone) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", string.Format(SRServiceModel.SFxNone2004)); } else { writer.WriteString(this.Uri.AbsoluteUri); } writer.WriteEndElement(); // ReferenceProperties if (_headers != null && _headers.HasReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceProperties, XD.Addressing200408Dictionary.Namespace); _headers.WriteReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // ReferenceParameters if (_headers != null && _headers.HasNonReferenceProperties) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing200408Dictionary.Namespace); _headers.WriteNonReferencePropertyContentsTo(writer); writer.WriteEndElement(); } // PSP (PortType, ServiceName, Policy) XmlDictionaryReader reader = null; if (_pspSection >= 0) { reader = GetReaderAtSection(_buffer, _pspSection); Copy(writer, reader); } // Metadata reader = null; if (_metadataSection >= 0) { reader = GetReaderAtSection(_buffer, _metadataSection); Copy(writer, reader); } // EndpointIdentity if (this.Identity != null) { this.Identity.WriteTo(writer); } // Extensions if (_extensionSection >= 0) { reader = GetReaderAtSection(_buffer, _extensionSection); while (reader.IsStartElement()) { if (reader.NamespaceURI == AddressingVersion.WSAddressingAugust2004.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } writer.WriteNode(reader, true); } } } private void WriteContentsTo10(XmlDictionaryWriter writer) { // Address writer.WriteStartElement(XD.AddressingDictionary.Address, XD.Addressing10Dictionary.Namespace); if (_isAnonymous) { writer.WriteString(XD.Addressing10Dictionary.Anonymous); } else if (_isNone) { writer.WriteString(XD.Addressing10Dictionary.NoneAddress); } else { writer.WriteString(this.Uri.AbsoluteUri); } writer.WriteEndElement(); // Headers if (_headers != null && _headers.Count > 0) { writer.WriteStartElement(XD.AddressingDictionary.ReferenceParameters, XD.Addressing10Dictionary.Namespace); _headers.WriteContentsTo(writer); writer.WriteEndElement(); } // Metadata if (_metadataSection >= 0) { XmlDictionaryReader reader = GetReaderAtSection(_buffer, _metadataSection); writer.WriteStartElement(XD.Addressing10Dictionary.Metadata, XD.Addressing10Dictionary.Namespace); Copy(writer, reader); writer.WriteEndElement(); } // EndpointIdentity if (this.Identity != null) { this.Identity.WriteTo(writer); } // Extensions if (_extensionSection >= 0) { XmlDictionaryReader reader = GetReaderAtSection(_buffer, _extensionSection); while (reader.IsStartElement()) { if (reader.NamespaceURI == AddressingVersion.WSAddressing10.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateXmlException(reader, string.Format(SRServiceModel.AddressingExtensionInBadNS, reader.LocalName, reader.NamespaceURI))); } writer.WriteNode(reader, true); } } } public void WriteContentsTo(AddressingVersion addressingVersion, XmlWriter writer) { XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); WriteContentsTo(addressingVersion, dictionaryWriter); } public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer) { WriteTo(addressingVersion, writer, XD.AddressingDictionary.EndpointReference, addressingVersion.DictionaryNamespace); } public void WriteTo(AddressingVersion addressingVersion, XmlDictionaryWriter writer, XmlDictionaryString localName, XmlDictionaryString ns) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } writer.WriteStartElement(localName, ns); WriteContentsTo(addressingVersion, writer); writer.WriteEndElement(); } public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer) { XmlDictionaryString dictionaryNamespace = addressingVersion.DictionaryNamespace; if (dictionaryNamespace == null) { dictionaryNamespace = XD.AddressingDictionary.Empty; } WriteTo(addressingVersion, XmlDictionaryWriter.CreateDictionaryWriter(writer), XD.AddressingDictionary.EndpointReference, dictionaryNamespace); } public void WriteTo(AddressingVersion addressingVersion, XmlWriter writer, string localName, string ns) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } writer.WriteStartElement(localName, ns); WriteContentsTo(addressingVersion, writer); writer.WriteEndElement(); } public static bool operator ==(EndpointAddress address1, EndpointAddress address2) { if (object.ReferenceEquals(address2, null)) { return (object.ReferenceEquals(address1, null)); } return address2.Equals(address1); } public static bool operator !=(EndpointAddress address1, EndpointAddress address2) { if (object.ReferenceEquals(address2, null)) { return !object.ReferenceEquals(address1, null); } return !address2.Equals(address1); } } public class EndpointAddressBuilder { private Uri _uri; private EndpointIdentity _identity; private Collection<AddressHeader> _headers; private XmlBuffer _extensionBuffer; // this buffer is wrapped just like in EndpointAddress private XmlBuffer _metadataBuffer; // this buffer is wrapped just like in EndpointAddress private bool _hasExtension; private bool _hasMetadata; private EndpointAddress _epr; public EndpointAddressBuilder() { _headers = new Collection<AddressHeader>(); } public EndpointAddressBuilder(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } _epr = address; _uri = address.Uri; _identity = address.Identity; _headers = new Collection<AddressHeader>(); #pragma warning disable 56506 for (int i = 0; i < address.Headers.Count; i++) { _headers.Add(address.Headers[i]); } } public Uri Uri { get { return _uri; } set { _uri = value; } } public EndpointIdentity Identity { get { return _identity; } set { _identity = value; } } public Collection<AddressHeader> Headers { get { return _headers; } } public XmlDictionaryReader GetReaderAtMetadata() { if (!_hasMetadata) { return _epr == null ? null : _epr.GetReaderAtMetadata(); } if (_metadataBuffer == null) { return null; } XmlDictionaryReader reader = _metadataBuffer.GetReader(0); reader.MoveToContent(); Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found"); reader.Read(); // consume the wrapper element return reader; } public void SetMetadataReader(XmlDictionaryReader reader) { _hasMetadata = true; _metadataBuffer = null; if (reader != null) { _metadataBuffer = new XmlBuffer(short.MaxValue); XmlDictionaryWriter writer = _metadataBuffer.OpenSection(reader.Quotas); writer.WriteStartElement(EndpointAddress.DummyName, EndpointAddress.DummyNamespace); EndpointAddress.Copy(writer, reader); _metadataBuffer.CloseSection(); _metadataBuffer.Close(); } } public XmlDictionaryReader GetReaderAtExtensions() { if (!_hasExtension) { return _epr == null ? null : _epr.GetReaderAtExtensions(); } if (_extensionBuffer == null) { return null; } XmlDictionaryReader reader = _extensionBuffer.GetReader(0); reader.MoveToContent(); Fx.Assert(reader.Name == EndpointAddress.DummyName, "EndpointAddressBuilder: Expected dummy element not found"); reader.Read(); // consume the wrapper element return reader; } public void SetExtensionReader(XmlDictionaryReader reader) { _hasExtension = true; EndpointIdentity identity; int tmp; _extensionBuffer = EndpointAddress.ReadExtensions(reader, null, null, out identity, out tmp); if (_extensionBuffer != null) { _extensionBuffer.Close(); } if (identity != null) { _identity = identity; } } public EndpointAddress ToEndpointAddress() { return new EndpointAddress( _uri, _identity, new AddressHeaderCollection(_headers), this.GetReaderAtMetadata(), this.GetReaderAtExtensions(), _epr == null ? null : _epr.GetReaderAtPsp()); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A table on the page. /// </summary> public class Table_Core : TypeCore, IWebPageElement { public Table_Core() { this._TypeId = 259; this._Id = "Table"; this._Schema_Org_Url = "http://schema.org/Table"; string label = ""; GetLabel(out label, "Table", typeof(Table_Core)); this._Label = label; this._Ancestors = new int[]{266,78,294}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{294}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
namespace Appleseed.Framework.Site.Data { using System; using System.Data; using System.Data.SqlClient; using Appleseed.Framework.Settings; /// <summary> /// Class that encapsulates all data logic necessary /// to publish a module using workflow /// </summary> public class WorkFlowDB { #region Public Methods /// <summary> /// This function puts the status of a module to approved /// </summary> /// <param name="moduleId">The module id.</param> public static void Approve(int moduleId) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_Approve", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@moduleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } /// <summary> /// The get last modified. /// </summary> /// <param name="moduleId"> /// The module id. /// </param> /// <param name="version"> /// The version. /// </param> /// <param name="email"> /// The email. /// </param> /// <param name="timestamp"> /// The timestamp. /// </param> public static void GetLastModified( int moduleId, WorkFlowVersion version, ref string email, ref DateTime timestamp) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_GetLastModified", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@ModuleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); var parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4) { Value = (int)version }; command.Parameters.Add(parameterWorkflowVersion); var parameterEmail = new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 256) { Direction = ParameterDirection.Output }; command.Parameters.Add(parameterEmail); var parameterDate = new SqlParameter("@LastModifiedDate", SqlDbType.DateTime, 8) { Direction = ParameterDirection.Output }; command.Parameters.Add(parameterDate); connection.Open(); try { command.ExecuteNonQuery(); email = Convert.IsDBNull(parameterEmail.Value) ? string.Empty : (string)parameterEmail.Value; timestamp = Convert.IsDBNull(parameterDate.Value) ? DateTime.MinValue : (DateTime)parameterDate.Value; } finally { connection.Close(); } } /// <summary> /// This function publishes the staging data of a module. /// </summary> /// <param name="moduleId">The module id.</param> public static void Publish(int moduleId) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_Publish", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@ModuleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } /// <summary> /// This function puts the status of a module back to working /// </summary> /// <param name="moduleId">The module ID.</param> public static void Reject(int moduleId) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_Reject", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@moduleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } /// <summary> /// This function puts the status of a module to request approval /// </summary> /// <param name="moduleId">The module ID.</param> public static void RequestApproval(int moduleId) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_RequestApproval", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@moduleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } /// <summary> /// This function reverts the staging data to the content in production of a module. /// </summary> /// <param name="moduleId">The module ID.</param> public static void Revert(int moduleId) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_Revert", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@ModuleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } /// <summary> /// The set last modified. /// </summary> /// <param name="moduleId"> /// The module id. /// </param> /// <param name="email"> /// The email. /// </param> public static void SetLastModified(int moduleId, string email) { // Create Instance of Connection and Command Object var connection = Config.SqlConnectionString; // Mark the Command as a SPROC var command = new SqlCommand("rb_SetLastModified", connection) { CommandType = CommandType.StoredProcedure }; // Add Parameters to SPROC var parameterModuleId = new SqlParameter("@ModuleID", SqlDbType.Int, 4) { Value = moduleId }; command.Parameters.Add(parameterModuleId); var parameterEmail = new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 256) { Value = email }; command.Parameters.Add(parameterEmail); connection.Open(); try { command.ExecuteNonQuery(); } finally { connection.Close(); } } #endregion } }
/* Copyright 2006-2017 Cryptany, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Threading; using Cryptany.Common.Utils; namespace Cryptany.Common.Logging { /// <summary> /// Thread-safe caching logger. Dumps logs to database. /// </summary> public class DBCachingLogger : ILogger { private Mutex localMutex; DataTable tmpTable; System.Timers.Timer _WriteDelayTimer; /// <summary> /// Default constructor /// </summary> public DBCachingLogger() { localMutex = new Mutex(); tmpTable = new DataTable(); tmpTable.Columns.Add("msgTime", typeof(DateTime)); tmpTable.Columns.Add("msgBody", typeof(string)); tmpTable.Columns.Add("Source", typeof(string)); tmpTable.Columns.Add("Severity", typeof(int)); _MaxWriteDelay = new TimeSpan(0, 1, 0); _MaxCacheSize = 100; _WriteDelayTimer = new System.Timers.Timer(_MaxWriteDelay.TotalMilliseconds); _WriteDelayTimer.Enabled = false; _WriteDelayTimer.Elapsed += new System.Timers.ElapsedEventHandler(_WriteDelayTimer_Elapsed); } void _WriteDelayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (tmpTable.Rows.Count > 0) Flush(); } #region ILogger Members /// <summary> /// Writes data to queue. /// </summary> /// <param name="msg">Message to save to log</param> /// <returns>true if data was written to queue sucessfully</returns> public bool Write(LogMessage msg) { // lock mutex if (!localMutex.WaitOne(new TimeSpan(0, 0, 5), true)) return false; //start timer if need if (!_WriteDelayTimer.Enabled) _WriteDelayTimer.Start(); object[] rowData = new object[4]; rowData[0] = msg.MessageTime; rowData[1] = msg.MessageText; rowData[2] = msg.Source; rowData[3] = msg.Severity; tmpTable.Rows.Add(rowData); localMutex.ReleaseMutex(); //flush if need if (AutoFlush || tmpTable.Rows.Count >= MaxCacheSize) { return Flush(); } return true; } private string _DefaultSource; /// <summary> /// Default Datasource /// </summary> public string DefaultSource { get { return _DefaultSource; } set { _DefaultSource = value; } } private bool _AutoFlush; /// <summary> /// Set to true to flush cache automatically after each write /// </summary> public bool AutoFlush { get { return _AutoFlush; } set { _AutoFlush = value; } } /// <summary> /// Write data from queue to database /// </summary> /// <returns>true if operation succeeded</returns> public bool Flush() { if (!localMutex.WaitOne(new TimeSpan(0, 0, 5), true)) return false; using (SqlConnection con = Database.Connection) { SqlBulkCopy bulkCopy = new SqlBulkCopy(con); bulkCopy.BulkCopyTimeout = 5; bulkCopy.ColumnMappings.Add(0, 1); bulkCopy.ColumnMappings.Add(1, 2); bulkCopy.ColumnMappings.Add(2, 3); bulkCopy.ColumnMappings.Add(3, 4); bulkCopy.DestinationTableName = "common.DBLog"; bulkCopy.WriteToServer(tmpTable); } tmpTable.Rows.Clear(); localMutex.ReleaseMutex(); return true; } private int _MaxCacheSize; /// <summary> /// Maximum log write queue size /// When queue reaches this amount, Flush method is called automatically /// </summary> public int MaxCacheSize { get { return _MaxCacheSize; } set { _MaxCacheSize = value; if (_MaxCacheSize < tmpTable.Rows.Count) { Flush(); } } } private TimeSpan _MaxWriteDelay; /// <summary> /// Maximum timeout to wait until flushing data to database /// Flush is called automatically after this timeout elapses /// </summary> public TimeSpan MaxWriteDelay { get { return _MaxWriteDelay; } set { _WriteDelayTimer.Stop(); _MaxWriteDelay = value; _WriteDelayTimer.Interval = (double)_MaxWriteDelay.Milliseconds; _WriteDelayTimer.Start(); } } #endregion #region IDisposable Members /// <summary> /// Dispose resources. Derived from IDisposable /// </summary> public void Dispose() { localMutex.Close(); _WriteDelayTimer.Stop(); _WriteDelayTimer.Close(); _WriteDelayTimer.Dispose(); //throw new Exception("The method or operation is not implemented."); } #endregion #region ILogger Members public string DefaultServiceSource { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class FloatSwizzleVec2Test { [Test] public void XYZW() { { var ov = new vec2(1.5f, 8f); var v = ov.swizzle.xx; Assert.AreEqual(1.5f, v.x); Assert.AreEqual(1.5f, v.y); } { var ov = new vec2(0.5f, -7f); var v = ov.swizzle.xxx; Assert.AreEqual(0.5f, v.x); Assert.AreEqual(0.5f, v.y); Assert.AreEqual(0.5f, v.z); } { var ov = new vec2(8.5f, -7.5f); var v = ov.swizzle.xxxx; Assert.AreEqual(8.5f, v.x); Assert.AreEqual(8.5f, v.y); Assert.AreEqual(8.5f, v.z); Assert.AreEqual(8.5f, v.w); } { var ov = new vec2(-3f, -4f); var v = ov.swizzle.xxxy; Assert.AreEqual(-3f, v.x); Assert.AreEqual(-3f, v.y); Assert.AreEqual(-3f, v.z); Assert.AreEqual(-4f, v.w); } { var ov = new vec2(-1.5f, 5.5f); var v = ov.swizzle.xxy; Assert.AreEqual(-1.5f, v.x); Assert.AreEqual(-1.5f, v.y); Assert.AreEqual(5.5f, v.z); } { var ov = new vec2(-8f, -4f); var v = ov.swizzle.xxyx; Assert.AreEqual(-8f, v.x); Assert.AreEqual(-8f, v.y); Assert.AreEqual(-4f, v.z); Assert.AreEqual(-8f, v.w); } { var ov = new vec2(-1.5f, -6.5f); var v = ov.swizzle.xxyy; Assert.AreEqual(-1.5f, v.x); Assert.AreEqual(-1.5f, v.y); Assert.AreEqual(-6.5f, v.z); Assert.AreEqual(-6.5f, v.w); } { var ov = new vec2(-2.5f, -7.5f); var v = ov.swizzle.xy; Assert.AreEqual(-2.5f, v.x); Assert.AreEqual(-7.5f, v.y); } { var ov = new vec2(-9.5f, 3f); var v = ov.swizzle.xyx; Assert.AreEqual(-9.5f, v.x); Assert.AreEqual(3f, v.y); Assert.AreEqual(-9.5f, v.z); } { var ov = new vec2(2f, 9.5f); var v = ov.swizzle.xyxx; Assert.AreEqual(2f, v.x); Assert.AreEqual(9.5f, v.y); Assert.AreEqual(2f, v.z); Assert.AreEqual(2f, v.w); } { var ov = new vec2(-1.5f, 8f); var v = ov.swizzle.xyxy; Assert.AreEqual(-1.5f, v.x); Assert.AreEqual(8f, v.y); Assert.AreEqual(-1.5f, v.z); Assert.AreEqual(8f, v.w); } { var ov = new vec2(7f, 3f); var v = ov.swizzle.xyy; Assert.AreEqual(7f, v.x); Assert.AreEqual(3f, v.y); Assert.AreEqual(3f, v.z); } { var ov = new vec2(0.5f, -6f); var v = ov.swizzle.xyyx; Assert.AreEqual(0.5f, v.x); Assert.AreEqual(-6f, v.y); Assert.AreEqual(-6f, v.z); Assert.AreEqual(0.5f, v.w); } { var ov = new vec2(-6.5f, 2.5f); var v = ov.swizzle.xyyy; Assert.AreEqual(-6.5f, v.x); Assert.AreEqual(2.5f, v.y); Assert.AreEqual(2.5f, v.z); Assert.AreEqual(2.5f, v.w); } { var ov = new vec2(5.5f, 5.5f); var v = ov.swizzle.yx; Assert.AreEqual(5.5f, v.x); Assert.AreEqual(5.5f, v.y); } { var ov = new vec2(-9f, -5.5f); var v = ov.swizzle.yxx; Assert.AreEqual(-5.5f, v.x); Assert.AreEqual(-9f, v.y); Assert.AreEqual(-9f, v.z); } { var ov = new vec2(-7f, 7f); var v = ov.swizzle.yxxx; Assert.AreEqual(7f, v.x); Assert.AreEqual(-7f, v.y); Assert.AreEqual(-7f, v.z); Assert.AreEqual(-7f, v.w); } { var ov = new vec2(3f, 3.5f); var v = ov.swizzle.yxxy; Assert.AreEqual(3.5f, v.x); Assert.AreEqual(3f, v.y); Assert.AreEqual(3f, v.z); Assert.AreEqual(3.5f, v.w); } { var ov = new vec2(-2f, -9.5f); var v = ov.swizzle.yxy; Assert.AreEqual(-9.5f, v.x); Assert.AreEqual(-2f, v.y); Assert.AreEqual(-9.5f, v.z); } { var ov = new vec2(-8f, -7.5f); var v = ov.swizzle.yxyx; Assert.AreEqual(-7.5f, v.x); Assert.AreEqual(-8f, v.y); Assert.AreEqual(-7.5f, v.z); Assert.AreEqual(-8f, v.w); } { var ov = new vec2(9f, -0.5f); var v = ov.swizzle.yxyy; Assert.AreEqual(-0.5f, v.x); Assert.AreEqual(9f, v.y); Assert.AreEqual(-0.5f, v.z); Assert.AreEqual(-0.5f, v.w); } { var ov = new vec2(5f, -8.5f); var v = ov.swizzle.yy; Assert.AreEqual(-8.5f, v.x); Assert.AreEqual(-8.5f, v.y); } { var ov = new vec2(6f, 5.5f); var v = ov.swizzle.yyx; Assert.AreEqual(5.5f, v.x); Assert.AreEqual(5.5f, v.y); Assert.AreEqual(6f, v.z); } { var ov = new vec2(-3.5f, 0.5f); var v = ov.swizzle.yyxx; Assert.AreEqual(0.5f, v.x); Assert.AreEqual(0.5f, v.y); Assert.AreEqual(-3.5f, v.z); Assert.AreEqual(-3.5f, v.w); } { var ov = new vec2(-1.5f, -2.5f); var v = ov.swizzle.yyxy; Assert.AreEqual(-2.5f, v.x); Assert.AreEqual(-2.5f, v.y); Assert.AreEqual(-1.5f, v.z); Assert.AreEqual(-2.5f, v.w); } { var ov = new vec2(-7f, 1f); var v = ov.swizzle.yyy; Assert.AreEqual(1f, v.x); Assert.AreEqual(1f, v.y); Assert.AreEqual(1f, v.z); } { var ov = new vec2(4.5f, 1f); var v = ov.swizzle.yyyx; Assert.AreEqual(1f, v.x); Assert.AreEqual(1f, v.y); Assert.AreEqual(1f, v.z); Assert.AreEqual(4.5f, v.w); } { var ov = new vec2(-7.5f, -6.5f); var v = ov.swizzle.yyyy; Assert.AreEqual(-6.5f, v.x); Assert.AreEqual(-6.5f, v.y); Assert.AreEqual(-6.5f, v.z); Assert.AreEqual(-6.5f, v.w); } } [Test] public void RGBA() { { var ov = new vec2(-3f, -0.5f); var v = ov.swizzle.rr; Assert.AreEqual(-3f, v.x); Assert.AreEqual(-3f, v.y); } { var ov = new vec2(4.5f, -0.5f); var v = ov.swizzle.rrr; Assert.AreEqual(4.5f, v.x); Assert.AreEqual(4.5f, v.y); Assert.AreEqual(4.5f, v.z); } { var ov = new vec2(0f, 8.5f); var v = ov.swizzle.rrrr; Assert.AreEqual(0f, v.x); Assert.AreEqual(0f, v.y); Assert.AreEqual(0f, v.z); Assert.AreEqual(0f, v.w); } { var ov = new vec2(8.5f, -3f); var v = ov.swizzle.rrrg; Assert.AreEqual(8.5f, v.x); Assert.AreEqual(8.5f, v.y); Assert.AreEqual(8.5f, v.z); Assert.AreEqual(-3f, v.w); } { var ov = new vec2(8f, 9.5f); var v = ov.swizzle.rrg; Assert.AreEqual(8f, v.x); Assert.AreEqual(8f, v.y); Assert.AreEqual(9.5f, v.z); } { var ov = new vec2(7.5f, 2f); var v = ov.swizzle.rrgr; Assert.AreEqual(7.5f, v.x); Assert.AreEqual(7.5f, v.y); Assert.AreEqual(2f, v.z); Assert.AreEqual(7.5f, v.w); } { var ov = new vec2(4.5f, -8f); var v = ov.swizzle.rrgg; Assert.AreEqual(4.5f, v.x); Assert.AreEqual(4.5f, v.y); Assert.AreEqual(-8f, v.z); Assert.AreEqual(-8f, v.w); } { var ov = new vec2(1f, 1f); var v = ov.swizzle.rg; Assert.AreEqual(1f, v.x); Assert.AreEqual(1f, v.y); } { var ov = new vec2(-8.5f, 5f); var v = ov.swizzle.rgr; Assert.AreEqual(-8.5f, v.x); Assert.AreEqual(5f, v.y); Assert.AreEqual(-8.5f, v.z); } { var ov = new vec2(6f, -3.5f); var v = ov.swizzle.rgrr; Assert.AreEqual(6f, v.x); Assert.AreEqual(-3.5f, v.y); Assert.AreEqual(6f, v.z); Assert.AreEqual(6f, v.w); } { var ov = new vec2(8.5f, 4f); var v = ov.swizzle.rgrg; Assert.AreEqual(8.5f, v.x); Assert.AreEqual(4f, v.y); Assert.AreEqual(8.5f, v.z); Assert.AreEqual(4f, v.w); } { var ov = new vec2(-4.5f, 2f); var v = ov.swizzle.rgg; Assert.AreEqual(-4.5f, v.x); Assert.AreEqual(2f, v.y); Assert.AreEqual(2f, v.z); } { var ov = new vec2(-8f, 2.5f); var v = ov.swizzle.rggr; Assert.AreEqual(-8f, v.x); Assert.AreEqual(2.5f, v.y); Assert.AreEqual(2.5f, v.z); Assert.AreEqual(-8f, v.w); } { var ov = new vec2(-8f, -4.5f); var v = ov.swizzle.rggg; Assert.AreEqual(-8f, v.x); Assert.AreEqual(-4.5f, v.y); Assert.AreEqual(-4.5f, v.z); Assert.AreEqual(-4.5f, v.w); } { var ov = new vec2(-0.5f, -7f); var v = ov.swizzle.gr; Assert.AreEqual(-7f, v.x); Assert.AreEqual(-0.5f, v.y); } { var ov = new vec2(2f, 7f); var v = ov.swizzle.grr; Assert.AreEqual(7f, v.x); Assert.AreEqual(2f, v.y); Assert.AreEqual(2f, v.z); } { var ov = new vec2(0f, -8.5f); var v = ov.swizzle.grrr; Assert.AreEqual(-8.5f, v.x); Assert.AreEqual(0f, v.y); Assert.AreEqual(0f, v.z); Assert.AreEqual(0f, v.w); } { var ov = new vec2(-1.5f, -4.5f); var v = ov.swizzle.grrg; Assert.AreEqual(-4.5f, v.x); Assert.AreEqual(-1.5f, v.y); Assert.AreEqual(-1.5f, v.z); Assert.AreEqual(-4.5f, v.w); } { var ov = new vec2(0f, 2.5f); var v = ov.swizzle.grg; Assert.AreEqual(2.5f, v.x); Assert.AreEqual(0f, v.y); Assert.AreEqual(2.5f, v.z); } { var ov = new vec2(-3f, -6f); var v = ov.swizzle.grgr; Assert.AreEqual(-6f, v.x); Assert.AreEqual(-3f, v.y); Assert.AreEqual(-6f, v.z); Assert.AreEqual(-3f, v.w); } { var ov = new vec2(-3f, -3f); var v = ov.swizzle.grgg; Assert.AreEqual(-3f, v.x); Assert.AreEqual(-3f, v.y); Assert.AreEqual(-3f, v.z); Assert.AreEqual(-3f, v.w); } { var ov = new vec2(-5f, -9f); var v = ov.swizzle.gg; Assert.AreEqual(-9f, v.x); Assert.AreEqual(-9f, v.y); } { var ov = new vec2(-8.5f, -8f); var v = ov.swizzle.ggr; Assert.AreEqual(-8f, v.x); Assert.AreEqual(-8f, v.y); Assert.AreEqual(-8.5f, v.z); } { var ov = new vec2(0.5f, -3.5f); var v = ov.swizzle.ggrr; Assert.AreEqual(-3.5f, v.x); Assert.AreEqual(-3.5f, v.y); Assert.AreEqual(0.5f, v.z); Assert.AreEqual(0.5f, v.w); } { var ov = new vec2(-8.5f, 2f); var v = ov.swizzle.ggrg; Assert.AreEqual(2f, v.x); Assert.AreEqual(2f, v.y); Assert.AreEqual(-8.5f, v.z); Assert.AreEqual(2f, v.w); } { var ov = new vec2(5.5f, 8.5f); var v = ov.swizzle.ggg; Assert.AreEqual(8.5f, v.x); Assert.AreEqual(8.5f, v.y); Assert.AreEqual(8.5f, v.z); } { var ov = new vec2(9.5f, -2f); var v = ov.swizzle.gggr; Assert.AreEqual(-2f, v.x); Assert.AreEqual(-2f, v.y); Assert.AreEqual(-2f, v.z); Assert.AreEqual(9.5f, v.w); } { var ov = new vec2(4f, 7f); var v = ov.swizzle.gggg; Assert.AreEqual(7f, v.x); Assert.AreEqual(7f, v.y); Assert.AreEqual(7f, v.z); Assert.AreEqual(7f, v.w); } } [Test] public void InlineXYZW() { { var v0 = new vec2(4f, 9.5f); var v1 = new vec2(6f, 3f); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(6f, v0.x); Assert.AreEqual(3f, v0.y); Assert.AreEqual(4f, v2.x); Assert.AreEqual(9.5f, v2.y); } } [Test] public void InlineRGBA() { { var v0 = new vec2(6.5f, -3.5f); var v1 = -5.5f; var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(-5.5f, v0.x); Assert.AreEqual(-3.5f, v0.y); Assert.AreEqual(6.5f, v2); } { var v0 = new vec2(-5f, -1f); var v1 = 7f; var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(-5f, v0.x); Assert.AreEqual(7f, v0.y); Assert.AreEqual(-1f, v2); } { var v0 = new vec2(5.5f, -5f); var v1 = new vec2(-0.5f, -7f); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(-0.5f, v0.x); Assert.AreEqual(-7f, v0.y); Assert.AreEqual(5.5f, v2.x); Assert.AreEqual(-5f, v2.y); } } } }
// 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.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in AcceptAsync that dereferences null SAEA argument")] [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ConnectAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveMessageFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendAsync that dereferences null SAEA argument")] [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")] [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA.SendPacketsElements")] [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendToAsync that dereferences null SAEA argument")] [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void Connect_ConnectTwice_NotSupported(int invalidatingAction) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction) { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); }); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); }); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); }); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); }); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); }); } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); }); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); }); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); }); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); }); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); }); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().ConnectAsync(new IPAddress[0], 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); }); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); }); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void EndConnect_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndConnect(Task.CompletedTask)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void EndSend_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndSend(Task.CompletedTask)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); }); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); }); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void EndSendto_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndSendTo(Task.CompletedTask)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null)); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Security; public sealed class LocalClientSecuritySettings { bool detectReplays; int replayCacheSize; TimeSpan replayWindow; TimeSpan maxClockSkew; bool cacheCookies; TimeSpan maxCookieCachingTime; TimeSpan sessionKeyRenewalInterval; TimeSpan sessionKeyRolloverInterval; bool reconnectTransportOnFailure; TimeSpan timestampValidityDuration; IdentityVerifier identityVerifier; int cookieRenewalThresholdPercentage; NonceCache nonceCache = null; LocalClientSecuritySettings(LocalClientSecuritySettings other) { this.detectReplays = other.detectReplays; this.replayCacheSize = other.replayCacheSize; this.replayWindow = other.replayWindow; this.maxClockSkew = other.maxClockSkew; this.cacheCookies = other.cacheCookies; this.maxCookieCachingTime = other.maxCookieCachingTime; this.sessionKeyRenewalInterval = other.sessionKeyRenewalInterval; this.sessionKeyRolloverInterval = other.sessionKeyRolloverInterval; this.reconnectTransportOnFailure = other.reconnectTransportOnFailure; this.timestampValidityDuration = other.timestampValidityDuration; this.identityVerifier = other.identityVerifier; this.cookieRenewalThresholdPercentage = other.cookieRenewalThresholdPercentage; this.nonceCache = other.nonceCache; } public bool DetectReplays { get { return this.detectReplays; } set { this.detectReplays = value; } } public int ReplayCacheSize { get { return this.replayCacheSize; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.ValueMustBeNonNegative))); } this.replayCacheSize = value; } } public TimeSpan ReplayWindow { get { return this.replayWindow; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.replayWindow = value; } } public TimeSpan MaxClockSkew { get { return this.maxClockSkew; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.maxClockSkew = value; } } public NonceCache NonceCache { get { return this.nonceCache; } set { this.nonceCache = value; } } public TimeSpan TimestampValidityDuration { get { return this.timestampValidityDuration; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.timestampValidityDuration = value; } } public bool CacheCookies { get { return this.cacheCookies; } set { this.cacheCookies = value; } } public TimeSpan MaxCookieCachingTime { get { return this.maxCookieCachingTime; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.maxCookieCachingTime = value; } } public int CookieRenewalThresholdPercentage { get { return this.cookieRenewalThresholdPercentage; } set { if (value < 0 || value > 100) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.ValueMustBeInRange, 0, 100))); } this.cookieRenewalThresholdPercentage = value; } } public TimeSpan SessionKeyRenewalInterval { get { return this.sessionKeyRenewalInterval; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.sessionKeyRenewalInterval = value; } } public TimeSpan SessionKeyRolloverInterval { get { return this.sessionKeyRolloverInterval; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRange0))); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.SFxTimeoutOutOfRangeTooBig))); } this.sessionKeyRolloverInterval = value; } } public bool ReconnectTransportOnFailure { get { return this.reconnectTransportOnFailure; } set { this.reconnectTransportOnFailure = value; } } public IdentityVerifier IdentityVerifier { get { return this.identityVerifier; } set { this.identityVerifier = value; } } public LocalClientSecuritySettings() { this.DetectReplays = SecurityProtocolFactory.defaultDetectReplays; this.ReplayCacheSize = SecurityProtocolFactory.defaultMaxCachedNonces; this.ReplayWindow = SecurityProtocolFactory.defaultReplayWindow; this.MaxClockSkew = SecurityProtocolFactory.defaultMaxClockSkew; this.TimestampValidityDuration = SecurityProtocolFactory.defaultTimestampValidityDuration; this.CacheCookies = IssuanceTokenProviderBase<IssuanceTokenProviderState>.defaultClientCacheTokens; this.MaxCookieCachingTime = IssuanceTokenProviderBase<IssuanceTokenProviderState>.DefaultClientMaxTokenCachingTime; this.SessionKeyRenewalInterval = SecuritySessionClientSettings.defaultKeyRenewalInterval; this.SessionKeyRolloverInterval = SecuritySessionClientSettings.defaultKeyRolloverInterval; this.ReconnectTransportOnFailure = SecuritySessionClientSettings.defaultTolerateTransportFailures; this.CookieRenewalThresholdPercentage = SpnegoTokenProvider.defaultServiceTokenValidityThresholdPercentage; this.IdentityVerifier = IdentityVerifier.CreateDefault(); this.nonceCache = null; } public LocalClientSecuritySettings Clone() { return new LocalClientSecuritySettings(this); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// CredentialOperations operations. /// </summary> internal partial class CredentialOperations : IServiceOperations<AutomationClient>, ICredentialOperations { /// <summary> /// Initializes a new instance of the CredentialOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal CredentialOperations(AutomationClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutomationClient /// </summary> public AutomationClient Client { get; private set; } /// <summary> /// Delete the credential. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='credentialName'> /// The name of credential. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string credentialName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (credentialName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "credentialName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("credentialName", credentialName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/credentials/{credentialName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{credentialName}", System.Uri.EscapeDataString(credentialName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the credential identified by credential name. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='credentialName'> /// The name of credential. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Credential>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string credentialName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (credentialName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "credentialName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("credentialName", credentialName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/credentials/{credentialName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{credentialName}", System.Uri.EscapeDataString(credentialName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Credential>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Credential>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create a credential. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='credentialName'> /// The parameters supplied to the create or update credential operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the create or update credential operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Credential>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string credentialName, CredentialCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (credentialName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "credentialName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("credentialName", credentialName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/credentials/{credentialName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{credentialName}", System.Uri.EscapeDataString(credentialName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Credential>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Credential>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Credential>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update a credential. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='credentialName'> /// The parameters supplied to the Update credential operation. /// </param> /// <param name='parameters'> /// The parameters supplied to the Update credential operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Credential>> UpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string credentialName, CredentialUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (credentialName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "credentialName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("credentialName", credentialName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/credentials/{credentialName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{credentialName}", System.Uri.EscapeDataString(credentialName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Credential>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Credential>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of credentials. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Credential>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/credentials").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Credential>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Credential>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of credentials. /// <see href="http://aka.ms/azureautomationsdk/credentialoperations" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Credential>>> ListByAutomationAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Credential>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Credential>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Collections; using newtelligence.DasBlog.Runtime; #region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion namespace newtelligence.DasBlog.Web.Services.Rsd { using System; using System.Xml; using System.Xml.Serialization; [XmlType(Namespace="", IncludeInSchema=false)] [XmlRoot("rsd", Namespace="http://archipelago.phrasewise.com/rsd")] public class RsdRoot { [XmlNamespaceDeclarations] public XmlSerializerNamespaces Namespaces; private string version; private RssServiceCollection services; public RsdRoot() { Namespaces = new XmlSerializerNamespaces(); services = new RssServiceCollection(); version = "1.0"; } [XmlAttribute("version")] public string Version { get { return version; } set { version = value; } } [XmlElement("service")] public RssServiceCollection Services { get { return services; } set { services = value; } } [XmlAnyElement] public XmlElement[] anyElements; [XmlAnyAttribute] public XmlAttribute[] anyAttributes; } [XmlRoot("service", Namespace="")] public class RsdService { string engineName; string engineLink; string homePageLink = ""; RsdApiCollection rsdApis = new RsdApiCollection(); [XmlElement("engineName")] public string EngineName { get { return engineName; } set { engineName = value; } } [XmlElement("engineLink")] public string EngineLink { get { return engineLink; } set { engineLink = value; } } [XmlElement("homePageLink", IsNullable=false)] public string HomePageLink { get { return homePageLink; } set { homePageLink = value; } } // [XmlIgnore] // public RsdApiCollection RsdApiCollection // // { get { return rsdApis; } set { rsdApis = value; } } [XmlArray("apis")] [XmlArrayItem("api")] public RsdApiCollection RsdApiCollection { get { return rsdApis; } set { rsdApis = value; } } [XmlAnyElement] public XmlElement[] anyElements; [XmlAnyAttribute] public XmlAttribute[] anyAttributes; public RsdService() { engineName = "newtelligence dasBlog "+GetType().Assembly.GetName().Version; engineLink = "http://dasblog.info/"; } } [Serializable] [XmlRoot(ElementName = "api")] public class RsdApi { string name; bool preferred; string apiLink; string blogID; [XmlAttribute("name")] public string Name { get { return name; } set { name = value; } } [XmlAttribute("preferred")] public bool Preferred { get { return preferred; } set { preferred = value; } } [XmlAttribute("apiLink")] public string ApiLink { get { return apiLink; } set { apiLink = value; } } [XmlAttribute("blogID")] public string BlogID { get { return blogID; } set { blogID = value; } } [XmlAnyElement] public XmlElement[] anyElements; [XmlAnyAttribute] public XmlAttribute[] anyAttributes; } /// <summary> /// A collection of elements of type RsdApi /// </summary> public class RsdApiCollection: System.Collections.CollectionBase { /// <summary> /// Initializes a new empty instance of the RsdApiCollection class. /// </summary> public RsdApiCollection() { // empty } /// <summary> /// Initializes a new instance of the RsdApiCollection class, containing elements /// copied from an array. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the new RsdApiCollection. /// </param> public RsdApiCollection(RsdApi[] items) { this.AddRange(items); } /// <summary> /// Initializes a new instance of the RsdApiCollection class, containing elements /// copied from another instance of RsdApiCollection /// </summary> /// <param name="items"> /// The RsdApiCollection whose elements are to be added to the new RsdApiCollection. /// </param> public RsdApiCollection(RsdApiCollection items) { this.AddRange(items); } /// <summary> /// Adds the elements of an array to the end of this RsdApiCollection. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the end of this RsdApiCollection. /// </param> public virtual void AddRange(RsdApi[] items) { foreach (RsdApi item in items) { this.List.Add(item); } } /// <summary> /// Adds the elements of another RsdApiCollection to the end of this RsdApiCollection. /// </summary> /// <param name="items"> /// The RsdApiCollection whose elements are to be added to the end of this RsdApiCollection. /// </param> public virtual void AddRange(RsdApiCollection items) { foreach (RsdApi item in items) { this.List.Add(item); } } /// <summary> /// Adds an instance of type RsdApi to the end of this RsdApiCollection. /// </summary> /// <param name="value"> /// The RsdApi to be added to the end of this RsdApiCollection. /// </param> public virtual void Add(RsdApi value) { this.List.Add(value); } /// <summary> /// Determines whether a specfic RsdApi value is in this RsdApiCollection. /// </summary> /// <param name="value"> /// The RsdApi value to locate in this RsdApiCollection. /// </param> /// <returns> /// true if value is found in this RsdApiCollection; /// false otherwise. /// </returns> public virtual bool Contains(RsdApi value) { return this.List.Contains(value); } /// <summary> /// Return the zero-based index of the first occurrence of a specific value /// in this RsdApiCollection /// </summary> /// <param name="value"> /// The RsdApi value to locate in the RsdApiCollection. /// </param> /// <returns> /// The zero-based index of the first occurrence of the _ELEMENT value if found; /// -1 otherwise. /// </returns> public virtual int IndexOf(RsdApi value) { return this.List.IndexOf(value); } /// <summary> /// Inserts an element into the RsdApiCollection at the specified index /// </summary> /// <param name="index"> /// The index at which the RsdApi is to be inserted. /// </param> /// <param name="value"> /// The RsdApi to insert. /// </param> public virtual void Insert(int index, RsdApi value) { this.List.Insert(index, value); } /// <summary> /// Gets or sets the RsdApi at the given index in this RsdApiCollection. /// </summary> public virtual RsdApi this[int index] { get { return (RsdApi) this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Removes the first occurrence of a specific RsdApi from this RsdApiCollection. /// </summary> /// <param name="value"> /// The RsdApi value to remove from this RsdApiCollection. /// </param> public virtual void Remove(RsdApi value) { this.List.Remove(value); } /// <summary> /// Type-specific enumeration class, used by RsdApiCollection.GetEnumerator. /// </summary> public class Enumerator: System.Collections.IEnumerator { private System.Collections.IEnumerator wrapped; public Enumerator(RsdApiCollection collection) { this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator(); } public RsdApi Current { get { return (RsdApi) (this.wrapped.Current); } } object System.Collections.IEnumerator.Current { get { return (RsdApi) (this.wrapped.Current); } } public bool MoveNext() { return this.wrapped.MoveNext(); } public void Reset() { this.wrapped.Reset(); } } /// <summary> /// Returns an enumerator that can iterate through the elements of this RsdApiCollection. /// </summary> /// <returns> /// An object that implements System.Collections.IEnumerator. /// </returns> public new virtual RsdApiCollection.Enumerator GetEnumerator() { return new RsdApiCollection.Enumerator(this); } } /// <summary> /// A collection of elements of type RsdService /// </summary> public class RssServiceCollection: System.Collections.CollectionBase { /// <summary> /// Initializes a new empty instance of the RssServiceCollection class. /// </summary> public RssServiceCollection() { // empty } /// <summary> /// Initializes a new instance of the RssServiceCollection class, containing elements /// copied from an array. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the new RssServiceCollection. /// </param> public RssServiceCollection(RsdService[] items) { this.AddRange(items); } /// <summary> /// Initializes a new instance of the RssServiceCollection class, containing elements /// copied from another instance of RssServiceCollection /// </summary> /// <param name="items"> /// The RssServiceCollection whose elements are to be added to the new RssServiceCollection. /// </param> public RssServiceCollection(RssServiceCollection items) { this.AddRange(items); } /// <summary> /// Adds the elements of an array to the end of this RssServiceCollection. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the end of this RssServiceCollection. /// </param> public virtual void AddRange(RsdService[] items) { foreach (RsdService item in items) { this.List.Add(item); } } /// <summary> /// Adds the elements of another RssServiceCollection to the end of this RssServiceCollection. /// </summary> /// <param name="items"> /// The RssServiceCollection whose elements are to be added to the end of this RssServiceCollection. /// </param> public virtual void AddRange(RssServiceCollection items) { foreach (RsdService item in items) { this.List.Add(item); } } /// <summary> /// Adds an instance of type RsdService to the end of this RssServiceCollection. /// </summary> /// <param name="value"> /// The RsdService to be added to the end of this RssServiceCollection. /// </param> public virtual void Add(RsdService value) { this.List.Add(value); } /// <summary> /// Determines whether a specfic RsdService value is in this RssServiceCollection. /// </summary> /// <param name="value"> /// The RsdService value to locate in this RssServiceCollection. /// </param> /// <returns> /// true if value is found in this RssServiceCollection; /// false otherwise. /// </returns> public virtual bool Contains(RsdService value) { return this.List.Contains(value); } /// <summary> /// Return the zero-based index of the first occurrence of a specific value /// in this RssServiceCollection /// </summary> /// <param name="value"> /// The RsdService value to locate in the RssServiceCollection. /// </param> /// <returns> /// The zero-based index of the first occurrence of the _ELEMENT value if found; /// -1 otherwise. /// </returns> public virtual int IndexOf(RsdService value) { return this.List.IndexOf(value); } /// <summary> /// Inserts an element into the RssServiceCollection at the specified index /// </summary> /// <param name="index"> /// The index at which the RsdService is to be inserted. /// </param> /// <param name="value"> /// The RsdService to insert. /// </param> public virtual void Insert(int index, RsdService value) { this.List.Insert(index, value); } /// <summary> /// Gets or sets the RsdService at the given index in this RssServiceCollection. /// </summary> public virtual RsdService this[int index] { get { return (RsdService) this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Removes the first occurrence of a specific RsdService from this RssServiceCollection. /// </summary> /// <param name="value"> /// The RsdService value to remove from this RssServiceCollection. /// </param> public virtual void Remove(RsdService value) { this.List.Remove(value); } /// <summary> /// Type-specific enumeration class, used by RssServiceCollection.GetEnumerator. /// </summary> public class Enumerator: System.Collections.IEnumerator { private System.Collections.IEnumerator wrapped; public Enumerator(RssServiceCollection collection) { this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator(); } public RsdService Current { get { return (RsdService) (this.wrapped.Current); } } object System.Collections.IEnumerator.Current { get { return (RsdService) (this.wrapped.Current); } } public bool MoveNext() { return this.wrapped.MoveNext(); } public void Reset() { this.wrapped.Reset(); } } /// <summary> /// Returns an enumerator that can iterate through the elements of this RssServiceCollection. /// </summary> /// <returns> /// An object that implements System.Collections.IEnumerator. /// </returns> public new virtual RssServiceCollection.Enumerator GetEnumerator() { return new RssServiceCollection.Enumerator(this); } } [XmlRoot("image")] public class ChannelImage { private string _url; private string _title; private string _link; // TODO: Add optional width and height elements as needed public ChannelImage(){} [XmlElement("url")] public string Url { get { return _url; } set { _url = value; } } [XmlElement("title")] public string Title { get { return _title; } set { _title = value; } } [XmlElement("link")] public string Link { get { return _link; } set { _link = value; } } } }
// Copyright (c) 2007 James Newton-King; 2014 Extesla, LLC. // // 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.Globalization; using OpenGamingLibrary.Json.Serialization; using OpenGamingLibrary.Json.Utilities; using System.Linq; namespace OpenGamingLibrary.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; internal ReadType _readType; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private readonly List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _stack.Count; if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) return depth; else return depth + 1; } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] { _currentPosition }); return JsonPosition.BuildPath(positions); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (depth < _stack.Count) return _stack[depth]; return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _stack = new List<JsonPosition>(4); _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) _hasExceededMaxDepth = false; return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract int? ReadAsInt32(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract string ReadAsString(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public abstract byte[] ReadAsBytes(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract decimal? ReadAsDecimal(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTime? ReadAsDateTime(); #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTimeOffset? ReadAsDateTimeOffset(); #endif internal virtual bool ReadInternal() { throw new NotImplementedException(); } #if !NET20 internal DateTimeOffset? ReadAsDateTimeOffsetInternal() { _readType = ReadType.ReadAsDateTimeOffset; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Date) { if (Value is DateTime) SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); return (DateTimeOffset)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } object temp; DateTimeOffset dt; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTimeOffset, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTimeOffset)temp; SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } #endif internal byte[] ReadAsBytesInternal() { _readType = ReadType.ReadAsBytes; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (IsWrappedInTypeObject()) { byte[] data = ReadAsBytes(); ReadInternal(); SetToken(JsonToken.Bytes, data, false); return data; } // attempt to convert possible base 64 string to bytes if (t == JsonToken.String) { string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } if (t == JsonToken.Null) return null; if (t == JsonToken.Bytes) { if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; } if (t == JsonToken.StartArray) { List<byte> data = new List<byte>(); while (ReadInternal()) { t = TokenType; switch (t) { case JsonToken.Integer: data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = data.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; case JsonToken.Comment: // skip break; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadAsDecimalInternal() { _readType = ReadType.ReadAsDecimal; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is decimal)) SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); return (decimal)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadAsInt32Internal() { _readType = ReadType.ReadAsInt32; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is int)) SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); return (int)Value; } if (t == JsonToken.Null) return null; int i; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal string ReadAsStringInternal() { _readType = ReadType.ReadAsString; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.String) return (string)Value; if (t == JsonToken.Null) return null; if (IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) s = ((IFormattable)Value).ToString(null, Culture); else s = Value.ToString(); SetToken(JsonToken.String, s, false); return s; } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal DateTime? ReadAsDateTimeInternal() { _readType = ReadType.ReadAsDateTime; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Date) return (DateTime)Value; if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } DateTime dt; object temp; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTime, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTime)temp; dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (TokenType == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } private bool IsWrappedInTypeObject() { _readType = ReadType.Read; if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReadInternal(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReadInternal(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return true; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) Read(); if (IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); if (updateIndex) UpdateScopeWithFinishedValue(); } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) _currentPosition.Position++; } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) _currentState = State.Start; else _currentState = State.Finished; } internal static bool IsPrimitiveToken(JsonToken token) { switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Undefined: case JsonToken.Null: case JsonToken.Date: case JsonToken.Bytes: return true; default: return false; } } internal static bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) Close(); } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } } }
using System; using UnityEngine; using UnityEditor; using System.CodeDom; using Microsoft.CSharp; using System.IO; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text; namespace Playflock.Log { [System.Serializable] public class HUDData : UnityEngine.Component { public string widgetName = ""; public string currentPath = ""; public bool isCreating = false; } public enum NamespaceType { System = 0, UnityEngine = 1, UnityEngineUI = 2 } public enum UeTypeCode { Color = 0 } public enum UeUiTypeCode { Button = 0, Image = 1, InputField = 2, Text = 3, Toggle = 4 } public class Member { public bool IsSerialized; public MemberAttributes Attribute; public string Name; public NamespaceType NamespaceType; public System.TypeCode SystemTypeCode; public UeTypeCode UeTypeCode; public UeUiTypeCode UeUiTypeCode; } public class HUDDebugFactory : EditorWindow { #region PRIVATE_VARIABLES private const string createMenuTitle = "Assets/Playflock/Create/HUDDebug"; private const string _nodeFolder = "/Nodes"; private const string _widgetFolder = "/Widgets"; private static EditorWindow window; /// <summary> /// Editor compiling status /// </summary> private bool isEditorBusy = false; private static string _rootPath; private string _nodeName; private Playflock.Log.NodeType _nodeType; private string _widgetName; private static Dictionary<Enum, string> _namespaceKV = new Dictionary<Enum, string>() { {NamespaceType.System, "System"}, {NamespaceType.UnityEngine, "UnityEngine"}, {NamespaceType.UnityEngineUI, "UnityEngine.UI"} }; private static List<Member> _widgetMembers = new List<Member>(); private Vector2 _membersScrollViewPos; private GameObject _templateWidget; #endregion public static void ShowCreateWindow() { window = (HUDDebugFactory) EditorWindow.GetWindow(typeof (HUDDebugFactory)); window.title = "Create HUD"; } private void InitHUDData() { EditorPrefs.SetString("nodeName", ""); EditorPrefs.SetString("widgetName", ""); EditorPrefs.SetBool("isCreatingNode", false); EditorPrefs.SetBool("isCreatingWidget", false); _rootPath = EditorPrefs.GetString("rootPath"); } #region UNITY_EVENTS void Awake() { InitHUDData(); } void Update() { if (EditorPrefs.GetBool("isCreatingNode")) { if (!EditorApplication.isCompiling) { isEditorBusy = false; AssetDatabase.Refresh(); EditorPrefs.SetBool("isCreatingNode", false); var go = new GameObject(); EditorPrefs.SetBool("isCreatingNode", false); go.AddComponent<RectTransform>(); #if UNITY_5 UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(go, "Assets/PlayFlock_Utils/HUDDebug/Editor/HUDDebugFactory.cs (126,21)", EditorPrefs.GetString("nodeName") + "Node"); #else string componentName = EditorPrefs.GetString( "nodeName" ) + "Node"; go.AddComponent( componentName ); #endif var path = EditorPrefs.GetString("rootPath") + _nodeFolder + "/" + EditorPrefs.GetString("nodeName") + "Node.prefab"; var relativePath = path.Substring(path.IndexOf("Assets/", StringComparison.Ordinal)); Debug.Log("Node prefab path : " + relativePath); PrefabUtility.CreatePrefab(relativePath, go); DestroyImmediate(go, false); AssetDatabase.Refresh(); Debug.Log("Create HUD node completed"); } else isEditorBusy = true; } if (EditorPrefs.GetBool("isCreatingWidget")) { if (!EditorApplication.isCompiling) { isEditorBusy = false; AssetDatabase.Refresh(); EditorPrefs.SetBool("isCreatingWidget", false); GameObject go = null; EditorPrefs.SetBool("isCreatingWidget", false); if (_templateWidget) go = (GameObject) Instantiate(_templateWidget); else { go = new GameObject(); go.AddComponent<RectTransform>(); } #if UNITY_5 UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(go, "Assets/PlayFlock_Utils/HUDDebug/Editor/HUDDebugFactory.cs (161,17)", EditorPrefs.GetString("widgetName") + "Widget"); #else string componentName = EditorPrefs.GetString("widgetName") + "Widget"; go.AddComponent(componentName); #endif var path = EditorPrefs.GetString("rootPath") + _widgetFolder + "/" + EditorPrefs.GetString("widgetName") + "Widget.prefab"; var relativePath = path.Substring(path.IndexOf("Assets/", StringComparison.Ordinal)); Debug.Log("Widget prefab path : " + relativePath); PrefabUtility.CreatePrefab(relativePath, go); DestroyImmediate(go, false); AssetDatabase.Refresh(); Debug.Log("Create HUD widget completed"); } else isEditorBusy = true; } } void OnGUI() { if (!isEditorBusy) { var isRootPathEmpty = String.IsNullOrEmpty( _rootPath ); if (isRootPathEmpty) { _rootPath = EditorPrefs.GetString("rootPath"); EditorGUILayout.HelpBox("Please select root directory of HUDDebug", MessageType.Error); } GUILayout.BeginHorizontal(); GUILayout.Label("Root path : " + _rootPath); if (GUILayout.Button("Select folder")) { var path = EditorUtility.OpenFolderPanel("Select HUDDebug folder", "Assets", ""); EditorPrefs.SetString("rootPath", path); _rootPath = path; } GUILayout.EndHorizontal(); GUILayout.Space(50f); GUILayout.Label("Node name:", GUILayout.MaxWidth(100f)); _nodeName = EditorPrefs.GetString("nodeName"); _nodeName = GUILayout.TextField(_nodeName, GUILayout.MaxWidth(400f)); EditorPrefs.SetString("nodeName", _nodeName); GUILayout.Space(10f); GUILayout.Label("Implementation type:", GUILayout.MaxWidth(150f)); _nodeType = (Playflock.Log.NodeType) EditorGUILayout.EnumPopup("", _nodeType, GUILayout.MaxWidth(200f)); GUILayout.Space(10f); GUILayout.Label("Widget name:", GUILayout.MaxWidth(100f)); _widgetName = EditorPrefs.GetString("widgetName"); _widgetName = GUILayout.TextField(_widgetName, GUILayout.MaxWidth(400f)); EditorPrefs.SetString("widgetName", _widgetName); _templateWidget = (GameObject) EditorGUILayout.ObjectField("From template:", _templateWidget, typeof (GameObject), true); GUILayout.Space(10f); GUILayout.BeginHorizontal(); GUILayout.Label("Members:", GUILayout.MaxWidth(100f)); if (GUILayout.Button("+", GUILayout.MaxWidth(30f))) { //add members Member member = new Member(); member.IsSerialized = false; member.Attribute = MemberAttributes.Public; member.NamespaceType = NamespaceType.System; member.Name = ""; member.SystemTypeCode = TypeCode.Boolean; member.UeTypeCode = UeTypeCode.Color; member.UeUiTypeCode = UeUiTypeCode.Text; _widgetMembers.Add(member); } GUILayout.EndHorizontal(); GUILayout.Space(10f); _membersScrollViewPos = GUILayout.BeginScrollView(_membersScrollViewPos); for (int i = 0; i < _widgetMembers.Count; i++) { GUILayout.BeginHorizontal(); _widgetMembers[i].Attribute = (MemberAttributes) EditorGUILayout.EnumPopup("", _widgetMembers[i].Attribute, GUILayout.MaxWidth(200f)); _widgetMembers[i].NamespaceType = (NamespaceType) EditorGUILayout.EnumPopup("", _widgetMembers[i].NamespaceType, GUILayout.MaxWidth(200f)); switch (_widgetMembers[i].NamespaceType) { case NamespaceType.System: _widgetMembers[i].SystemTypeCode = (System.TypeCode) EditorGUILayout.EnumPopup("", _widgetMembers[i].SystemTypeCode, GUILayout.MaxWidth(200f)); break; case NamespaceType.UnityEngine: _widgetMembers[i].UeTypeCode = (UeTypeCode) EditorGUILayout.EnumPopup("", _widgetMembers[i].UeTypeCode, GUILayout.MaxWidth(200f)); break; case NamespaceType.UnityEngineUI: _widgetMembers[i].UeUiTypeCode = (UeUiTypeCode) EditorGUILayout.EnumPopup("", _widgetMembers[i].UeUiTypeCode, GUILayout.MaxWidth(200f)); break; } GUILayout.Label("Name : ", GUILayout.MaxWidth(40f)); _widgetMembers[i].Name = GUILayout.TextArea(_widgetMembers[i].Name); _widgetMembers[i].IsSerialized = EditorGUILayout.Toggle(_widgetMembers[i].IsSerialized, GUILayout.MaxWidth(10f)); GUILayout.Label("IsSerialized", GUILayout.MaxWidth(80f)); if (GUILayout.Button("-", GUILayout.MaxWidth(30f))) { _widgetMembers.RemoveAt(i); } GUILayout.EndHorizontal(); GUILayout.Space(10f); } GUILayout.EndScrollView(); } if (!isEditorBusy && IsCreateAvailable()) { if (GUILayout.Button("Create HUD")) { if (File.Exists(_rootPath + _nodeFolder + "/" + EditorPrefs.GetString("nodeName") + "Node.cs")) { if ( !EditorUtility.DisplayDialog("HUD node", "File with same name already exists, replace it?", "Replace", "Cancel")) return; } if (File.Exists(_rootPath + _widgetFolder + "/" + EditorPrefs.GetString("widgetName") + "Widget.cs")) { if ( !EditorUtility.DisplayDialog("HUD widget", "File with same name already exists, replace it?", "Replace", "Cancel")) return; } Debug.Log("Creating HUD..."); if (!string.IsNullOrEmpty(EditorPrefs.GetString("nodeName"))) { CreateNodeScript(EditorPrefs.GetString("nodeName"), _nodeType); var nodeScriptPath = _rootPath + _nodeFolder + "/" + EditorPrefs.GetString("nodeName") + "Node.cs"; Debug.Log(nodeScriptPath); AssetDatabase.Refresh(); EditorPrefs.SetBool("isCreatingNode", true); } if (!string.IsNullOrEmpty(EditorPrefs.GetString("widgetName"))) { CreateWidgetScript(EditorPrefs.GetString("widgetName")); var widgetScriptPath = _rootPath + _widgetFolder + "/" + EditorPrefs.GetString("widgetName") + "Widget.cs"; Debug.Log(widgetScriptPath); AssetDatabase.Refresh(); EditorPrefs.SetBool("isCreatingWidget", true); } } } else if (!IsCreateAvailable()) { EditorGUILayout.HelpBox("Please fill at least one of the fields (Node or Widget)", MessageType.Warning); } else { EditorGUILayout.HelpBox("Please wait...", MessageType.Info); } Repaint(); } void OnDestroy() { _widgetMembers.Clear(); } #endregion private bool IsCreateAvailable() { return !String.IsNullOrEmpty(_nodeName) || !String.IsNullOrEmpty(_widgetName); } /// <summary> /// Create widget prefab and c# script with same name /// </summary> [MenuItem(createMenuTitle, false, 0)] static void Create() { ShowCreateWindow(); } #region CODE_GENERATOR private enum accessModifier { Public, Private } private static void CreateNodeScript(string name, Playflock.Log.NodeType nodeType) { var unit = new CodeCompileUnit(); //add namespace var importsNamespace = new CodeNamespace { Imports = { new CodeNamespaceImport("UnityEngine"), new CodeNamespaceImport("UnityEngine.UI"), new CodeNamespaceImport("System.Collections") } }; var playflockNamespace = new CodeNamespace("Playflock.Log.Node"); unit.Namespaces.Add(importsNamespace); unit.Namespaces.Add(playflockNamespace); // add class var declarationClass = new CodeTypeDeclaration(name + "Node"); declarationClass.IsClass = true; //inherits from declarationClass.BaseTypes.Add("HUDNode"); //Methods var baseMethod = new CodeMemberMethod(); switch (nodeType) { case Playflock.Log.NodeType.Toggle: baseMethod.Name = "OnToggle"; baseMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Boolean", "isOn")); baseMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; baseMethod.Statements.Add(new CodeSnippetStatement("\t\t\tbase.OnToggle( isOn );")); break; case Playflock.Log.NodeType.Button: baseMethod.Name = "OnClick"; baseMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; baseMethod.Statements.Add(new CodeSnippetStatement("\t\t\tbase.OnClick();")); break; } //Methods declarationClass.Members.Add(baseMethod); playflockNamespace.Types.Add(declarationClass); var provider = (CSharpCodeProvider) CodeDomProvider.CreateProvider("csharp"); var scriptPath = _rootPath + _nodeFolder + "/" + name + "Node.cs"; using (var sw = new StreamWriter(scriptPath, false)) { var tw = new IndentedTextWriter(sw, " "); //generate source code var options = new CodeGeneratorOptions(); options.BracingStyle = "C"; options.BlankLinesBetweenMembers = true; provider.GenerateCodeFromCompileUnit(unit, tw, options); tw.Close(); sw.Close(); } //delete autogenerated summary (optional) using (var Reader = new StreamReader(scriptPath)) { var fileContent = Reader.ReadToEnd(); var sb = new StringBuilder(fileContent); sb.Remove(0, 420); Reader.Close(); using (var streamWriter = new StreamWriter(scriptPath)) { streamWriter.Write(sb); streamWriter.Close(); } } //Debug.Log("HUD node script generation completed"); } private static void CreateWidgetScript(string name) { var unit = new CodeCompileUnit(); //add namespace var importsNamespace = new CodeNamespace { Imports = { new CodeNamespaceImport("UnityEngine"), new CodeNamespaceImport("UnityEngine.UI"), new CodeNamespaceImport("System.Collections") } }; var playflockNamespace = new CodeNamespace("Playflock.Log.Widget"); unit.Namespaces.Add(importsNamespace); unit.Namespaces.Add(playflockNamespace); // add class var declarationClass = new CodeTypeDeclaration(name + "Widget"); declarationClass.IsClass = true; //inherits from declarationClass.BaseTypes.Add("HUDWidget"); //add member (ex: private bool = false) //UnityEngine.UI List<CodeMemberField> memberFields = new List<CodeMemberField>(); foreach (var wm in _widgetMembers) { CodeMemberField activeField = null; switch (wm.NamespaceType) { case NamespaceType.System: activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.SystemTypeCode, wm.Name); break; case NamespaceType.UnityEngine: activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.UeTypeCode, wm.Name); break; case NamespaceType.UnityEngineUI: activeField = new CodeMemberField(_namespaceKV[wm.NamespaceType] + "." + wm.UeUiTypeCode, wm.Name); break; } activeField.Attributes = wm.Attribute; if (wm.IsSerialized) { var customAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof (SerializeField))); CodeAttributeDeclarationCollection declarationsCollection = new CodeAttributeDeclarationCollection(); declarationsCollection.Add(customAttribute); activeField.CustomAttributes = new CodeAttributeDeclarationCollection(declarationsCollection); } memberFields.Add(activeField); } //Methods var initializeMethod = new CodeMemberMethod(); initializeMethod.Name = "Initialize"; initializeMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; var drawMethod = new CodeMemberMethod(); drawMethod.Name = "Draw"; drawMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; foreach (var mf in memberFields) declarationClass.Members.Add(mf); declarationClass.Members.Add(initializeMethod); declarationClass.Members.Add(drawMethod); //var attribute = new CodeAttributeDeclaration( //new CodeTypeReference(typeof(SerializableAttribute))); //unit.AssemblyCustomAttributes.Add(attribute); playflockNamespace.Types.Add(declarationClass); var provider = (CSharpCodeProvider) CodeDomProvider.CreateProvider("csharp"); var scriptPath = _rootPath + _widgetFolder + "/" + name + "Widget.cs"; using (var sw = new StreamWriter(scriptPath, false)) { var tw = new IndentedTextWriter(sw, " "); //generate source code var options = new CodeGeneratorOptions(); options.BracingStyle = "C"; options.BlankLinesBetweenMembers = true; provider.GenerateCodeFromCompileUnit(unit, tw, options); tw.Close(); sw.Close(); } //delete autogenerated summary (optional) using (var Reader = new StreamReader(scriptPath)) { var fileContent = Reader.ReadToEnd(); var sb = new StringBuilder(fileContent); sb.Remove(0, 420); Reader.Close(); using (var streamWriter = new StreamWriter(scriptPath)) { streamWriter.Write(sb); streamWriter.Close(); } } //Debug.Log("HUD widget script generation completed"); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Server.Handlers.MapImage { public class MapAddServiceConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IMapImageService m_MapService; private IGridService m_GridService; private string m_ConfigName = "MapImageService"; public MapAddServiceConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); string mapService = serverConfig.GetString("LocalServiceModule", String.Empty); if (mapService == String.Empty) throw new Exception("No LocalServiceModule in config file"); Object[] args = new Object[] { config }; m_MapService = ServerUtils.LoadPlugin<IMapImageService>(mapService, args); string gridService = serverConfig.GetString("GridService", String.Empty); if (gridService != string.Empty) m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args); if (m_GridService != null) m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is ON"); else m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is OFF"); bool proxy = serverConfig.GetBoolean("HasProxy", false); IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); server.AddStreamHandler(new MapServerPostHandler(m_MapService, m_GridService, proxy, auth)); } } class MapServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IMapImageService m_MapService; private IGridService m_GridService; bool m_Proxy; public MapServerPostHandler(IMapImageService service, IGridService grid, bool proxy, IServiceAuth auth) : base("POST", "/map", auth) { m_MapService = service; m_GridService = grid; m_Proxy = proxy; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA")) { httpResponse.StatusCode = (int)OSHttpStatusCode.ClientErrorBadRequest; return FailureResult("Bad request."); } uint x = 0, y = 0; UInt32.TryParse(request["X"].ToString(), out x); UInt32.TryParse(request["Y"].ToString(), out y); m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y); // string type = "image/jpeg"; // // if (request.ContainsKey("TYPE")) // type = request["TYPE"].ToString(); if (m_GridService != null) { System.Net.IPAddress ipAddr = GetCallerIP(httpRequest); GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y)); if (r != null) { if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString()) { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address); return FailureResult("IP address of caller does not match IP address of registered region"); } } else { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}", ipAddr, x, y); return FailureResult("Region not found at given coordinates"); } } byte[] data = Convert.FromBase64String(request["DATA"].ToString()); string reason = string.Empty; bool result = m_MapService.AddMapTile((int)x, (int)y, data, out reason); if (result) return SuccessResult(); else return FailureResult(reason); } catch (Exception e) { m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return FailureResult("Unexpected server error"); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return Util.DocToBytes(doc); } private System.Net.IPAddress GetCallerIP(IOSHttpRequest request) { if (!m_Proxy) return request.RemoteIPEndPoint.Address; // We're behind a proxy string xff = "X-Forwarded-For"; string xffValue = request.Headers[xff.ToLower()]; if (xffValue == null || (xffValue != null && xffValue == string.Empty)) xffValue = request.Headers[xff]; if (xffValue == null || (xffValue != null && xffValue == string.Empty)) { m_log.WarnFormat("[MAP IMAGE HANDLER]: No XFF header"); return request.RemoteIPEndPoint.Address; } System.Net.IPEndPoint ep = Util.GetClientIPFromXFF(xffValue); if (ep != null) return ep.Address; // Oops return request.RemoteIPEndPoint.Address; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { if (processName == null) { processName = string.Empty; } Process[] procs = GetProcesses(machineName); var list = new List<Process>(); for (int i = 0; i < procs.Length; i++) { if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) { list.Add(procs[i]); } else { procs[i].Dispose(); } } return list.ToArray(); } /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { SetPrivilege(Interop.mincore.SeDebugPrivilege, (int)Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED); } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { SetPrivilege(Interop.mincore.SeDebugPrivilege, 0); } /// <summary>Stops the associated process immediately.</summary> public void Kill() { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_TERMINATE); if (!Interop.mincore.TerminateProcess(handle, -1)) throw new Win32Exception(); } finally { ReleaseProcessHandle(handle); } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { _signaled = false; } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { // Nop } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { SafeProcessHandle handle = null; bool exited; ProcessWaitHandle processWaitHandle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.SYNCHRONIZE, false); if (handle.IsInvalid) { exited = true; } else { processWaitHandle = new ProcessWaitHandle(handle); if (processWaitHandle.WaitOne(milliseconds)) { exited = true; _signaled = true; } else { exited = false; _signaled = false; } } } finally { if (processWaitHandle != null) { processWaitHandle.Dispose(); } // If we have a hard timeout, we cannot wait for the streams if (_output != null && milliseconds == Timeout.Infinite) { _output.WaitUtilEOF(); } if (_error != null && milliseconds == Timeout.Infinite) { _error.WaitUtilEOF(); } ReleaseProcessHandle(handle); } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { // We only return null if we couldn't find a main module. This could be because // the process hasn't finished loading the main module (most likely). // On NT, the first module is the main module. EnsureState(State.HaveId | State.IsLocal); ModuleInfo module = NtProcessManager.GetFirstModuleInfo(_processId); return (module != null ? new ProcessModule(module) : null); } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.mincore.ProcessOptions.SYNCHRONIZE, false); if (handle.IsInvalid) { _exited = true; } else { int localExitCode; // Although this is the wrong way to check whether the process has exited, // it was historically the way we checked for it, and a lot of code then took a dependency on // the fact that this would always be set before the pipes were closed, so they would read // the exit code out after calling ReadToEnd() or standard output or standard error. In order // to allow 259 to function as a valid exit code and to break as few people as possible that // took the ReadToEnd dependency, we check for an exit code before doing the more correct // check to see if we have been signalled. if (Interop.mincore.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.mincore.HandleOptions.STILL_ACTIVE) { _exitCode = localExitCode; _exited = true; } else { // The best check for exit is that the kernel process object handle is invalid, // or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE // does not guarantee the process is closed, // since some process could return an actual STILL_ACTIVE exit code (259). if (!_signaled) // if we just came from WaitForExit, don't repeat { using (var wh = new ProcessWaitHandle(handle)) { _signaled = wh.WaitOne(0); } } if (_signaled) { if (!Interop.mincore.GetExitCodeProcess(handle, out localExitCode)) throw new Win32Exception(); _exitCode = localExitCode; _exited = true; } } } } finally { ReleaseProcessHandle(handle); } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetProcessTimes().ExitTime; } } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return GetProcessTimes().PrivilegedProcessorTime; } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { return GetProcessTimes().StartTime; } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { return GetProcessTimes().TotalProcessorTime; } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return GetProcessTimes().UserProcessorTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION); bool disabled; if (!Interop.mincore.GetProcessPriorityBoost(handle, out disabled)) { throw new Win32Exception(); } return !disabled; } finally { ReleaseProcessHandle(handle); } } set { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION); if (!Interop.mincore.SetProcessPriorityBoost(handle, !value)) throw new Win32Exception(); } finally { ReleaseProcessHandle(handle); } } } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { get { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION); int value = Interop.mincore.GetPriorityClass(handle); if (value == 0) { throw new Win32Exception(); } return (ProcessPriorityClass)value; } finally { ReleaseProcessHandle(handle); } } set { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION); if (!Interop.mincore.SetPriorityClass(handle, (int)value)) { throw new Win32Exception(); } } finally { ReleaseProcessHandle(handle); } } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private IntPtr ProcessorAffinityCore { get { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION); IntPtr processAffinity, systemAffinity; if (!Interop.mincore.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity)) throw new Win32Exception(); return processAffinity; } finally { ReleaseProcessHandle(handle); } } set { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_SET_INFORMATION); if (!Interop.mincore.SetProcessAffinityMask(handle, value)) throw new Win32Exception(); } finally { ReleaseProcessHandle(handle); } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return unchecked((int)Interop.mincore.GetCurrentProcessId()); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { return GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_ALL_ACCESS); } /// <summary>Get the minimum and maximum working set limits.</summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION); // GetProcessWorkingSetSize is not exposed in coresys. We use // GetProcessWorkingSetSizeEx instead which also returns FLAGS which give some flexibility // in terms of Min and Max values which we neglect. int ignoredFlags; if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags)) { throw new Win32Exception(); } } finally { ReleaseProcessHandle(handle); } } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_SET_QUOTA); IntPtr min, max; int ignoredFlags; if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } if (newMin.HasValue) { min = newMin.Value; } if (newMax.HasValue) { max = newMax.Value; } if ((long)min > (long)max) { if (newMin != null) { throw new ArgumentException(SR.BadMinWorkset); } else { throw new ArgumentException(SR.BadMaxWorkset); } } // We use SetProcessWorkingSetSizeEx which gives an option to follow // the max and min value even in low-memory and abundant-memory situations. // However, we do not use these flags to emulate the existing behavior if (!Interop.mincore.SetProcessWorkingSetSizeEx(handle, min, max, 0)) { throw new Win32Exception(); } // The value may be rounded/changed by the OS, so go get it if (!Interop.mincore.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } resultingMin = min; resultingMax = max; } finally { ReleaseProcessHandle(handle); } } private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { // See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points: // * The handles are duplicated as non-inheritable before they are passed to CreateProcess so // that the child process can not close them // * CreateProcess allows you to redirect all or none of the standard IO handles, so we use // GetStdHandle for the handles that are not being redirected StringBuilder commandLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments); Interop.mincore.STARTUPINFO startupInfo = new Interop.mincore.STARTUPINFO(); Interop.mincore.PROCESS_INFORMATION processInfo = new Interop.mincore.PROCESS_INFORMATION(); Interop.mincore.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.mincore.SECURITY_ATTRIBUTES(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); bool retVal; int errorCode = 0; // handles used in parent process SafeFileHandle standardInputWritePipeHandle = null; SafeFileHandle standardOutputReadPipeHandle = null; SafeFileHandle standardErrorReadPipeHandle = null; GCHandle environmentHandle = new GCHandle(); lock (s_createProcessLock) { try { // set up the streams if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { if (startInfo.RedirectStandardInput) { CreatePipe(out standardInputWritePipeHandle, out startupInfo.hStdInput, true); } else { startupInfo.hStdInput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_INPUT_HANDLE), false); } if (startInfo.RedirectStandardOutput) { CreatePipe(out standardOutputReadPipeHandle, out startupInfo.hStdOutput, false); } else { startupInfo.hStdOutput = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_OUTPUT_HANDLE), false); } if (startInfo.RedirectStandardError) { CreatePipe(out standardErrorReadPipeHandle, out startupInfo.hStdError, false); } else { startupInfo.hStdError = new SafeFileHandle(Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_ERROR_HANDLE), false); } startupInfo.dwFlags = Interop.mincore.StartupInfoOptions.STARTF_USESTDHANDLES; } // set up the creation flags paramater int creationFlags = 0; if (startInfo.CreateNoWindow) creationFlags |= Interop.mincore.StartupInfoOptions.CREATE_NO_WINDOW; // set up the environment block parameter IntPtr environmentPtr = (IntPtr)0; if (startInfo._environmentVariables != null) { creationFlags |= Interop.mincore.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT; byte[] environmentBytes = EnvironmentVariablesToByteArray(startInfo._environmentVariables); environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned); environmentPtr = environmentHandle.AddrOfPinnedObject(); } string workingDirectory = startInfo.WorkingDirectory; if (workingDirectory == string.Empty) workingDirectory = Directory.GetCurrentDirectory(); if (startInfo.UserName.Length != 0) { Interop.mincore.LogonFlags logonFlags = (Interop.mincore.LogonFlags)0; if (startInfo.LoadUserProfile) { logonFlags = Interop.mincore.LogonFlags.LOGON_WITH_PROFILE; } try { } finally { retVal = Interop.mincore.CreateProcessWithLogonW( startInfo.UserName, startInfo.Domain, startInfo.PasswordInClearText, logonFlags, null, // we don't need this since all the info is in commandLine commandLine, creationFlags, environmentPtr, workingDirectory, startupInfo, // pointer to STARTUPINFO processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(processInfo.hThread); } if (!retVal) { if (errorCode == Interop.mincore.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.mincore.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) throw new Win32Exception(errorCode, SR.InvalidApplication); throw new Win32Exception(errorCode); } } else { try { } finally { retVal = Interop.mincore.CreateProcess( null, // we don't need this since all the info is in commandLine commandLine, // pointer to the command line string ref unused_SecAttrs, // address to process security attributes, we don't need to inheriat the handle ref unused_SecAttrs, // address to thread security attributes. true, // handle inheritance flag creationFlags, // creation flags environmentPtr, // pointer to new environment block workingDirectory, // pointer to current directory name startupInfo, // pointer to STARTUPINFO processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); if (processInfo.hProcess != (IntPtr)0 && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(processInfo.hThread); } if (!retVal) { if (errorCode == Interop.mincore.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.mincore.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) throw new Win32Exception(errorCode, SR.InvalidApplication); throw new Win32Exception(errorCode); } } } finally { // free environment block if (environmentHandle.IsAllocated) { environmentHandle.Free(); } startupInfo.Dispose(); } } if (startInfo.RedirectStandardInput) { Encoding enc = GetEncoding((int)Interop.mincore.GetConsoleCP()); _standardInput = new StreamWriter(new FileStream(standardInputWritePipeHandle, FileAccess.Write, 4096, false), enc, 4096); _standardInput.AutoFlush = true; } if (startInfo.RedirectStandardOutput) { Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.mincore.GetConsoleOutputCP()); _standardOutput = new StreamReader(new FileStream(standardOutputReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (startInfo.RedirectStandardError) { Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.mincore.GetConsoleOutputCP()); _standardError = new StreamReader(new FileStream(standardErrorReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } bool ret = false; if (!procSH.IsInvalid) { SetProcessHandle(procSH); SetProcessId((int)processInfo.dwProcessId); threadSH.Dispose(); ret = true; } return ret; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private bool _signaled; private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { // Construct a StringBuilder with the appropriate command line // to pass to CreateProcess. If the filename isn't already // in quotes, we quote it here. This prevents some security // problems (it specifies exactly which part of the string // is the file to execute). StringBuilder commandLine = new StringBuilder(); string fileName = executableFileName.Trim(); bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal)); if (!fileNameIsQuoted) { commandLine.Append("\""); } commandLine.Append(fileName); if (!fileNameIsQuoted) { commandLine.Append("\""); } if (!string.IsNullOrEmpty(arguments)) { commandLine.Append(" "); commandLine.Append(arguments); } return commandLine; } /// <summary>Gets timing information for the current process.</summary> private ProcessThreadTimes GetProcessTimes() { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.mincore.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false); if (handle.IsInvalid) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } ProcessThreadTimes processTimes = new ProcessThreadTimes(); if (!Interop.mincore.GetProcessTimes(handle, out processTimes._create, out processTimes._exit, out processTimes._kernel, out processTimes._user)) { throw new Win32Exception(); } return processTimes; } finally { ReleaseProcessHandle(handle); } } private static void SetPrivilege(string privilegeName, int attrib) { SafeTokenHandle hToken = null; Interop.mincore.LUID debugValue = new Interop.mincore.LUID(); // this is only a "pseudo handle" to the current process - no need to close it later SafeProcessHandle processHandle = Interop.mincore.GetCurrentProcess(); // get the process token so we can adjust the privilege on it. We DO need to // close the token when we're done with it. if (!Interop.mincore.OpenProcessToken(processHandle, Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken)) { throw new Win32Exception(); } try { if (!Interop.mincore.LookupPrivilegeValue(null, privilegeName, out debugValue)) { throw new Win32Exception(); } Interop.mincore.TokenPrivileges tkp = new Interop.mincore.TokenPrivileges(); tkp.Luid = debugValue; tkp.Attributes = attrib; Interop.mincore.AdjustTokenPrivileges(hToken, false, tkp, 0, IntPtr.Zero, IntPtr.Zero); // AdjustTokenPrivileges can return true even if it failed to // set the privilege, so we need to use GetLastError if (Marshal.GetLastWin32Error() != Interop.mincore.Errors.ERROR_SUCCESS) { throw new Win32Exception(); } } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(processToken)"); #endif if (hToken != null) { hToken.Dispose(); } } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. /// If a handle is stored in current process object, then use it. /// Note that the handle we stored in current process object will have all access we need. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "GetProcessHandle(access = 0x" + access.ToString("X8", CultureInfo.InvariantCulture) + ", throwIfExited = " + throwIfExited + ")"); #if DEBUG if (_processTracing.TraceVerbose) { StackFrame calledFrom = new StackTrace(true).GetFrame(0); Debug.WriteLine(" called from " + calledFrom.GetFileName() + ", line " + calledFrom.GetFileLineNumber()); } #endif #endif if (_haveProcessHandle) { if (throwIfExited) { // Since haveProcessHandle is true, we know we have the process handle // open with at least SYNCHRONIZE access, so we can wait on it with // zero timeout to see if the process has exited. using (ProcessWaitHandle waitHandle = new ProcessWaitHandle(_processHandle)) { if (waitHandle.WaitOne(0)) { if (_haveProcessId) throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); else throw new InvalidOperationException(SR.ProcessHasExitedNoId); } } } return _processHandle; } else { EnsureState(State.HaveId | State.IsLocal); SafeProcessHandle handle = SafeProcessHandle.InvalidHandle; handle = ProcessManager.OpenProcess(_processId, access, throwIfExited); if (throwIfExited && (access & Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0) { if (Interop.mincore.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.mincore.HandleOptions.STILL_ACTIVE) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } } return handle; } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access) { return GetProcessHandle(access, true); } private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.mincore.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize) { bool ret = Interop.mincore.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize); if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid) { throw new Win32Exception(); } } // Using synchronous Anonymous pipes for process input/output redirection means we would end up // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since // it will take advantage of the NT IO completion port infrastructure. But we can't really use // Overlapped I/O for process input/output as it would break Console apps (managed Console class // methods such as WriteLine as well as native CRT functions like printf) which are making an // assumption that the console standard handles (obtained via GetStdHandle()) are opened // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously! private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) { Interop.mincore.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.mincore.SECURITY_ATTRIBUTES(); securityAttributesParent.bInheritHandle = true; SafeFileHandle hTmp = null; try { if (parentInputs) { CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0); } else { CreatePipeWithSecurityAttributes(out hTmp, out childHandle, ref securityAttributesParent, 0); } // Duplicate the parent handle to be non-inheritable so that the child process // doesn't have access. This is done for correctness sake, exact reason is unclear. // One potential theory is that child process can do something brain dead like // closing the parent end of the pipe and there by getting into a blocking situation // as parent will not be draining the pipe at the other end anymore. SafeProcessHandle currentProcHandle = Interop.mincore.GetCurrentProcess(); if (!Interop.mincore.DuplicateHandle(currentProcHandle, hTmp, currentProcHandle, out parentHandle, 0, false, Interop.mincore.HandleOptions.DUPLICATE_SAME_ACCESS)) { throw new Win32Exception(); } } finally { if (hTmp != null && !hTmp.IsInvalid) { hTmp.Dispose(); } } } private static byte[] EnvironmentVariablesToByteArray(Dictionary<string, string> sd) { // get the keys string[] keys = new string[sd.Count]; byte[] envBlock = null; sd.Keys.CopyTo(keys, 0); // sort both by the keys // Windows 2000 requires the environment block to be sorted by the key // It will first converting the case the strings and do ordinal comparison. // We do not use Array.Sort(keys, values, IComparer) since it is only supported // in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0 // we workaround this by sorting only the keys and then lookup the values form the keys. Array.Sort(keys, StringComparer.OrdinalIgnoreCase); // create a list of null terminated "key=val" strings StringBuilder stringBuff = new StringBuilder(); for (int i = 0; i < sd.Count; ++i) { stringBuff.Append(keys[i]); stringBuff.Append('='); stringBuff.Append(sd[keys[i]]); stringBuff.Append('\0'); } // an extra null at the end indicates end of list. stringBuff.Append('\0'); envBlock = Encoding.Unicode.GetBytes(stringBuff.ToString()); return envBlock; } } }
// 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; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class GetEnumeratorStringDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { StringDictionary sd; IEnumerator en; DictionaryEntry curr; // Enumerator.Current value // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; // [] StringDictionary GetEnumerator() //----------------------------------------------------------------- sd = new StringDictionary(); // [] Enumerator for empty dictionary // en = sd.GetEnumerator(); string type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return false // bool res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // Filled collection // [] Enumerator for filled dictionary // for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } en = sd.GetEnumerator(); type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return true // for (int i = 0; i < sd.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = (DictionaryEntry)en.Current; // //enumerator enumerates in different than added order // so we'll check Contains // if (!sd.ContainsValue(curr.Value.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain value from enumerator", i)); } if (!sd.ContainsKey(curr.Key.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i)); } if (String.Compare(sd[curr.Key.ToString()], curr.Value.ToString()) != 0) { Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i)); } // while we didn't MoveNext, Current should return the same value DictionaryEntry curr1 = (DictionaryEntry)en.Current; if (!curr.Equals(curr1)) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // [] Modify dictionary when enumerating // if (sd.Count < 1) { for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } } en = sd.GetEnumerator(); res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false")); } curr = (DictionaryEntry)en.Current; int cnt = sd.Count; sd.Remove(keys[0]); if (sd.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item DictionaryEntry curr2 = (DictionaryEntry)en.Current; if (!curr.Equals(curr2)) { Assert.False(true, string.Format("Error, current returned different value after modification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // // [] Modify dictionary when enumerated beyond the end // sd.Clear(); for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } en = sd.GetEnumerator(); for (int i = 0; i < sd.Count; i++) { en.MoveNext(); } curr = (DictionaryEntry)en.Current; curr = (DictionaryEntry)en.Current; cnt = sd.Count; sd.Remove(keys[0]); if (sd.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item curr2 = (DictionaryEntry)en.Current; if (!curr.Equals(curr2)) { Assert.False(true, string.Format("Error, current returned different value after modification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); } } }
// 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. // File System.Windows.Controls.Slider.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class Slider : System.Windows.Controls.Primitives.RangeBase { #region Methods and constructors protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize) { return default(System.Windows.Size); } public override void OnApplyTemplate() { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnDecreaseLarge() { } protected virtual new void OnDecreaseSmall() { } protected virtual new void OnIncreaseLarge() { } protected virtual new void OnIncreaseSmall() { } protected virtual new void OnMaximizeValue() { } protected override void OnMaximumChanged(double oldMaximum, double newMaximum) { } protected virtual new void OnMinimizeValue() { } protected override void OnMinimumChanged(double oldMinimum, double newMinimum) { } protected override void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } protected virtual new void OnThumbDragCompleted(System.Windows.Controls.Primitives.DragCompletedEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnThumbDragDelta(System.Windows.Controls.Primitives.DragDeltaEventArgs e) { Contract.Requires(e != null); } protected virtual new void OnThumbDragStarted(System.Windows.Controls.Primitives.DragStartedEventArgs e) { Contract.Requires(e != null); } protected override void OnValueChanged(double oldValue, double newValue) { } public Slider() { } #endregion #region Properties and indexers public System.Windows.Controls.Primitives.AutoToolTipPlacement AutoToolTipPlacement { get { return default(System.Windows.Controls.Primitives.AutoToolTipPlacement); } set { } } public int AutoToolTipPrecision { get { return default(int); } set { } } public static System.Windows.Input.RoutedCommand DecreaseLarge { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public static System.Windows.Input.RoutedCommand DecreaseSmall { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public int Delay { get { return default(int); } set { } } public static System.Windows.Input.RoutedCommand IncreaseLarge { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public static System.Windows.Input.RoutedCommand IncreaseSmall { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public int Interval { get { return default(int); } set { } } public bool IsDirectionReversed { get { return default(bool); } set { } } public bool IsMoveToPointEnabled { get { return default(bool); } set { } } public bool IsSelectionRangeEnabled { get { return default(bool); } set { } } public bool IsSnapToTickEnabled { get { return default(bool); } set { } } public static System.Windows.Input.RoutedCommand MaximizeValue { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public static System.Windows.Input.RoutedCommand MinimizeValue { get { Contract.Ensures(Contract.Result<System.Windows.Input.RoutedCommand>() != null); return default(System.Windows.Input.RoutedCommand); } } public Orientation Orientation { get { return default(Orientation); } set { } } public double SelectionEnd { get { return default(double); } set { } } public double SelectionStart { get { return default(double); } set { } } public double TickFrequency { get { return default(double); } set { } } public System.Windows.Controls.Primitives.TickPlacement TickPlacement { get { return default(System.Windows.Controls.Primitives.TickPlacement); } set { } } public System.Windows.Media.DoubleCollection Ticks { get { return default(System.Windows.Media.DoubleCollection); } set { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty AutoToolTipPlacementProperty; public readonly static System.Windows.DependencyProperty AutoToolTipPrecisionProperty; public readonly static System.Windows.DependencyProperty DelayProperty; public readonly static System.Windows.DependencyProperty IntervalProperty; public readonly static System.Windows.DependencyProperty IsDirectionReversedProperty; public readonly static System.Windows.DependencyProperty IsMoveToPointEnabledProperty; public readonly static System.Windows.DependencyProperty IsSelectionRangeEnabledProperty; public readonly static System.Windows.DependencyProperty IsSnapToTickEnabledProperty; public readonly static System.Windows.DependencyProperty OrientationProperty; public readonly static System.Windows.DependencyProperty SelectionEndProperty; public readonly static System.Windows.DependencyProperty SelectionStartProperty; public readonly static System.Windows.DependencyProperty TickFrequencyProperty; public readonly static System.Windows.DependencyProperty TickPlacementProperty; public readonly static System.Windows.DependencyProperty TicksProperty; #endregion } }
namespace Nancy.Authentication.Forms.Tests { using System; using System.Linq; using System.Threading; using Bootstrapper; using Cryptography; using FakeItEasy; using Fakes; using Helpers; using Nancy.Security; using Nancy.Tests; using Nancy.Tests.Fakes; using Xunit; public class FormsAuthenticationFixture { private FormsAuthenticationConfiguration config; private FormsAuthenticationConfiguration secureConfig; private FormsAuthenticationConfiguration domainPathConfig; private NancyContext context; private Guid userGuid; private string validCookieValue = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithNoHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithEmptyHmac = HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithInvalidHmac = HttpUtility.UrlEncode("C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9"); private string cookieWithBrokenEncryptedData = HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9"); private CryptographyConfiguration cryptographyConfiguration; private string domain = ".nancyfx.org"; private string path = "/"; public FormsAuthenticationFixture() { this.cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); this.config = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false }; this.secureConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = true }; this.domainPathConfig = new FormsAuthenticationConfiguration() { CryptographyConfiguration = this.cryptographyConfiguration, RedirectUrl = "/login", UserMapper = A.Fake<IUserMapper>(), RequiresSSL = false, Domain = domain, Path = path }; this.context = new NancyContext { Request = new Request( "GET", new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" }) }; this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010"); } [Fact] public void Should_throw_with_null_application_pipelines_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(null, this.config)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_null_config_passed_to_enable() { var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null)); result.ShouldBeOfType(typeof(ArgumentNullException)); } [Fact] public void Should_throw_with_invalid_config_passed_to_enable() { var fakeConfig = A.Fake<FormsAuthenticationConfiguration>(); A.CallTo(() => fakeConfig.IsValid).Returns(false); var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig)); result.ShouldBeOfType(typeof(ArgumentException)); } [Fact] public void Should_add_a_pre_and_post_hook_when_enabled() { var pipelines = A.Fake<IPipelines>(); FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true() { var pipelines = A.Fake<IPipelines>(); this.config.DisableRedirect = true; FormsAuthentication.Enable(pipelines, this.config); A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored)) .MustNotHaveHappened(); } [Fact] public void Should_return_redirect_response_when_user_logs_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .HttpOnly.ShouldBeTrue(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First() .Expires.ShouldNotBeNull(); } [Fact] public void Should_encrypt_cookie_when_logging_in_with_redirect() { var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_encrypt_cookie_when_logging_in_without_redirect() { // Given var mockEncrypter = A.Fake<IEncryptionProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect() { var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1)); A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect() { // Given var fakeEncrypter = A.Fake<IEncryptionProvider>(); var fakeCryptoText = "FakeText"; A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored)) .Returns(fakeCryptoText); var mockHmac = A.Fake<IHmacProvider>(); this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac); FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1)); // Then A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_return_redirect_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); } [Fact] public void Should_return_ok_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.OK); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Value.ShouldBeEmpty(); cookie.Expires.ShouldNotBeNull(); (cookie.Expires < DateTime.Now).ShouldBeTrue(); } [Fact] public void Should_get_username_from_mapping_service_with_valid_cookie() { var fakePipelines = new Pipelines(); var mockMapper = A.Fake<IUserMapper>(); this.config.UserMapper = mockMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context)) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_user_in_context_with_valid_cookie() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity {UserName = "Bob"}; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeSameAs(fakeUser); } [Fact] public void Should_not_set_user_in_context_with_invalid_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_empty_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_user_in_context_with_no_hmac() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_not_set_username_in_context_with_broken_encryption_data() { var fakePipelines = new Pipelines(); var fakeMapper = A.Fake<IUserMapper>(); var fakeUser = new FakeUserIdentity { UserName = "Bob" }; A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser); this.config.UserMapper = fakeMapper; FormsAuthentication.Enable(fakePipelines, this.config); this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData); var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken()); context.CurrentUser.ShouldBeNull(); } [Fact] public void Should_retain_querystring_when_redirecting_to_login_page() { // Given var fakePipelines = new Pipelines(); FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = "next"; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = null; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty() { // Given var fakePipelines = new Pipelines(); this.config.RedirectQuerystringKey = string.Empty; FormsAuthentication.Enable(fakePipelines, this.config); var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "?foo=bar"), Response = HttpStatusCode.Unauthorized }; // When fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken()); // Then queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar"); } [Fact] public void Should_retain_querystring_when_redirecting_after_successfull_login() { // Given var queryContext = new NancyContext() { Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar") }; FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); // When var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1)); // Then result.Headers["Location"].ShouldEqual("/secure?foo=bar"); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.UserLoggedInResponse(userGuid); // Then result.Cookies .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName) .First() .Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/"); var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect() { // Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig); // When var result = FormsAuthentication.LogOutResponse(); // Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Secure.ShouldBeTrue(); } [Fact] public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing"); } [Fact] public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo"); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/moo"); } [Fact] public void Should_redirect_to_given_url_if_local() { FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config); context.Request.Query[config.RedirectQuerystringKey] = "~/login"; var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); result.ShouldBeOfType(typeof(Response)); result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther); result.Headers["Location"].ShouldEqual("/testing/login"); } [Fact] public void Should_set_Domain_when_config_provides_domain_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Domain.ShouldEqual(domain); } [Fact] public void Should_set_Path_when_config_provides_path_value() { //Given FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig); //When var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid); //Then var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First(); cookie.Path.ShouldEqual(path); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Drawing; using System.Globalization; using System.IO; using System.Text; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; using GongSolutions.Shell.Interop; namespace GongSolutions.Shell { /// <summary> /// Represents an item in the Windows Shell namespace. /// </summary> [TypeConverter(typeof(ShellItemConverter))] public class ShellItem : IEnumerable<ShellItem> { /// <summary> /// Initializes a new instance of the <see cref="ShellItem"/> class. /// </summary> /// /// <remarks> /// Takes a <see cref="Uri"/> containing the location of the ShellItem. /// This constructor accepts URIs using two schemes: /// /// - file: A file or folder in the computer's filesystem, e.g. /// file:///D:/Folder /// - shell: A virtual folder, or a file or folder referenced from /// a virtual folder, e.g. shell:///Personal/file.txt /// </remarks> /// /// <param name="uri"> /// A <see cref="Uri"/> containing the location of the ShellItem. /// </param> public ShellItem(Uri uri) { Initialize(uri); } /// <summary> /// Initializes a new instance of the <see cref="ShellItem"/> class. /// </summary> /// /// <remarks> /// Takes a <see cref="string"/> containing the location of the ShellItem. /// This constructor accepts URIs using two schemes: /// /// - file: A file or folder in the computer's filesystem, e.g. /// file:///D:/Folder /// - shell: A virtual folder, or a file or folder referenced from /// a virtual folder, e.g. shell:///Personal/file.txt /// </remarks> /// /// <param name="path"> /// A string containing a Uri with the location of the ShellItem. /// </param> public ShellItem(string path) { Initialize(new Uri(path)); } /// <summary> /// Initializes a new instance of the <see cref="ShellItem"/> class. /// </summary> /// /// <remarks> /// Takes an <see cref="Environment.SpecialFolder"/> containing the /// location of the folder. /// </remarks> /// /// <param name="folder"> /// An <see cref="Environment.SpecialFolder"/> containing the /// location of the folder. /// </param> public ShellItem(Environment.SpecialFolder folder) { IntPtr pidl; if (Shell32.SHGetSpecialFolderLocation(IntPtr.Zero, (CSIDL)folder, out pidl) == HResult.S_OK) { try { m_ComInterface = CreateItemFromIDList(pidl); } finally { Shell32.ILFree(pidl); } } else { // SHGetSpecialFolderLocation does not support many common // CSIDL values on Windows 98, but SHGetFolderPath in // ShFolder.dll does, so fall back to it if necessary. We // try SHGetSpecialFolderLocation first because it returns // a PIDL which is preferable to a path as it can express // virtual folder locations. StringBuilder path = new StringBuilder(); Marshal.ThrowExceptionForHR((int)Shell32.SHGetFolderPath( IntPtr.Zero, (CSIDL)folder, IntPtr.Zero, 0, path)); m_ComInterface = CreateItemFromParsingName(path.ToString()); } } /// <summary> /// Initializes a new instance of the <see cref="ShellItem"/> class. /// </summary> /// /// <remarks> /// Creates a ShellItem which is a named child of <paramref name="parent"/>. /// </remarks> /// /// <param name="parent"> /// The parent folder of the item. /// </param> /// /// <param name="name"> /// The name of the child item. /// </param> public ShellItem(ShellItem parent, string name) { if (parent.IsFileSystem) { // If the parent folder is in the file system, our best // chance of success is to use the FileSystemPath to // create the new item. Folders other than Desktop don't // seem to implement ParseDisplayName properly. m_ComInterface = CreateItemFromParsingName( Path.Combine(parent.FileSystemPath, name)); } else { IShellFolder folder = parent.GetIShellFolder(); uint eaten; IntPtr pidl; uint attributes = 0; folder.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, name, out eaten, out pidl, ref attributes); try { m_ComInterface = CreateItemFromIDList(pidl); } finally { Shell32.ILFree(pidl); } } } internal ShellItem(IntPtr pidl) { m_ComInterface = CreateItemFromIDList(pidl); } internal ShellItem(ShellItem parent, IntPtr pidl) { m_ComInterface = CreateItemWithParent(parent, pidl); } /// <summary> /// Initializes a new instance of the <see cref="ShellItem"/> class. /// </summary> /// /// <param name="comInterface"> /// An <see cref="IShellItem"/> representing the folder. /// </param> public ShellItem(IShellItem comInterface) { m_ComInterface = comInterface; } /// <summary> /// Compares two <see cref="IShellItem"/>s. The comparison is carried /// out by display order. /// </summary> /// /// <param name="item"> /// The item to compare. /// </param> /// /// <returns> /// 0 if the two items are equal. A negative number if /// <see langword="this"/> is before <paramref name="item"/> in /// display order. A positive number if /// <see langword="this"/> comes after <paramref name="item"/> in /// display order. /// </returns> public int Compare(ShellItem item) { int result = m_ComInterface.Compare(item.ComInterface, SICHINT.DISPLAY); return result; } /// <summary> /// Determines whether two <see cref="ShellItem"/>s refer to /// the same shell folder. /// </summary> /// /// <param name="obj"> /// The item to compare. /// </param> /// /// <returns> /// <see langword="true"/> if the two objects refer to the same /// folder, <see langword="false"/> otherwise. /// </returns> public override bool Equals(object obj) { if (obj is ShellItem) { ShellItem otherItem = (ShellItem)obj; bool result = m_ComInterface.Compare(otherItem.ComInterface, SICHINT.DISPLAY) == 0; // Sometimes, folders are reported as being unequal even when // they refer to the same folder, so double check by comparing // the file system paths. (This was showing up on Windows XP in // the SpecialFolders() test) if (!result) { result = IsFileSystem && otherItem.IsFileSystem && (FileSystemPath == otherItem.FileSystemPath); } return result; } else { return false; } } /// <summary> /// Returns the name of the item in the specified style. /// </summary> /// /// <param name="sigdn"> /// The style of display name to return. /// </param> /// /// <returns> /// A string containing the display name of the item. /// </returns> public string GetDisplayName(SIGDN sigdn) { IntPtr resultPtr = m_ComInterface.GetDisplayName(sigdn); string result = Marshal.PtrToStringUni(resultPtr); Marshal.FreeCoTaskMem(resultPtr); return result; } /// <summary> /// Returns an enumerator detailing the child items of the /// <see cref="ShellItem"/>. /// </summary> /// /// <remarks> /// This method returns all child item including hidden /// items. /// </remarks> /// /// <returns> /// An enumerator over all child items. /// </returns> public IEnumerator<ShellItem> GetEnumerator() { return GetEnumerator(SHCONTF.FOLDERS | SHCONTF.INCLUDEHIDDEN | SHCONTF.NONFOLDERS); } /// <summary> /// Returns an enumerator detailing the child items of the /// <see cref="ShellItem"/>. /// </summary> /// /// <param name="filter"> /// A filter describing the types of child items to be included. /// </param> /// /// <returns> /// An enumerator over all child items. /// </returns> public IEnumerator<ShellItem> GetEnumerator(SHCONTF filter) { IShellFolder folder = GetIShellFolder(); IEnumIDList enumId = GetIEnumIDList(folder, filter); uint count; IntPtr pidl; HResult result; if (enumId == null) { yield break; } result = enumId.Next(1, out pidl, out count); while (result == HResult.S_OK) { yield return new ShellItem(this, pidl); Shell32.ILFree(pidl); result = enumId.Next(1, out pidl, out count); } if (result != HResult.S_FALSE) { Marshal.ThrowExceptionForHR((int)result); } yield break; } /// <summary> /// Returns an enumerator detailing the child items of the /// <see cref="ShellItem"/>. /// </summary> /// /// <remarks> /// This method returns all child item including hidden /// items. /// </remarks> /// /// <returns> /// An enumerator over all child items. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an <see cref="ComTypes.IDataObject"/> representing the /// item. This object is used in drag and drop operations. /// </summary> public ComTypes.IDataObject GetIDataObject() { IntPtr result = m_ComInterface.BindToHandler(IntPtr.Zero, BHID.SFUIObject, typeof(ComTypes.IDataObject).GUID); return (ComTypes.IDataObject)Marshal.GetTypedObjectForIUnknown(result, typeof(ComTypes.IDataObject)); } /// <summary> /// Returns an <see cref="IDropTarget"/> representing the /// item. This object is used in drag and drop operations. /// </summary> public IDropTarget GetIDropTarget(System.Windows.Forms.Control control) { IntPtr result = GetIShellFolder().CreateViewObject(control.Handle, typeof(IDropTarget).GUID); return (IDropTarget)Marshal.GetTypedObjectForIUnknown(result, typeof(IDropTarget)); } /// <summary> /// Returns an <see cref="IShellFolder"/> representing the /// item. /// </summary> public IShellFolder GetIShellFolder() { IntPtr result = m_ComInterface.BindToHandler(IntPtr.Zero, BHID.SFObject, typeof(IShellFolder).GUID); return (IShellFolder)Marshal.GetTypedObjectForIUnknown(result, typeof(IShellFolder)); } /// <summary> /// Gets the index in the system image list of the icon representing /// the item. /// </summary> /// /// <param name="type"> /// The type of icon to retrieve. /// </param> /// /// <param name="flags"> /// Flags detailing additional information to be conveyed by the icon. /// </param> /// /// <returns></returns> public int GetSystemImageListIndex(ShellIconType type, ShellIconFlags flags) { SHFILEINFO info = new SHFILEINFO(); IntPtr result = Shell32.SHGetFileInfo(Pidl, 0, out info, Marshal.SizeOf(info), SHGFI.ICON | SHGFI.SYSICONINDEX | SHGFI.OVERLAYINDEX | SHGFI.PIDL | (SHGFI)type | (SHGFI)flags); if (result == IntPtr.Zero) { throw new Exception("Error retreiving shell folder icon"); } return info.iIcon; } /// <summary> /// Tests whether the <see cref="ShellItem"/> is the immediate parent /// of another item. /// </summary> /// /// <param name="item"> /// The potential child item. /// </param> public bool IsImmediateParentOf(ShellItem item) { return IsFolder && Shell32.ILIsParent(Pidl, item.Pidl, true); } /// <summary> /// Tests whether the <see cref="ShellItem"/> is the parent of /// another item. /// </summary> /// /// <param name="item"> /// The potential child item. /// </param> public bool IsParentOf(ShellItem item) { return IsFolder && Shell32.ILIsParent(Pidl, item.Pidl, false); } /// <summary> /// Returns a string representation of the <see cref="ShellItem"/>. /// </summary> public override string ToString() { return ToUri().ToString(); } /// <summary> /// Returns a URI representation of the <see cref="ShellItem"/>. /// </summary> public Uri ToUri() { KnownFolderManager manager = new KnownFolderManager(); StringBuilder path = new StringBuilder("shell:///"); KnownFolder knownFolder = manager.FindNearestParent(this); if (knownFolder != null) { List<string> folders = new List<string>(); ShellItem knownFolderItem = knownFolder.CreateShellItem(); ShellItem item = this; while (item != knownFolderItem) { folders.Add(item.GetDisplayName(SIGDN.PARENTRELATIVEPARSING)); item = item.Parent; } folders.Reverse(); path.Append(knownFolder.Name); foreach (string s in folders) { path.Append('/'); path.Append(s); } return new Uri(path.ToString()); } else { return new Uri(FileSystemPath); } } /// <summary> /// Gets a child item. /// </summary> /// /// <param name="name"> /// The name of the child item. /// </param> public ShellItem this[string name] { get { return new ShellItem(this, name); } } /// <summary> /// Tests if two <see cref="ShellItem"/>s refer to the same folder. /// </summary> /// /// <param name="a"> /// The first folder. /// </param> /// /// <param name="b"> /// The second folder. /// </param> public static bool operator !=(ShellItem a, ShellItem b) { if (object.ReferenceEquals(a, null)) { return !object.ReferenceEquals(b, null); } else { return !a.Equals(b); } } /// <summary> /// Tests if two <see cref="ShellItem"/>s refer to the same folder. /// </summary> /// /// <param name="a"> /// The first folder. /// </param> /// /// <param name="b"> /// The second folder. /// </param> public static bool operator ==(ShellItem a, ShellItem b) { if (object.ReferenceEquals(a, null)) { return object.ReferenceEquals(b, null); } else { return a.Equals(b); } } /// <summary> /// Gets the underlying <see cref="IShellItem"/> COM interface. /// </summary> public IShellItem ComInterface { get { return m_ComInterface; } } /// <summary> /// Gets the normal display name of the item. /// </summary> public string DisplayName { get { return GetDisplayName(SIGDN.NORMALDISPLAY); } } /// <summary> /// Gets the file system path of the item. /// </summary> public string FileSystemPath { get { return GetDisplayName(SIGDN.FILESYSPATH); } } /// <summary> /// Gets a value indicating whether the item has subfolders. /// </summary> public bool HasSubFolders { get { return m_ComInterface.GetAttributes(SFGAO.HASSUBFOLDER) != 0; } } /// <summary> /// Gets a value indicating whether the item is a file system item. /// </summary> public bool IsFileSystem { get { return m_ComInterface.GetAttributes(SFGAO.FILESYSTEM) != 0; } } /// <summary> /// Gets a value indicating whether the item is a file system item /// or the child of a file system item. /// </summary> public bool IsFileSystemAncestor { get { return m_ComInterface.GetAttributes(SFGAO.FILESYSANCESTOR) != 0; } } /// <summary> /// Gets a value indicating whether the item is a folder. /// </summary> public bool IsFolder { get { return m_ComInterface.GetAttributes(SFGAO.FOLDER) != 0; } } /// <summary> /// Gets a value indicating whether the item is read-only. /// </summary> public bool IsReadOnly { get { return m_ComInterface.GetAttributes(SFGAO.READONLY) != 0; } } /// <summary> /// Gets the item's parent. /// </summary> public ShellItem Parent { get { IShellItem item; HResult result = m_ComInterface.GetParent(out item); if (result == HResult.S_OK) { return new ShellItem(item); } else if (result == HResult.MK_E_NOOBJECT) { return null; } else { Marshal.ThrowExceptionForHR((int)result); return null; } } } /// <summary> /// Gets the item's parsing name. /// </summary> public string ParsingName { get { return GetDisplayName(SIGDN.DESKTOPABSOLUTEPARSING); } } /// <summary> /// Gets a PIDL representing the item. /// </summary> public IntPtr Pidl { get { return GetIDListFromObject(m_ComInterface); } } /// <summary> /// Gets the item's shell icon. /// </summary> public Icon ShellIcon { get { SHFILEINFO info = new SHFILEINFO(); IntPtr result = Shell32.SHGetFileInfo(Pidl, 0, out info, Marshal.SizeOf(info), SHGFI.ADDOVERLAYS | SHGFI.ICON | SHGFI.SMALLICON | SHGFI.PIDL); if (result == IntPtr.Zero) { throw new Exception("Error retreiving shell folder icon"); } return Icon.FromHandle(info.hIcon); } } /// <summary> /// Gets the item's tooltip text. /// </summary> public string ToolTipText { get { IntPtr result; IQueryInfo queryInfo; IntPtr infoTipPtr; string infoTip; try { IntPtr relativePidl = Shell32.ILFindLastID(Pidl); Parent.GetIShellFolder().GetUIObjectOf(IntPtr.Zero, 1, new IntPtr[] { relativePidl }, typeof(IQueryInfo).GUID, 0, out result); } catch (Exception) { return string.Empty; } queryInfo = (IQueryInfo) Marshal.GetTypedObjectForIUnknown(result, typeof(IQueryInfo)); queryInfo.GetInfoTip(0, out infoTipPtr); infoTip = Marshal.PtrToStringUni(infoTipPtr); Ole32.CoTaskMemFree(infoTipPtr); return infoTip; } } /// <summary> /// Gets the Desktop folder. /// </summary> public static ShellItem Desktop { get { if (m_Desktop == null) { IShellItem item; IntPtr pidl; Shell32.SHGetSpecialFolderLocation( IntPtr.Zero, (CSIDL)Environment.SpecialFolder.Desktop, out pidl); try { item = CreateItemFromIDList(pidl); } finally { Shell32.ILFree(pidl); } m_Desktop = new ShellItem(item); } return m_Desktop; } } internal static bool RunningVista { get { return Environment.OSVersion.Version.Major >= 6; } } void Initialize(Uri uri) { if (uri.Scheme == "file") { m_ComInterface = CreateItemFromParsingName(uri.LocalPath); } else if (uri.Scheme == "shell") { InitializeFromShellUri(uri); } else { throw new InvalidOperationException("Invalid uri scheme"); } } void InitializeFromShellUri(Uri uri) { KnownFolderManager manager = new KnownFolderManager(); string path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped); string knownFolder; string restOfPath; int separatorIndex = path.IndexOf('/'); if (separatorIndex != -1) { knownFolder = path.Substring(0, separatorIndex); restOfPath = path.Substring(separatorIndex + 1); } else { knownFolder = path; restOfPath = string.Empty; } m_ComInterface = manager.GetFolder(knownFolder).CreateShellItem().ComInterface; if (restOfPath != string.Empty) { m_ComInterface = this[restOfPath.Replace('/', '\\')].ComInterface; } } static IShellItem CreateItemFromIDList(IntPtr pidl) { if (RunningVista) { return Shell32.SHCreateItemFromIDList(pidl, typeof(IShellItem).GUID); } else { return new Interop.VistaBridge.ShellItemImpl( pidl, false); } } static IShellItem CreateItemFromParsingName(string path) { if (RunningVista) { return Shell32.SHCreateItemFromParsingName(path, IntPtr.Zero, typeof(IShellItem).GUID); } else { IShellFolder desktop = Desktop.GetIShellFolder(); uint attributes = 0; uint eaten; IntPtr pidl; desktop.ParseDisplayName(IntPtr.Zero, IntPtr.Zero, path, out eaten, out pidl, ref attributes); return new Interop.VistaBridge.ShellItemImpl( pidl, true); } } static IShellItem CreateItemWithParent(ShellItem parent, IntPtr pidl) { if (RunningVista) { return Shell32.SHCreateItemWithParent(IntPtr.Zero, parent.GetIShellFolder(), pidl, typeof(IShellItem).GUID); } else { Interop.VistaBridge.ShellItemImpl impl = (Interop.VistaBridge.ShellItemImpl)parent.ComInterface; return new Interop.VistaBridge.ShellItemImpl( Shell32.ILCombine(impl.Pidl, pidl), true); } } static IntPtr GetIDListFromObject(IShellItem item) { if (RunningVista) { return Shell32.SHGetIDListFromObject(item); } else { return ((Interop.VistaBridge.ShellItemImpl)item).Pidl; } } static IEnumIDList GetIEnumIDList(IShellFolder folder, SHCONTF flags) { IEnumIDList result; if (folder.EnumObjects(IntPtr.Zero, flags, out result) == HResult.S_OK) { return result; } else { return null; } } IShellItem m_ComInterface; static ShellItem m_Desktop; } class ShellItemConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } else { return base.CanConvertFrom(context, sourceType); } } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } else { return base.CanConvertTo(context, destinationType); } } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string s = (string)value; if (s.Length == 0) { return ShellItem.Desktop; } else { return new ShellItem(s); } } else { return base.ConvertFrom(context, culture, value); } } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is ShellItem) { Uri uri = ((ShellItem)value).ToUri(); if (destinationType == typeof(string)) { if (uri.Scheme == "file") { return uri.LocalPath; } else { return uri.ToString(); } } else if (destinationType == typeof(InstanceDescriptor)) { return new InstanceDescriptor( typeof(ShellItem).GetConstructor(new Type[] { typeof(string) }), new object[] { uri.ToString() }); } } return base.ConvertTo(context, culture, value, destinationType); } } /// <summary> /// Enumerates the types of shell icons. /// </summary> public enum ShellIconType { /// <summary>The system large icon type</summary> LargeIcon = SHGFI.LARGEICON, /// <summary>The system shell icon type</summary> ShellIcon = SHGFI.SHELLICONSIZE, /// <summary>The system small icon type</summary> SmallIcon = SHGFI.SMALLICON, } /// <summary> /// Enumerates the optional styles that can be applied to shell icons. /// </summary> [Flags] public enum ShellIconFlags { /// <summary>The icon is displayed opened.</summary> OpenIcon = SHGFI.OPENICON, /// <summary>Get the overlay for the icon as well.</summary> OverlayIndex = SHGFI.OVERLAYINDEX } }
// 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.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; namespace System.Data { /// <summary> /// Represents a databindable, customized view of a <see cref='System.Data.DataTable'/> /// for sorting, filtering, searching, editing, and navigation. /// </summary> [DefaultProperty(nameof(Table))] [DefaultEvent("PositionChanged")] public class DataView : MarshalByValueComponent, IBindingListView, System.ComponentModel.ITypedList, ISupportInitializeNotification { private DataViewManager _dataViewManager; private DataTable _table; private bool _locked = false; private Index _index; private Dictionary<string, Index> _findIndexes; private string _sort = string.Empty; /// <summary>Allow a user implemented comparision of two DataRow</summary> /// <remarks>User must use correct DataRowVersion in comparison or index corruption will happen</remarks> private System.Comparison<DataRow> _comparison; /// <summary> /// IFilter will allow LinqDataView to wrap <see cref='System.Predicate&lt;DataRow&gt;'/> instead of using a DataExpression /// </summary> private IFilter _rowFilter = null; private DataViewRowState _recordStates = DataViewRowState.CurrentRows; private bool _shouldOpen = true; private bool _open = false; private bool _allowNew = true; private bool _allowEdit = true; private bool _allowDelete = true; private bool _applyDefaultSort = false; internal DataRow _addNewRow; private ListChangedEventArgs _addNewMoved; private System.ComponentModel.ListChangedEventHandler _onListChanged; internal static ListChangedEventArgs s_resetEventArgs = new ListChangedEventArgs(ListChangedType.Reset, -1); private DataTable _delayedTable = null; private string _delayedRowFilter = null; private string _delayedSort = null; private DataViewRowState _delayedRecordStates = (DataViewRowState)(-1); private bool _fInitInProgress = false; private bool _fEndInitInProgress = false; /// <summary> /// You can't delay create the DataRowView instances since multiple thread read access is valid /// and each thread must obtain the same DataRowView instance and we want to avoid (inter)locking. /// </summary> /// <remarks> /// In V1.1, the DataRowView[] was recreated after every change. Each DataRowView was bound to a DataRow. /// In V2.0 Whidbey, the DataRowView retained but bound to an index instead of DataRow, allowing the DataRow to vary. /// In V2.0 Orcas, the DataRowView retained and bound to a DataRow, allowing the index to vary. /// </remarks> private Dictionary<DataRow, DataRowView> _rowViewCache = new Dictionary<DataRow, DataRowView>(DataRowReferenceComparer.s_default); /// <summary> /// This collection allows expression maintaince to (add / remove) from the index when it really should be a (change / move). /// </summary> private readonly Dictionary<DataRow, DataRowView> _rowViewBuffer = new Dictionary<DataRow, DataRowView>(DataRowReferenceComparer.s_default); private sealed class DataRowReferenceComparer : IEqualityComparer<DataRow> { internal static readonly DataRowReferenceComparer s_default = new DataRowReferenceComparer(); private DataRowReferenceComparer() { } public bool Equals(DataRow x, DataRow y) => x == (object)y; public int GetHashCode(DataRow obj) => obj._objectID; } private DataViewListener _dvListener = null; private static int s_objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); internal DataView(DataTable table, bool locked) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace("<ds.DataView.DataView|INFO> {0}, table={1}, locked={2}", ObjectID, (table != null) ? table.ObjectID : 0, locked); _dvListener = new DataViewListener(this); _locked = locked; _table = table; _dvListener.RegisterMetaDataEvents(_table); } /// <summary> /// Initializes a new instance of the <see cref='System.Data.DataView'/> class. /// </summary> public DataView() : this(null) { SetIndex2("", DataViewRowState.CurrentRows, null, true); } /// <summary> /// Initializes a new instance of the <see cref='System.Data.DataView'/> class with the /// specified <see cref='System.Data.DataTable'/>. /// </summary> public DataView(DataTable table) : this(table, false) { SetIndex2("", DataViewRowState.CurrentRows, null, true); } /// <summary> /// Initializes a new instance of the <see cref='System.Data.DataView'/> class with the /// specified <see cref='System.Data.DataTable'/>. /// </summary> public DataView(DataTable table, string RowFilter, string Sort, DataViewRowState RowState) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace("<ds.DataView.DataView|API> {0}, table={1}, RowFilter='{2}', Sort='{3}', RowState={4}", ObjectID, (table != null) ? table.ObjectID : 0, RowFilter, Sort, RowState); if (table == null) { throw ExceptionBuilder.CanNotUse(); } _dvListener = new DataViewListener(this); _locked = false; _table = table; _dvListener.RegisterMetaDataEvents(_table); if ((((int)RowState) & ((int)~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } else if ((((int)RowState) & ((int)DataViewRowState.ModifiedOriginal)) != 0 && (((int)RowState) & ((int)DataViewRowState.ModifiedCurrent)) != 0) { throw ExceptionBuilder.SetRowStateFilter(); } if (Sort == null) { Sort = string.Empty; } if (RowFilter == null) { RowFilter = string.Empty; } DataExpression newFilter = new DataExpression(table, RowFilter); SetIndex(Sort, RowState, newFilter); } /// <summary> /// Sets or gets a value indicating whether deletes are allowed. /// </summary> [DefaultValue(true)] public bool AllowDelete { get { return _allowDelete; } set { if (_allowDelete != value) { _allowDelete = value; OnListChanged(s_resetEventArgs); } } } /// <summary> /// Gets or sets a value indicating whether to use the default sort. /// </summary> [RefreshProperties(RefreshProperties.All)] [DefaultValue(false)] public bool ApplyDefaultSort { get { return _applyDefaultSort; } set { DataCommonEventSource.Log.Trace("<ds.DataView.set_ApplyDefaultSort|API> {0}, {1}", ObjectID, value); if (_applyDefaultSort != value) { _comparison = null; // clear the delegate to allow the Sort string to be effective _applyDefaultSort = value; UpdateIndex(true); OnListChanged(s_resetEventArgs); } } } /// <summary> /// Gets or sets a value indicating whether edits are allowed. /// </summary> [DefaultValue(true)] public bool AllowEdit { get { return _allowEdit; } set { if (_allowEdit != value) { _allowEdit = value; OnListChanged(s_resetEventArgs); } } } /// <summary> /// Gets or sets a value indicating whether the new rows can /// be added using the <see cref='System.Data.DataView.AddNew'/> /// method. /// </summary> [DefaultValue(true)] public bool AllowNew { get { return _allowNew; } set { if (_allowNew != value) { _allowNew = value; OnListChanged(s_resetEventArgs); } } } /// <summary> /// Gets the number of records in the <see cref='System.Data.DataView'/>. /// </summary> [Browsable(false)] public int Count { get { Debug.Assert(_rowViewCache.Count == CountFromIndex, "DataView.Count mismatch"); return _rowViewCache.Count; } } private int CountFromIndex => ((null != _index) ? _index.RecordCount : 0) + ((null != _addNewRow) ? 1 : 0); /// <summary> /// Gets the <see cref='System.Data.DataViewManager'/> associated with this <see cref='System.Data.DataView'/> . /// </summary> [Browsable(false)] public DataViewManager DataViewManager => _dataViewManager; [Browsable(false)] public bool IsInitialized => !_fInitInProgress; /// <summary> /// Gets a value indicating whether the data source is currently open and /// projecting views of data on the <see cref='System.Data.DataTable'/>. /// </summary> [Browsable(false)] protected bool IsOpen => _open; bool ICollection.IsSynchronized => false; /// <summary> /// Gets or sets the expression used to filter which rows are viewed in the <see cref='System.Data.DataView'/>. /// </summary> [DefaultValue("")] public virtual string RowFilter { get { DataExpression expression = (_rowFilter as DataExpression); return (expression == null ? "" : expression.Expression); // CONSIDER: return optimized expression here } set { if (value == null) { value = string.Empty; } DataCommonEventSource.Log.Trace("<ds.DataView.set_RowFilter|API> {0}, '{1}'", ObjectID, value); if (_fInitInProgress) { _delayedRowFilter = value; return; } CultureInfo locale = (_table != null ? _table.Locale : CultureInfo.CurrentCulture); if (null == _rowFilter || (string.Compare(RowFilter, value, false, locale) != 0)) { DataExpression newFilter = new DataExpression(_table, value); SetIndex(_sort, _recordStates, newFilter); } } } #region RowPredicateFilter /// <summary> /// The predicate delegate that will determine if a DataRow should be contained within the view. /// This RowPredicate property is mutually exclusive with the RowFilter property. /// </summary> internal Predicate<DataRow> RowPredicate { get { RowPredicateFilter filter = (GetFilter() as RowPredicateFilter); return ((null != filter) ? filter._predicateFilter : null); } set { if (!ReferenceEquals(RowPredicate, value)) { SetIndex(Sort, RowStateFilter, ((null != value) ? new RowPredicateFilter(value) : null)); } } } private sealed class RowPredicateFilter : System.Data.IFilter { internal readonly Predicate<DataRow> _predicateFilter; /// <summary></summary> internal RowPredicateFilter(Predicate<DataRow> predicate) { Debug.Assert(null != predicate, "null predicate"); _predicateFilter = predicate; } /// <summary></summary> bool IFilter.Invoke(DataRow row, DataRowVersion version) { Debug.Assert(DataRowVersion.Default != version, "not expecting Default"); Debug.Assert(DataRowVersion.Proposed != version, "not expecting Proposed"); return _predicateFilter(row); } } #endregion /// <summary> /// Gets or sets the row state filter used in the <see cref='System.Data.DataView'/>. /// </summary> [DefaultValue(DataViewRowState.CurrentRows)] public DataViewRowState RowStateFilter { get { return _recordStates; } set { DataCommonEventSource.Log.Trace("<ds.DataView.set_RowStateFilter|API> {0}, {1}", ObjectID, value); if (_fInitInProgress) { _delayedRecordStates = value; return; } if ((((int)value) & ((int)~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } else if ((((int)value) & ((int)DataViewRowState.ModifiedOriginal)) != 0 && (((int)value) & ((int)DataViewRowState.ModifiedCurrent)) != 0) { throw ExceptionBuilder.SetRowStateFilter(); } if (_recordStates != value) { SetIndex(_sort, value, _rowFilter); } } } /// <summary> /// Gets or sets the sort column or columns, and sort order for the table. /// </summary> [DefaultValue("")] public string Sort { get { if (_sort.Length == 0 && _applyDefaultSort && _table != null && _table._primaryIndex.Length > 0) { return _table.FormatSortString(_table._primaryIndex); } else { return _sort; } } set { if (value == null) { value = string.Empty; } DataCommonEventSource.Log.Trace("<ds.DataView.set_Sort|API> {0}, '{1}'", ObjectID, value); if (_fInitInProgress) { _delayedSort = value; return; } CultureInfo locale = (_table != null ? _table.Locale : CultureInfo.CurrentCulture); if (string.Compare(_sort, value, false, locale) != 0 || (null != _comparison)) { CheckSort(value); _comparison = null; // clear the delegate to allow the Sort string to be effective SetIndex(value, _recordStates, _rowFilter); } } } /// <summary>Allow a user implemented comparision of two DataRow</summary> /// <remarks>User must use correct DataRowVersion in comparison or index corruption will happen</remarks> internal System.Comparison<DataRow> SortComparison { get { return _comparison; } set { DataCommonEventSource.Log.Trace("<ds.DataView.set_SortComparison|API> {0}", ObjectID); if (!ReferenceEquals(_comparison, value)) { _comparison = value; SetIndex("", _recordStates, _rowFilter); } } } object ICollection.SyncRoot => this; /// <summary> /// Gets or sets the source <see cref='System.Data.DataTable'/>. /// </summary> [TypeConverterAttribute(typeof(DataTableTypeConverter))] [DefaultValue(null)] [RefreshProperties(RefreshProperties.All)] public DataTable Table { get { return _table; } set { DataCommonEventSource.Log.Trace("<ds.DataView.set_Table|API> {0}, {1}", ObjectID, (value != null) ? value.ObjectID : 0); if (_fInitInProgress && value != null) { _delayedTable = value; return; } if (_locked) { throw ExceptionBuilder.SetTable(); } if (_dataViewManager != null) { throw ExceptionBuilder.CanNotSetTable(); } if (value != null && value.TableName.Length == 0) { throw ExceptionBuilder.CanNotBindTable(); } if (_table != value) { _dvListener.UnregisterMetaDataEvents(); _table = value; if (_table != null) { _dvListener.RegisterMetaDataEvents(_table); } SetIndex2("", DataViewRowState.CurrentRows, null, false); if (_table != null) { OnListChanged(new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, new DataTablePropertyDescriptor(_table))); } // index was updated without firing the reset, fire it now OnListChanged(s_resetEventArgs); } } } object IList.this[int recordIndex] { get { return this[recordIndex]; } set { throw ExceptionBuilder.SetIListObject(); } } /// <summary> /// Gets a row of data from a specified table. /// </summary> public DataRowView this[int recordIndex] => GetRowView(GetRow(recordIndex)); /// <summary> /// Adds a new row of data to view. /// </summary> /// <remarks> /// Only one new row of data allowed at a time, so previous new row will be added to row collection. /// Unsupported pattern: dataTable.Rows.Add(dataView.AddNew().Row) /// </remarks> public virtual DataRowView AddNew() { long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataView.AddNew|API> {0}", ObjectID); try { CheckOpen(); if (!AllowNew) { throw ExceptionBuilder.AddNewNotAllowNull(); } if (_addNewRow != null) { _rowViewCache[_addNewRow].EndEdit(); } Debug.Assert(null == _addNewRow, "AddNew addNewRow is not null"); _addNewRow = _table.NewRow(); DataRowView drv = new DataRowView(this, _addNewRow); _rowViewCache.Add(_addNewRow, drv); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, IndexOf(drv))); return drv; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } public void BeginInit() { _fInitInProgress = true; } public void EndInit() { if (_delayedTable != null && _delayedTable.fInitInProgress) { _delayedTable._delayedViews.Add(this); return; } _fInitInProgress = false; _fEndInitInProgress = true; if (_delayedTable != null) { Table = _delayedTable; _delayedTable = null; } if (_delayedSort != null) { Sort = _delayedSort; _delayedSort = null; } if (_delayedRowFilter != null) { RowFilter = _delayedRowFilter; _delayedRowFilter = null; } if (_delayedRecordStates != (DataViewRowState)(-1)) { RowStateFilter = _delayedRecordStates; _delayedRecordStates = (DataViewRowState)(-1); } _fEndInitInProgress = false; SetIndex(Sort, RowStateFilter, _rowFilter); OnInitialized(); } private void CheckOpen() { if (!IsOpen) throw ExceptionBuilder.NotOpen(); } private void CheckSort(string sort) { if (_table == null) { throw ExceptionBuilder.CanNotUse(); } if (sort.Length == 0) { return; } _table.ParseSortString(sort); } /// <summary> /// Closes the <see cref='System.Data.DataView'/> /// </summary> protected void Close() { _shouldOpen = false; UpdateIndex(); _dvListener.UnregisterMetaDataEvents(); } public void CopyTo(Array array, int index) { if (null != _index) { RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(0); while (iterator.MoveNext()) { array.SetValue(GetRowView(iterator.Current), index); checked { index++; } } } if (null != _addNewRow) { array.SetValue(_rowViewCache[_addNewRow], index); } } private void CopyTo(DataRowView[] array, int index) { if (null != _index) { RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(0); while (iterator.MoveNext()) { array[index] = GetRowView(iterator.Current); checked { index++; } } } if (null != _addNewRow) { array[index] = _rowViewCache[_addNewRow]; } } /// <summary> /// Deletes a row at the specified index. /// </summary> public void Delete(int index) => Delete(GetRow(index)); internal void Delete(DataRow row) { if (null != row) { long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataView.Delete|API> {0}, row={1}", ObjectID, row._objectID); try { CheckOpen(); if (row == _addNewRow) { FinishAddNew(false); return; } if (!AllowDelete) { throw ExceptionBuilder.CanNotDelete(); } row.Delete(); } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } } protected override void Dispose(bool disposing) { if (disposing) { Close(); } base.Dispose(disposing); } /// <summary> /// Finds a row in the <see cref='System.Data.DataView'/> by the specified primary key value. /// </summary> public int Find(object key) => FindByKey(key); /// <summary>Find index of a DataRowView instance that matches the specified primary key value.</summary> internal virtual int FindByKey(object key) => _index.FindRecordByKey(key); /// <summary> /// Finds a row in the <see cref='System.Data.DataView'/> by the specified primary key values. /// </summary> public int Find(object[] key) => FindByKey(key); /// <summary>Find index of a DataRowView instance that matches the specified primary key values.</summary> internal virtual int FindByKey(object[] key) => _index.FindRecordByKey(key); /// <summary> /// Finds a row in the <see cref='System.Data.DataView'/> by the specified primary key value. /// </summary> public DataRowView[] FindRows(object key) => FindRowsByKey(new object[] { key }); /// <summary> /// Finds a row in the <see cref='System.Data.DataView'/> by the specified primary key values. /// </summary> public DataRowView[] FindRows(object[] key) => FindRowsByKey(key); /// <summary>Find DataRowView instances that match the specified primary key values.</summary> internal virtual DataRowView[] FindRowsByKey(object[] key) { long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataView.FindRows|API> {0}", ObjectID); try { Range range = _index.FindRecords(key); return GetDataRowViewFromRange(range); } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } /// <summary>Convert a Range into a DataRowView[].</summary> internal DataRowView[] GetDataRowViewFromRange(Range range) { if (range.IsNull) { return Array.Empty<DataRowView>(); } var rows = new DataRowView[range.Count]; for (int i = 0; i < rows.Length; i++) { rows[i] = this[i + range.Min]; } return rows; } internal void FinishAddNew(bool success) { Debug.Assert(null != _addNewRow, "null addNewRow"); DataCommonEventSource.Log.Trace("<ds.DataView.FinishAddNew|INFO> {0}, success={1}", ObjectID, success); DataRow newRow = _addNewRow; if (success) { if (DataRowState.Detached == newRow.RowState) { // MaintainDataView will translate the ItemAdded from the RowCollection into // into either an ItemMoved or no event, since it didn't change position. // also possible it's added to the RowCollection but filtered out of the view. _table.Rows.Add(newRow); } else { // this means that the record was added to the table by different means and not part of view newRow.EndEdit(); } } if (newRow == _addNewRow) { // this means that the record did not get to the view bool flag = _rowViewCache.Remove(_addNewRow); Debug.Assert(flag, "didn't remove addNewRow"); _addNewRow = null; if (!success) { newRow.CancelEdit(); } OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, Count)); } } /// <summary> /// xGets an enumerator for this <see cref='System.Data.DataView'/>. /// </summary> public IEnumerator GetEnumerator() { // V1.1 compatability: returning List<DataRowView>.GetEnumerator() from RowViewCache // prevents users from changing data without invalidating the enumerator // aka don't 'return this.RowViewCache.GetEnumerator()' var temp = new DataRowView[Count]; CopyTo(temp, 0); return temp.GetEnumerator(); } #region IList bool IList.IsReadOnly => false; bool IList.IsFixedSize => false; int IList.Add(object value) { if (value == null) { // null is default value, so we AddNew. AddNew(); return Count - 1; } throw ExceptionBuilder.AddExternalObject(); } void IList.Clear() { throw ExceptionBuilder.CanNotClear(); } bool IList.Contains(object value) => (0 <= IndexOf(value as DataRowView)); int IList.IndexOf(object value) => IndexOf(value as DataRowView); /// <summary>Return positional index of a <see cref="DataRowView"/> in this DataView</summary> /// <remarks>Behavioral change: will now return -1 once a DataRowView becomes detached.</remarks> internal int IndexOf(DataRowView rowview) { if (null != rowview) { if (ReferenceEquals(_addNewRow, rowview.Row)) { return Count - 1; } if ((null != _index) && (DataRowState.Detached != rowview.Row.RowState)) { DataRowView cached; // verify the DataRowView is one we currently track - not something previously detached if (_rowViewCache.TryGetValue(rowview.Row, out cached) && cached == (object)rowview) { return IndexOfDataRowView(rowview); } } } return -1; } private int IndexOfDataRowView(DataRowView rowview) { // rowview.GetRecord() may return the proposed record // the index will only contain the original or current record, never proposed. // return index.GetIndex(rowview.GetRecord()); return _index.GetIndex(rowview.Row.GetRecordFromVersion(rowview.Row.GetDefaultRowVersion(RowStateFilter) & ~DataRowVersion.Proposed)); } void IList.Insert(int index, object value) { throw ExceptionBuilder.InsertExternalObject(); } void IList.Remove(object value) { int index = IndexOf(value as DataRowView); if (0 <= index) { // must delegate to IList.RemoveAt ((IList)this).RemoveAt(index); } else { throw ExceptionBuilder.RemoveExternalObject(); } } void IList.RemoveAt(int index) => Delete(index); internal Index GetFindIndex(string column, bool keepIndex) { if (_findIndexes == null) { _findIndexes = new Dictionary<string, Index>(); } Index findIndex; if (_findIndexes.TryGetValue(column, out findIndex)) { if (!keepIndex) { _findIndexes.Remove(column); findIndex.RemoveRef(); if (findIndex.RefCount == 1) { // if we have created it and we are removing it, refCount is (1) findIndex.RemoveRef(); // if we are reusing the index created by others, refcount is (2) } } } else { if (keepIndex) { findIndex = _table.GetIndex(column, _recordStates, GetFilter()); _findIndexes[column] = findIndex; findIndex.AddRef(); } } return findIndex; } #endregion #region IBindingList implementation bool IBindingList.AllowNew => AllowNew; object IBindingList.AddNew() => AddNew(); bool IBindingList.AllowEdit => AllowEdit; bool IBindingList.AllowRemove => AllowDelete; bool IBindingList.SupportsChangeNotification => true; bool IBindingList.SupportsSearching => true; bool IBindingList.SupportsSorting => true; bool IBindingList.IsSorted => Sort.Length != 0; PropertyDescriptor IBindingList.SortProperty => GetSortProperty(); internal PropertyDescriptor GetSortProperty() { if (_table != null && _index != null && _index._indexFields.Length == 1) { return new DataColumnPropertyDescriptor(_index._indexFields[0].Column); } return null; } ListSortDirection IBindingList.SortDirection => (_index._indexFields.Length == 1 && _index._indexFields[0].IsDescending) ? ListSortDirection.Descending : ListSortDirection.Ascending; #endregion #region ListChanged & Initialized events /// <summary> /// Occurs when the list managed by the <see cref='System.Data.DataView'/> changes. /// </summary> public event ListChangedEventHandler ListChanged { add { DataCommonEventSource.Log.Trace("<ds.DataView.add_ListChanged|API> {0}", ObjectID); _onListChanged += value; } remove { DataCommonEventSource.Log.Trace("<ds.DataView.remove_ListChanged|API> {0}", ObjectID); _onListChanged -= value; } } public event EventHandler Initialized; #endregion #region IBindingList implementation void IBindingList.AddIndex(PropertyDescriptor property) => GetFindIndex(property.Name, keepIndex: true); void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) { Sort = CreateSortString(property, direction); } int IBindingList.Find(PropertyDescriptor property, object key) { // NOTE: this function had keepIndex previosely if (property != null) { bool created = false; Index findIndex = null; try { if ((null == _findIndexes) || !_findIndexes.TryGetValue(property.Name, out findIndex)) { created = true; findIndex = _table.GetIndex(property.Name, _recordStates, GetFilter()); findIndex.AddRef(); } Range recordRange = findIndex.FindRecords(key); if (!recordRange.IsNull) { // check to see if key is equal return _index.GetIndex(findIndex.GetRecord(recordRange.Min)); } } finally { if (created && (null != findIndex)) { findIndex.RemoveRef(); if (findIndex.RefCount == 1) { // if we have created it and we are removing it, refCount is (1) findIndex.RemoveRef(); // if we are reusing the index created by others, refcount is (2) } } } } return -1; } void IBindingList.RemoveIndex(PropertyDescriptor property) { // Ups: If we don't have index yet we will create it before destroing; Fix this later GetFindIndex(property.Name, /*keepIndex:*/false); } void IBindingList.RemoveSort() { DataCommonEventSource.Log.Trace("<ds.DataView.RemoveSort|API> {0}", ObjectID); Sort = string.Empty; } #endregion #region Additional method and properties for new interface IBindingListView void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) { if (sorts == null) { throw ExceptionBuilder.ArgumentNull(nameof(sorts)); } var sortString = new StringBuilder(); bool addCommaToString = false; foreach (ListSortDescription sort in sorts) { if (sort == null) { throw ExceptionBuilder.ArgumentContainsNull(nameof(sorts)); } PropertyDescriptor property = sort.PropertyDescriptor; if (property == null) { throw ExceptionBuilder.ArgumentNull(nameof(PropertyDescriptor)); } if (!_table.Columns.Contains(property.Name)) { // just check if column does not exist, we will handle duplicate column in Sort throw ExceptionBuilder.ColumnToSortIsOutOfRange(property.Name); } ListSortDirection direction = sort.SortDirection; if (addCommaToString) // (sortStr.Length != 0) { sortString.Append(','); } sortString.Append(CreateSortString(property, direction)); if (!addCommaToString) { addCommaToString = true; } } Sort = sortString.ToString(); // what if we dont have any valid sort criteira? we would reset the sort } private string CreateSortString(PropertyDescriptor property, ListSortDirection direction) { Debug.Assert(property != null, "property is null"); StringBuilder resultString = new StringBuilder(); resultString.Append('['); resultString.Append(property.Name); resultString.Append(']'); if (ListSortDirection.Descending == direction) { resultString.Append(" DESC"); } return resultString.ToString(); } void IBindingListView.RemoveFilter() { DataCommonEventSource.Log.Trace("<ds.DataView.RemoveFilter|API> {0}", ObjectID); RowFilter = string.Empty; } string IBindingListView.Filter { get { return RowFilter; } set { RowFilter = value; } } ListSortDescriptionCollection IBindingListView.SortDescriptions => GetSortDescriptions(); internal ListSortDescriptionCollection GetSortDescriptions() { ListSortDescription[] sortDescArray = Array.Empty<ListSortDescription>(); if (_table != null && _index != null && _index._indexFields.Length > 0) { sortDescArray = new ListSortDescription[_index._indexFields.Length]; for (int i = 0; i < _index._indexFields.Length; i++) { DataColumnPropertyDescriptor columnProperty = new DataColumnPropertyDescriptor(_index._indexFields[i].Column); if (_index._indexFields[i].IsDescending) { sortDescArray[i] = new ListSortDescription(columnProperty, ListSortDirection.Descending); } else { sortDescArray[i] = new ListSortDescription(columnProperty, ListSortDirection.Ascending); } } } return new ListSortDescriptionCollection(sortDescArray); } bool IBindingListView.SupportsAdvancedSorting => true; bool IBindingListView.SupportsFiltering => true; #endregion #region ITypedList string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { if (_table != null) { if (listAccessors == null || listAccessors.Length == 0) { return _table.TableName; } else { DataSet dataSet = _table.DataSet; if (dataSet != null) { DataTable foundTable = dataSet.FindTable(_table, listAccessors, 0); if (foundTable != null) { return foundTable.TableName; } } } } return string.Empty; } PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { if (_table != null) { if (listAccessors == null || listAccessors.Length == 0) { return _table.GetPropertyDescriptorCollection(null); } else { DataSet dataSet = _table.DataSet; if (dataSet == null) { return new PropertyDescriptorCollection(null); } DataTable foundTable = dataSet.FindTable(_table, listAccessors, 0); if (foundTable != null) { return foundTable.GetPropertyDescriptorCollection(null); } } } return new PropertyDescriptorCollection(null); } #endregion /// <summary> /// Gets the filter for the <see cref='System.Data.DataView'/>. /// </summary> internal virtual IFilter GetFilter() => _rowFilter; private int GetRecord(int recordIndex) { if (unchecked((uint)Count <= (uint)recordIndex)) { throw ExceptionBuilder.RowOutOfRange(recordIndex); } return recordIndex == _index.RecordCount ? _addNewRow.GetDefaultRecord() : _index.GetRecord(recordIndex); } /// <exception cref="IndexOutOfRangeException"></exception> internal DataRow GetRow(int index) { int count = Count; if (unchecked((uint)count <= (uint)index)) { throw ExceptionBuilder.GetElementIndex(index); } if ((index == (count - 1)) && (_addNewRow != null)) { // if we could rely on tempRecord being registered with recordManager // then this special case code would go away return _addNewRow; } return _table._recordManager[GetRecord(index)]; } private DataRowView GetRowView(int record) => GetRowView(_table._recordManager[record]); private DataRowView GetRowView(DataRow dr) => _rowViewCache[dr]; protected virtual void IndexListChanged(object sender, ListChangedEventArgs e) { if (ListChangedType.Reset != e.ListChangedType) { OnListChanged(e); } if (_addNewRow != null && _index.RecordCount == 0) { FinishAddNew(false); } if (ListChangedType.Reset == e.ListChangedType) { OnListChanged(e); } } internal void IndexListChangedInternal(ListChangedEventArgs e) { _rowViewBuffer.Clear(); if ((ListChangedType.ItemAdded == e.ListChangedType) && (null != _addNewMoved)) { if (_addNewMoved.NewIndex == _addNewMoved.OldIndex) { // ItemAdded for addNewRow which didn't change position // RowStateChange only triggers RowChanged, not ListChanged } else { // translate the ItemAdded into ItemMoved for addNewRow adding into sorted collection ListChangedEventArgs f = _addNewMoved; _addNewMoved = null; IndexListChanged(this, f); } } // the ItemAdded has to fire twice for AddNewRow (public IBindingList API documentation) IndexListChanged(this, e); } internal void MaintainDataView(ListChangedType changedType, DataRow row, bool trackAddRemove) { DataRowView buffer = null; switch (changedType) { case ListChangedType.ItemAdded: Debug.Assert(null != row, "MaintainDataView.ItemAdded with null DataRow"); if (trackAddRemove) { if (_rowViewBuffer.TryGetValue(row, out buffer)) { // help turn expression add/remove into a changed/move bool flag = _rowViewBuffer.Remove(row); Debug.Assert(flag, "row actually removed"); } } if (row == _addNewRow) { // DataView.AddNew().Row was added to DataRowCollection int index = IndexOfDataRowView(_rowViewCache[_addNewRow]); Debug.Assert(0 <= index, "ItemAdded was actually deleted"); _addNewRow = null; _addNewMoved = new ListChangedEventArgs(ListChangedType.ItemMoved, index, Count - 1); } else if (!_rowViewCache.ContainsKey(row)) { _rowViewCache.Add(row, buffer ?? new DataRowView(this, row)); } else { Debug.Assert(false, "ItemAdded DataRow already in view"); } break; case ListChangedType.ItemDeleted: Debug.Assert(null != row, "MaintainDataView.ItemDeleted with null DataRow"); Debug.Assert(row != _addNewRow, "addNewRow being deleted"); if (trackAddRemove) { // help turn expression add/remove into a changed/move _rowViewCache.TryGetValue(row, out buffer); if (null != buffer) { _rowViewBuffer.Add(row, buffer); } else { Debug.Assert(false, "ItemDeleted DataRow not in view tracking"); } } if (!_rowViewCache.Remove(row)) { Debug.Assert(false, "ItemDeleted DataRow not in view"); } break; case ListChangedType.Reset: Debug.Assert(null == row, "MaintainDataView.Reset with non-null DataRow"); ResetRowViewCache(); break; case ListChangedType.ItemChanged: case ListChangedType.ItemMoved: break; case ListChangedType.PropertyDescriptorAdded: case ListChangedType.PropertyDescriptorChanged: case ListChangedType.PropertyDescriptorDeleted: Debug.Assert(false, "unexpected"); break; } } /// <summary> /// Raises the <see cref='E:System.Data.DataView.ListChanged'/> event. /// </summary> protected virtual void OnListChanged(ListChangedEventArgs e) { DataCommonEventSource.Log.Trace("<ds.DataView.OnListChanged|INFO> {0}, ListChangedType={1}", ObjectID, e.ListChangedType); try { DataColumn col = null; string propertyName = null; switch (e.ListChangedType) { case ListChangedType.ItemChanged: // ItemChanged - a column value changed (0 <= e.OldIndex) // ItemChanged - a DataRow.RowError changed (-1 == e.OldIndex) // ItemChanged - RowState changed (e.NewIndex == e.OldIndex) case ListChangedType.ItemMoved: // ItemMoved - a column value affecting sort order changed // ItemMoved - a state change in equivalent fields Debug.Assert(((ListChangedType.ItemChanged == e.ListChangedType) && ((e.NewIndex == e.OldIndex) || (-1 == e.OldIndex))) || (ListChangedType.ItemMoved == e.ListChangedType && (e.NewIndex != e.OldIndex) && (0 <= e.OldIndex)), "unexpected ItemChanged|ItemMoved"); Debug.Assert(0 <= e.NewIndex, "negative NewIndex"); if (0 <= e.NewIndex) { DataRow dr = GetRow(e.NewIndex); if (dr.HasPropertyChanged) { col = dr.LastChangedColumn; propertyName = (null != col) ? col.ColumnName : string.Empty; } } break; case ListChangedType.ItemAdded: case ListChangedType.ItemDeleted: case ListChangedType.PropertyDescriptorAdded: case ListChangedType.PropertyDescriptorChanged: case ListChangedType.PropertyDescriptorDeleted: case ListChangedType.Reset: break; } if (_onListChanged != null) { if ((col != null) && (e.NewIndex == e.OldIndex)) { ListChangedEventArgs newEventArg = new ListChangedEventArgs(e.ListChangedType, e.NewIndex, new DataColumnPropertyDescriptor(col)); _onListChanged(this, newEventArg); } else { _onListChanged(this, e); } } if (null != propertyName) { // empty string if more than 1 column changed this[e.NewIndex].RaisePropertyChangedEvent(propertyName); } } catch (Exception f) when (Common.ADP.IsCatchableExceptionType(f)) { ExceptionBuilder.TraceExceptionWithoutRethrow(f); // ignore the exception } } private void OnInitialized() { Initialized?.Invoke(this, EventArgs.Empty); } /// <summary> /// Opens a <see cref='System.Data.DataView'/>. /// </summary> protected void Open() { _shouldOpen = true; UpdateIndex(); _dvListener.RegisterMetaDataEvents(_table); } protected void Reset() { if (IsOpen) { _index.Reset(); } } internal void ResetRowViewCache() { Dictionary<DataRow, DataRowView> rvc = new Dictionary<DataRow, DataRowView>(CountFromIndex, DataRowReferenceComparer.s_default); DataRowView drv; if (null != _index) { // this improves performance by iterating of the index instead of computing record by index RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(0); while (iterator.MoveNext()) { DataRow row = _table._recordManager[iterator.Current]; if (!_rowViewCache.TryGetValue(row, out drv)) { drv = new DataRowView(this, row); } rvc.Add(row, drv); } } if (null != _addNewRow) { _rowViewCache.TryGetValue(_addNewRow, out drv); Debug.Assert(null != drv, "didn't contain addNewRow"); rvc.Add(_addNewRow, drv); } Debug.Assert(rvc.Count == CountFromIndex, "didn't add expected count"); _rowViewCache = rvc; } internal void SetDataViewManager(DataViewManager dataViewManager) { if (_table == null) throw ExceptionBuilder.CanNotUse(); if (_dataViewManager != dataViewManager) { if (dataViewManager != null) { dataViewManager._nViews--; } _dataViewManager = dataViewManager; if (dataViewManager != null) { dataViewManager._nViews++; DataViewSetting dataViewSetting = dataViewManager.DataViewSettings[_table]; try { // sdub: check that we will not do unnesasary operation here if dataViewSetting.Sort == this.Sort ... _applyDefaultSort = dataViewSetting.ApplyDefaultSort; DataExpression newFilter = new DataExpression(_table, dataViewSetting.RowFilter); SetIndex(dataViewSetting.Sort, dataViewSetting.RowStateFilter, newFilter); } catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); // ignore the exception } _locked = true; } else { SetIndex("", DataViewRowState.CurrentRows, null); } } } internal virtual void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter) { SetIndex2(newSort, newRowStates, newRowFilter, true); } internal void SetIndex2(string newSort, DataViewRowState newRowStates, IFilter newRowFilter, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.DataView.SetIndex|INFO> {0}, newSort='{1}', newRowStates={2}", ObjectID, newSort, newRowStates); _sort = newSort; _recordStates = newRowStates; _rowFilter = newRowFilter; Debug.Assert((0 == (DataViewRowState.ModifiedCurrent & newRowStates)) || (0 == (DataViewRowState.ModifiedOriginal & newRowStates)), "asking DataViewRowState for both Original & Current records"); if (_fEndInitInProgress) { return; } if (fireEvent) { // old code path for virtual UpdateIndex UpdateIndex(true); } else { // new code path for RelatedView Debug.Assert(null == _comparison, "RelatedView should not have a comparison function"); UpdateIndex(true, false); } if (null != _findIndexes) { Dictionary<string, Index> indexes = _findIndexes; _findIndexes = null; foreach (KeyValuePair<string, Index> entry in indexes) { entry.Value.RemoveRef(); } } } protected void UpdateIndex() => UpdateIndex(false); protected virtual void UpdateIndex(bool force) => UpdateIndex(force, true); internal void UpdateIndex(bool force, bool fireEvent) { long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataView.UpdateIndex|INFO> {0}, force={1}", ObjectID, force); try { if (_open != _shouldOpen || force) { _open = _shouldOpen; Index newIndex = null; if (_open) { if (_table != null) { if (null != SortComparison) { // because an Index with a Comparison<DataRow is not sharable, directly create the index here newIndex = new Index(_table, SortComparison, ((DataViewRowState)_recordStates), GetFilter()); // bump the addref from 0 to 1 to added to table index collection // the bump from 1 to 2 will happen via DataViewListener.RegisterListChangedEvent newIndex.AddRef(); } else { newIndex = _table.GetIndex(Sort, ((DataViewRowState)_recordStates), GetFilter()); } } } if (_index == newIndex) { return; } DataTable table = _index != null ? _index.Table : newIndex.Table; if (_index != null) { _dvListener.UnregisterListChangedEvent(); } _index = newIndex; if (_index != null) { _dvListener.RegisterListChangedEvent(_index); } ResetRowViewCache(); if (fireEvent) { OnListChanged(s_resetEventArgs); } } } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } internal void ChildRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataRelationPropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : /*default*/ null ); } internal void ParentRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { DataRelationPropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : /*default*/ null ); } protected virtual void ColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { DataColumnPropertyDescriptor NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataColumnPropertyDescriptor((System.Data.DataColumn)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataColumnPropertyDescriptor((System.Data.DataColumn)e.Element)) : /*default*/ null ); } internal void ColumnCollectionChangedInternal(object sender, CollectionChangeEventArgs e) => ColumnCollectionChanged(sender, e); public DataTable ToTable() => ToTable(null, false, Array.Empty<string>()); public DataTable ToTable(string tableName) => ToTable(tableName, false, Array.Empty<string>()); public DataTable ToTable(bool distinct, params string[] columnNames) => ToTable(null, distinct, columnNames); public DataTable ToTable(string tableName, bool distinct, params string[] columnNames) { DataCommonEventSource.Log.Trace("<ds.DataView.ToTable|API> {0}, TableName='{1}', distinct={2}", ObjectID, tableName, distinct); if (columnNames == null) { throw ExceptionBuilder.ArgumentNull(nameof(columnNames)); } DataTable dt = new DataTable(); dt.Locale = _table.Locale; dt.CaseSensitive = _table.CaseSensitive; dt.TableName = ((null != tableName) ? tableName : _table.TableName); dt.Namespace = _table.Namespace; dt.Prefix = _table.Prefix; if (columnNames.Length == 0) { columnNames = new string[Table.Columns.Count]; for (int i = 0; i < columnNames.Length; i++) { columnNames[i] = Table.Columns[i].ColumnName; } } int[] columnIndexes = new int[columnNames.Length]; List<object[]> rowlist = new List<object[]>(); for (int i = 0; i < columnNames.Length; i++) { DataColumn dc = Table.Columns[columnNames[i]]; if (dc == null) { throw ExceptionBuilder.ColumnNotInTheUnderlyingTable(columnNames[i], Table.TableName); } dt.Columns.Add(dc.Clone()); columnIndexes[i] = Table.Columns.IndexOf(dc); } foreach (DataRowView drview in this) { object[] o = new object[columnNames.Length]; for (int j = 0; j < columnIndexes.Length; j++) { o[j] = drview[columnIndexes[j]]; } if (!distinct || !RowExist(rowlist, o)) { dt.Rows.Add(o); rowlist.Add(o); } } return dt; } private bool RowExist(List<object[]> arraylist, object[] objectArray) { for (int i = 0; i < arraylist.Count; i++) { object[] rows = arraylist[i]; bool retval = true; for (int j = 0; j < objectArray.Length; j++) { retval &= (rows[j].Equals(objectArray[j])); } if (retval) { return true; } } return false; } /// <summary> /// If <paramref name="view"/> is equivalent to the current view with regards to all properties. /// <see cref="RowFilter"/> and <see cref="Sort"/> may differ by <see cref="StringComparison.OrdinalIgnoreCase"/>. /// </summary> public virtual bool Equals(DataView view) { if ((null == view) || Table != view.Table || Count != view.Count || !string.Equals(RowFilter, view.RowFilter, StringComparison.OrdinalIgnoreCase) || // case insensitive !string.Equals(Sort, view.Sort, StringComparison.OrdinalIgnoreCase) || // case insensitive !ReferenceEquals(SortComparison, view.SortComparison) || !ReferenceEquals(RowPredicate, view.RowPredicate) || RowStateFilter != view.RowStateFilter || DataViewManager != view.DataViewManager || AllowDelete != view.AllowDelete || AllowNew != view.AllowNew || AllowEdit != view.AllowEdit) { return false; } return true; } internal int ObjectID => _objectID; } }
// 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 Xunit; /// <summary> /// NOTE: All tests checking the output file should always call Stop before checking because Stop will flush the file to disk. /// </summary> namespace System.ServiceProcess.Tests { [OuterLoop(/* Modifies machine state */)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Persistent issues starting test service on NETFX")] public class ServiceBaseTests : IDisposable { private const int connectionTimeout = 30000; private readonly TestServiceProvider _testService; private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); protected static bool IsProcessElevated => s_isElevated.Value; protected static bool IsElevatedAndSupportsEventLogs => IsProcessElevated && PlatformDetection.IsNotWindowsNanoServer; private bool _disposed; public ServiceBaseTests() { _testService = new TestServiceProvider(); } private void AssertExpectedProperties(ServiceController testServiceController) { var comparer = PlatformDetection.IsFullFramework ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; // Full framework upper cases the name Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName, comparer); Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName); Assert.Equal(_testService.TestMachineName, testServiceController.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType); Assert.True(testServiceController.CanPauseAndContinue); Assert.True(testServiceController.CanStop); Assert.True(testServiceController.CanShutdown); } // [Fact] // To cleanup lingering Test Services uncomment the Fact attribute, make it public and run the following command // msbuild /t:rebuildandtest /p:XunitMethodName=System.ServiceProcess.Tests.ServiceBaseTests.Cleanup /p:OuterLoop=true // Remember to comment out the Fact again before running tests otherwise it will cleanup tests running in parallel // and cause them to fail. private void Cleanup() { string currentService = ""; foreach (ServiceController controller in ServiceController.GetServices()) { try { currentService = controller.DisplayName; if (controller.DisplayName.StartsWith("Test Service")) { Console.WriteLine("Trying to clean-up " + currentService); TestServiceInstaller deleteService = new TestServiceInstaller() { ServiceName = controller.ServiceName }; deleteService.RemoveService(); Console.WriteLine("Cleaned up " + currentService); } } catch (Exception ex) { Console.WriteLine("Failed " + ex.Message); } } } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnStartThenStop() { ServiceController controller = ConnectToServer(); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnStartWithArgsThenStop() { ServiceController controller = ConnectToServer(); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); controller.Start(new string[] { "StartWithArguments", "a", "b", "c" }); _testService.Client = null; _testService.Client.Connect(); // There is no definite order between start and connected when tests are running on multiple threads. // In this case we dont care much about the order, so we are just checking whether the appropiate bytes have been sent. Assert.Equal((int)(PipeMessageByteCode.Connected | PipeMessageByteCode.Start), _testService.GetByte() | _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Running); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnPauseThenStop() { ServiceController controller = ConnectToServer(); controller.Pause(); Assert.Equal((int)PipeMessageByteCode.Pause, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Paused); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnPauseAndContinueThenStop() { ServiceController controller = ConnectToServer(); controller.Pause(); Assert.Equal((int)PipeMessageByteCode.Pause, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Paused); controller.Continue(); Assert.Equal((int)PipeMessageByteCode.Continue, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Running); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnExecuteCustomCommand() { ServiceController controller = ConnectToServer(); controller.ExecuteCommand(128); Assert.Equal(128, _testService.GetByte()); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsProcessElevated))] public void TestOnContinueBeforePause() { ServiceController controller = ConnectToServer(); controller.Continue(); controller.WaitForStatus(ServiceControllerStatus.Running); controller.Stop(); Assert.Equal((int)PipeMessageByteCode.Stop, _testService.GetByte()); controller.WaitForStatus(ServiceControllerStatus.Stopped); } [ConditionalFact(nameof(IsElevatedAndSupportsEventLogs))] public void LogWritten() { string serviceName = Guid.NewGuid().ToString(); // The default username for installing the service is NT AUTHORITY\\LocalService which does not have access to EventLog. // If the username is null, then the service is created under LocalSystem Account which have access to EventLog. var testService = new TestServiceProvider(serviceName, userName: null); Assert.True(EventLog.SourceExists(serviceName)); testService.DeleteTestServices(); } [ConditionalFact(nameof(IsElevatedAndSupportsEventLogs))] public void LogWritten_AutoLog_False() { string serviceName = nameof(LogWritten_AutoLog_False) + Guid.NewGuid().ToString(); var testService = new TestServiceProvider(serviceName); Assert.False(EventLog.SourceExists(serviceName)); testService.DeleteTestServices(); } [ConditionalFact(nameof(IsProcessElevated))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full Framework receives the Connected Byte Code after the Exception Thrown Byte Code")] public void PropagateExceptionFromOnStart() { string serviceName = nameof(PropagateExceptionFromOnStart) + Guid.NewGuid().ToString(); var testService = new TestServiceProvider(serviceName); testService.Client.Connect(connectionTimeout); Assert.Equal((int)PipeMessageByteCode.Connected, testService.GetByte()); Assert.Equal((int)PipeMessageByteCode.ExceptionThrown, testService.GetByte()); testService.DeleteTestServices(); } private ServiceController ConnectToServer() { _testService.Client.Connect(connectionTimeout); Assert.Equal((int)PipeMessageByteCode.Connected, _testService.GetByte()); ServiceController controller = new ServiceController(_testService.TestServiceName); AssertExpectedProperties(controller); return controller; } public void Dispose() { if (!_disposed) { _testService.DeleteTestServices(); _disposed = true; } } } }
/* * 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 copyrightD * 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.Linq; using System.Text; using OpenSim.Framework; using OMV = OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS { public class BSPrimLinkable : BSPrimDisplaced { // The purpose of this subclass is to add linkset functionality to the prim. This overrides // operations necessary for keeping the linkset created and, additionally, this // calls the linkset implementation for its creation and management. #pragma warning disable 414 private static readonly string LogHeader = "[BULLETS PRIMLINKABLE]"; #pragma warning restore 414 // This adds the overrides for link() and delink() so the prim is linkable. public BSLinkset Linkset { get; set; } // The index of this child prim. public int LinksetChildIndex { get; set; } public BSLinkset.LinksetImplementation LinksetType { get; set; } public BSPrimLinkable(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) : base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical) { // Default linkset implementation for this prim LinksetType = (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation; Linkset = BSLinkset.Factory(PhysScene, this); Linkset.Refresh(this); } public override void Destroy() { Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime */); base.Destroy(); } public override void link(OpenSim.Region.PhysicsModules.SharedBase.PhysicsActor obj) { BSPrimLinkable parent = obj as BSPrimLinkable; if (parent != null) { BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = parent.Linkset.AddMeToLinkset(this); DetailLog("{0},BSPrimLinkable.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } return; } public override void delink() { // TODO: decide if this parent checking needs to happen at taint time // Race condition here: if link() and delink() in same simulation tick, the delink will not happen BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/); DetailLog("{0},BSPrimLinkable.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); return; } // When simulator changes position, this might be moving a child of the linkset. public override OMV.Vector3 Position { get { return base.Position; } set { base.Position = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); } } // When simulator changes orientation, this might be moving a child of the linkset. public override OMV.Quaternion Orientation { get { return base.Orientation; } set { base.Orientation = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); } } public override float TotalMass { get { return Linkset.LinksetMass; } } public override OMV.Vector3 CenterOfMass { get { return Linkset.CenterOfMass; } } public override OMV.Vector3 GeometricCenter { get { return Linkset.GeometricCenter; } } // Refresh the linkset structure and parameters when the prim's physical parameters are changed. public override void UpdatePhysicalParameters() { base.UpdatePhysicalParameters(); // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. // For compound based linksets, this enables and disables interactions of the children. if (Linkset != null) // null can happen during initialization Linkset.Refresh(this); } // When the prim is made dynamic or static, the linkset needs to change. protected override void MakeDynamic(bool makeStatic) { base.MakeDynamic(makeStatic); if (Linkset != null) // null can happen during initialization { if (makeStatic) Linkset.MakeStatic(this); else Linkset.MakeDynamic(this); } } // Body is being taken apart. Remove physical dependencies and schedule a rebuild. protected override void RemoveDependencies() { Linkset.RemoveDependencies(this); base.RemoveDependencies(); } // Called after a simulation step for the changes in physical object properties. // Do any filtering/modification needed for linksets. public override void UpdateProperties(EntityProperties entprop) { if (Linkset.IsRoot(this) || Linkset.ShouldReportPropertyUpdates(this)) { // Properties are only updated for the roots of a linkset. // TODO: this will have to change when linksets are articulated. base.UpdateProperties(entprop); } /* else { // For debugging, report the movement of children DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, entprop.Acceleration, entprop.RotationalVelocity); } */ // The linkset might like to know about changing locations Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); } // Called after a simulation step to post a collision with this object. // This returns 'true' if the collision has been queued and the SendCollisions call must // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // Ask the linkset if it wants to handle the collision if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) { // The linkset didn't handle it so pass the collision through normal processing ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } return ret; } // A linkset reports any collision on any part of the linkset. public long SomeCollisionSimulationStep = 0; public override bool HasSomeCollision { get { return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; } set { if (value) SomeCollisionSimulationStep = PhysScene.SimulationStep; else SomeCollisionSimulationStep = 0; base.HasSomeCollision = value; } } // Convert the existing linkset of this prim into a new type. public bool ConvertLinkset(BSLinkset.LinksetImplementation newType) { bool ret = false; if (LinksetType != newType) { DetailLog("{0},BSPrimLinkable.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); // Set the implementation type first so the call to BSLinkset.Factory gets the new type. this.LinksetType = newType; BSLinkset oldLinkset = this.Linkset; BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this); this.Linkset = newLinkset; // Pick up any physical dependencies this linkset might have in the physics engine. oldLinkset.RemoveDependencies(this); // Create a list of the children (mainly because can't interate through a list that's changing) List<BSPrimLinkable> children = new List<BSPrimLinkable>(); oldLinkset.ForEachMember((child) => { if (!oldLinkset.IsRoot(child)) children.Add(child); return false; // 'false' says to continue to next member }); // Remove the children from the old linkset and add to the new (will be a new instance from the factory) foreach (BSPrimLinkable child in children) { oldLinkset.RemoveMeFromLinkset(child, true /*inTaintTime*/); } foreach (BSPrimLinkable child in children) { newLinkset.AddMeToLinkset(child); child.Linkset = newLinkset; } // Force the shape and linkset to get reconstructed newLinkset.Refresh(this); this.ForceBodyShapeRebuild(true /* inTaintTime */); } return ret; } #region Extension public override object Extension(string pFunct, params object[] pParams) { DetailLog("{0} BSPrimLinkable.Extension,op={1},nParam={2}", LocalID, pFunct, pParams.Length); object ret = null; switch (pFunct) { // physGetLinksetType(); // pParams = [ BSPhysObject root, null ] case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; DetailLog("{0},BSPrimLinkable.Extension.physGetLinksetType,type={1}", LocalID, ret); break; } // physSetLinksetType(type); // pParams = [ BSPhysObject root, null, integer type ] case ExtendedPhysics.PhysFunctSetLinksetType: { if (pParams.Length > 2) { BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[2]; if (Linkset.IsRoot(this)) { PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate() { // Cause the linkset type to change DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}", LocalID, Linkset.LinksetImpl, linksetType); ConvertLinkset(linksetType); }); } ret = (object)(int)linksetType; } break; } // physChangeLinkType(linknum, typeCode); // pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physGetLinkType(linknum); // pParams = [ BSPhysObject root, BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); // pParams = [ BSPhysObject root, BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] case ExtendedPhysics.PhysFunctChangeLinkParams: { ret = Linkset.Extension(pFunct, pParams); break; } default: ret = base.Extension(pFunct, pParams); break; } return ret; } #endregion // Extension } }
using Orleans.CodeGenerator.SyntaxGeneration; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using static Orleans.CodeGenerator.InvokableGenerator; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator { internal static class SerializerGenerator { private const string BaseTypeSerializerFieldName = "_baseTypeSerializer"; private const string ActivatorFieldName = "_activator"; private const string SerializeMethodName = "Serialize"; private const string DeserializeMethodName = "Deserialize"; private const string WriteFieldMethodName = "WriteField"; private const string ReadValueMethodName = "ReadValue"; private const string CodecFieldTypeFieldName = "_codecFieldType"; public static ClassDeclarationSyntax GenerateSerializer(LibraryTypes libraryTypes, ISerializableTypeDescription type) { var simpleClassName = GetSimpleClassName(type); var members = new List<ISerializableMember>(); foreach (var member in type.Members) { if (member is ISerializableMember serializable) { members.Add(serializable); } else if (member is IFieldDescription field) { members.Add(new SerializableMember(libraryTypes, type, field, members.Count)); } else if (member is MethodParameterFieldDescription methodParameter) { members.Add(new SerializableMethodMember(methodParameter)); } } var fieldDescriptions = GetFieldDescriptions(type, members, libraryTypes); var fieldDeclarations = GetFieldDeclarations(fieldDescriptions); var ctor = GenerateConstructor(libraryTypes, simpleClassName, fieldDescriptions); var accessibility = type.Accessibility switch { Accessibility.Public => SyntaxKind.PublicKeyword, _ => SyntaxKind.InternalKeyword, }; var classDeclaration = ClassDeclaration(simpleClassName) .AddBaseListTypes(SimpleBaseType(libraryTypes.FieldCodec_1.ToTypeSyntax(type.TypeSyntax))) .AddModifiers(Token(accessibility), Token(SyntaxKind.SealedKeyword)) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetGeneratedCodeAttributeSyntax()))) .AddMembers(fieldDeclarations) .AddMembers(ctor); if (type.IsEnumType) { var writeMethod = GenerateEnumWriteMethod(type, libraryTypes); var readMethod = GenerateEnumReadMethod(type, libraryTypes); classDeclaration = classDeclaration.AddMembers(writeMethod, readMethod); } else { var serializeMethod = GenerateSerializeMethod(type, fieldDescriptions, members, libraryTypes); var deserializeMethod = GenerateDeserializeMethod(type, fieldDescriptions, members, libraryTypes); var writeFieldMethod = GenerateCompoundTypeWriteFieldMethod(type, libraryTypes); var readValueMethod = GenerateCompoundTypeReadValueMethod(type, fieldDescriptions, libraryTypes); classDeclaration = classDeclaration.AddMembers(serializeMethod, deserializeMethod, writeFieldMethod, readValueMethod); var serializerInterface = type.IsValueType ? libraryTypes.ValueSerializer : libraryTypes.BaseCodec_1; classDeclaration = classDeclaration.AddBaseListTypes(SimpleBaseType(serializerInterface.ToTypeSyntax(type.TypeSyntax))); } if (type.IsGenericType) { classDeclaration = SyntaxFactoryUtility.AddGenericTypeParameters(classDeclaration, type.TypeParameters); } return classDeclaration; } public static string GetSimpleClassName(ISerializableTypeDescription serializableType) => GetSimpleClassName(serializableType.Name); public static string GetSimpleClassName(string name) => $"Codec_{name}"; public static string GetGeneratedNamespaceName(ITypeSymbol type) => type.GetNamespaceAndNesting() switch { { Length: > 0 } ns => $"{CodeGenerator.CodeGeneratorName}.{ns}", _ => CodeGenerator.CodeGeneratorName }; private static MemberDeclarationSyntax[] GetFieldDeclarations(List<GeneratedFieldDescription> fieldDescriptions) { return fieldDescriptions.Select(GetFieldDeclaration).ToArray(); static MemberDeclarationSyntax GetFieldDeclaration(GeneratedFieldDescription description) { switch (description) { case TypeFieldDescription type: return FieldDeclaration( VariableDeclaration( type.FieldType, SingletonSeparatedList(VariableDeclarator(type.FieldName) .WithInitializer(EqualsValueClause(TypeOfExpression(type.UnderlyingTypeSyntax)))))) .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)); case CodecFieldTypeFieldDescription type: return FieldDeclaration( VariableDeclaration( type.FieldType, SingletonSeparatedList(VariableDeclarator(type.FieldName) .WithInitializer(EqualsValueClause(TypeOfExpression(type.CodecFieldType)))))) .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)); case SetterFieldDescription setter: { var fieldSetterVariable = VariableDeclarator(setter.FieldName); return FieldDeclaration(VariableDeclaration(setter.FieldType).AddVariables(fieldSetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword)); } case GetterFieldDescription getter: { var fieldGetterVariable = VariableDeclarator(getter.FieldName); return FieldDeclaration(VariableDeclaration(getter.FieldType).AddVariables(fieldGetterVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword)); } default: return FieldDeclaration(VariableDeclaration(description.FieldType, SingletonSeparatedList(VariableDeclarator(description.FieldName)))) .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword)); } } } private static ConstructorDeclarationSyntax GenerateConstructor(LibraryTypes libraryTypes, string simpleClassName, List<GeneratedFieldDescription> fieldDescriptions) { var injected = fieldDescriptions.Where(f => f.IsInjected).ToList(); var parameters = new List<ParameterSyntax>(injected.Select(f => Parameter(f.FieldName.ToIdentifier()).WithType(f.FieldType))); const string CodecProviderParameterName = "codecProvider"; parameters.Add(Parameter(Identifier(CodecProviderParameterName)).WithType(libraryTypes.ICodecProvider.ToTypeSyntax())); var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); IEnumerable<StatementSyntax> GetStatements() { foreach (var field in fieldDescriptions) { switch (field) { case GetterFieldDescription getter: yield return getter.InitializationSyntax; break; case SetterFieldDescription setter: yield return setter.InitializationSyntax; break; case GeneratedFieldDescription _ when field.IsInjected: yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ThisExpression().Member(field.FieldName.ToIdentifierName()), Unwrapped(field.FieldName.ToIdentifierName()))); break; case CodecFieldDescription codec when !field.IsInjected: { yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ThisExpression().Member(field.FieldName.ToIdentifierName()), GetService(field.FieldType))); } break; } } } return ConstructorDeclaration(simpleClassName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters.ToArray()) .AddBodyStatements(GetStatements().ToArray()); static ExpressionSyntax Unwrapped(ExpressionSyntax expr) { return InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName("UnwrapService")), ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(expr) }))); } static ExpressionSyntax GetService(TypeSyntax type) { return InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), GenericName(Identifier("GetService"), TypeArgumentList(SingletonSeparatedList(type)))), ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(IdentifierName(CodecProviderParameterName)) }))); } } private static List<GeneratedFieldDescription> GetFieldDescriptions( ISerializableTypeDescription serializableTypeDescription, List<ISerializableMember> members, LibraryTypes libraryTypes) { var fields = new List<GeneratedFieldDescription>(); fields.AddRange(serializableTypeDescription.Members .Distinct(MemberDescriptionTypeComparer.Default) .Select(member => GetTypeDescription(member))); fields.Add(new CodecFieldTypeFieldDescription(libraryTypes.Type.ToTypeSyntax(), CodecFieldTypeFieldName, serializableTypeDescription.TypeSyntax)); if (serializableTypeDescription.HasComplexBaseType) { fields.Add(new BaseCodecFieldDescription(libraryTypes.BaseCodec_1.ToTypeSyntax(serializableTypeDescription.BaseTypeSyntax), BaseTypeSerializerFieldName)); } if (serializableTypeDescription.UseActivator) { fields.Add(new ActivatorFieldDescription(libraryTypes.IActivator_1.ToTypeSyntax(serializableTypeDescription.TypeSyntax), ActivatorFieldName)); } // Add a codec field for any field in the target which does not have a static codec. fields.AddRange(serializableTypeDescription.Members .Distinct(MemberDescriptionTypeComparer.Default) .Where(t => !libraryTypes.StaticCodecs.Any(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, t.Type))) .Select(member => GetCodecDescription(member))); foreach (var member in members) { if (member.GetGetterFieldDescription() is { } getterFieldDescription) { fields.Add(getterFieldDescription); } if (member.GetSetterFieldDescription() is { } setterFieldDescription) { fields.Add(setterFieldDescription); } } for (var hookIndex = 0; hookIndex < serializableTypeDescription.SerializationHooks.Count; ++hookIndex) { var hookType = serializableTypeDescription.SerializationHooks[hookIndex]; fields.Add(new SerializationHookFieldDescription(hookType.ToTypeSyntax(), $"_hook{hookIndex}")); } return fields; CodecFieldDescription GetCodecDescription(IMemberDescription member) { TypeSyntax codecType = null; if (member.Type.HasAttribute(libraryTypes.GenerateSerializerAttribute) && (!SymbolEqualityComparer.Default.Equals(member.Type.ContainingAssembly, libraryTypes.Compilation.Assembly) || member.Type.ContainingAssembly.HasAttribute(libraryTypes.TypeManifestProviderAttribute))) { // Use the concrete generated type and avoid expensive interface dispatch if (member.Type is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsGenericType) { // Construct the full generic type name var ns = ParseName(GetGeneratedNamespaceName(member.Type)); var name = GenericName(Identifier(GetSimpleClassName(member.Type.Name)), TypeArgumentList(SeparatedList(namedTypeSymbol.TypeArguments.Select(arg => member.GetTypeSyntax(arg))))); codecType = QualifiedName(ns, name); } else { var simpleName = $"{GetGeneratedNamespaceName(member.Type)}.{GetSimpleClassName(member.Type.Name)}"; codecType = ParseTypeName(simpleName); } } else if (libraryTypes.WellKnownCodecs.FirstOrDefault(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, member.Type)) is WellKnownCodecDescription codec) { // The codec is not a static codec and is also not a generic codec. codecType = codec.CodecType.ToTypeSyntax(); } else if (member.Type is INamedTypeSymbol named && libraryTypes.WellKnownCodecs.FirstOrDefault(c => member.Type is INamedTypeSymbol named && named.ConstructedFrom is ISymbol unboundFieldType && SymbolEqualityComparer.Default.Equals(c.UnderlyingType, unboundFieldType)) is WellKnownCodecDescription genericCodec) { // Construct the generic codec type using the field's type arguments. codecType = genericCodec.CodecType.Construct(named.TypeArguments.ToArray()).ToTypeSyntax(); } else { // Use the IFieldCodec<TField> interface codecType = libraryTypes.FieldCodec_1.ToTypeSyntax(member.TypeSyntax); } var fieldName = '_' + ToLowerCamelCase(member.TypeNameIdentifier) + "Codec"; return new CodecFieldDescription(codecType, fieldName, member.Type); } TypeFieldDescription GetTypeDescription(IMemberDescription member) { var fieldName = '_' + ToLowerCamelCase(member.TypeNameIdentifier) + "Type"; return new TypeFieldDescription(libraryTypes.Type.ToTypeSyntax(), fieldName, member.TypeSyntax, member.Type); } static string ToLowerCamelCase(string input) => char.IsLower(input, 0) ? input : char.ToLowerInvariant(input[0]) + input.Substring(1); } private static MemberDeclarationSyntax GenerateSerializeMethod( ISerializableTypeDescription type, List<GeneratedFieldDescription> serializerFields, List<ISerializableMember> members, LibraryTypes libraryTypes) { var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword)); var writerParam = "writer".ToIdentifierName(); var instanceParam = "instance".ToIdentifierName(); var body = new List<StatementSyntax>(); if (type.HasComplexBaseType) { body.Add( ExpressionStatement( InvocationExpression( ThisExpression().Member(BaseTypeSerializerFieldName.ToIdentifierName()).Member(SerializeMethodName), ArgumentList(SeparatedList(new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(instanceParam) }))))); body.Add(ExpressionStatement(InvocationExpression(writerParam.Member("WriteEndBase"), ArgumentList()))); } body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnSerializing")); // Order members according to their FieldId, since fields must be serialized in order and FieldIds are serialized as deltas. var previousFieldIdVar = "previousFieldId".ToIdentifierName(); if (type.OmitDefaultMemberValues && members.Count > 0) { // C#: uint previousFieldId = 0; body.Add(LocalDeclarationStatement( VariableDeclaration( PredefinedType(Token(SyntaxKind.UIntKeyword)), SingletonSeparatedList(VariableDeclarator(previousFieldIdVar.Identifier) .WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))))))); } uint previousFieldId = 0; foreach (var member in members.OrderBy(m => m.Member.FieldId)) { var description = member.Member; ExpressionSyntax fieldIdDeltaExpr; if (type.OmitDefaultMemberValues) { // C#: <fieldId> - previousFieldId fieldIdDeltaExpr = BinaryExpression(SyntaxKind.SubtractExpression, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(description.FieldId)), previousFieldIdVar); } else { var fieldIdDelta = description.FieldId - previousFieldId; previousFieldId = description.FieldId; fieldIdDeltaExpr = LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldIdDelta)); } // Codecs can either be static classes or injected into the constructor. // Either way, the member signatures are the same. var memberType = description.Type; var staticCodec = libraryTypes.StaticCodecs.FirstOrDefault(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, memberType)); ExpressionSyntax codecExpression; if (staticCodec != null && libraryTypes.Compilation.IsSymbolAccessibleWithin(staticCodec.CodecType, libraryTypes.Compilation.Assembly)) { codecExpression = staticCodec.CodecType.ToNameSyntax(); } else { var instanceCodec = serializerFields.OfType<CodecFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType)); codecExpression = ThisExpression().Member(instanceCodec.FieldName); } var expectedType = serializerFields.OfType<TypeFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType)); var writeFieldExpr = ExpressionStatement( InvocationExpression( codecExpression.Member("WriteField"), ArgumentList( SeparatedList( new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldIdDeltaExpr), Argument(expectedType.FieldName.ToIdentifierName()), Argument(member.GetGetter(instanceParam)) })))); if (!type.OmitDefaultMemberValues) { body.Add(writeFieldExpr); } else { ExpressionSyntax condition = member.IsValueType switch { true => BinaryExpression(SyntaxKind.NotEqualsExpression, member.GetGetter(instanceParam), LiteralExpression(SyntaxKind.DefaultLiteralExpression)), false => IsPatternExpression(member.GetGetter(instanceParam), TypePattern(libraryTypes.Object.ToTypeSyntax())) }; body.Add(IfStatement( condition, Block( writeFieldExpr, ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, previousFieldIdVar, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(description.FieldId))))))); } } body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnSerialized")); var parameters = new[] { Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter("instance".ToIdentifier()).WithType(type.TypeSyntax) }; if (type.IsValueType) { parameters[1] = parameters[1].WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))); } return MethodDeclaration(returnType, SerializeMethodName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddTypeParameterListParameters(TypeParameter("TBufferWriter")) .AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax()))) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); } private static MemberDeclarationSyntax GenerateDeserializeMethod( ISerializableTypeDescription type, List<GeneratedFieldDescription> serializerFields, List<ISerializableMember> members, LibraryTypes libraryTypes) { var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword)); var readerParam = "reader".ToIdentifierName(); var instanceParam = "instance".ToIdentifierName(); var idVar = "id".ToIdentifierName(); var headerVar = "header".ToIdentifierName(); var readHeaderLocalFunc = "ReadHeader".ToIdentifierName(); var readHeaderEndLocalFunc = "ReadHeaderExpectingEndBaseOrEndObject".ToIdentifierName(); var body = new List<StatementSyntax> { // C#: int id = 0; LocalDeclarationStatement( VariableDeclaration( PredefinedType(Token(SyntaxKind.IntKeyword)), SingletonSeparatedList(VariableDeclarator(idVar.Identifier) .WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))))))), // C#: Field header = default; LocalDeclarationStatement( VariableDeclaration( libraryTypes.Field.ToTypeSyntax(), SingletonSeparatedList(VariableDeclarator(headerVar.Identifier) .WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.DefaultLiteralExpression)))))) }; if (type.HasComplexBaseType) { // C#: this.baseTypeSerializer.Deserialize(ref reader, instance); body.Add( ExpressionStatement( InvocationExpression( ThisExpression().Member(BaseTypeSerializerFieldName.ToIdentifierName()).Member(DeserializeMethodName), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(instanceParam) }))))); } body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnDeserializing")); body.Add(WhileStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression), Block(GetDeserializerLoopBody()))); body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnDeserialized")); var genericParam = ParseTypeName("TReaderInput"); var parameters = new[] { Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(genericParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter(instanceParam.Identifier).WithType(type.TypeSyntax) }; if (type.IsValueType) { parameters[1] = parameters[1].WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))); } return MethodDeclaration(returnType, DeserializeMethodName) .AddTypeParameterListParameters(TypeParameter("TReaderInput")) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); // Create the loop body. List<StatementSyntax> GetDeserializerLoopBody() { var loopBody = new List<StatementSyntax>(); var codecs = serializerFields.OfType<ICodecDescription>() .Concat(libraryTypes.StaticCodecs) .ToList(); var orderedMembers = members.OrderBy(m => m.Member.FieldId).ToList(); var lastMember = orderedMembers.LastOrDefault(); // C#: id = OrleansGeneratedCodeHelper.ReadHeader(ref reader, ref header, id); { var readHeaderMethodName = orderedMembers.Count == 0 ? "ReadHeaderExpectingEndBaseOrEndObject" : "ReadHeader"; var readFieldHeader = ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(idVar.Identifier), InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName(readHeaderMethodName)), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(headerVar).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(idVar) }))))); loopBody.Add(readFieldHeader); } foreach (var member in orderedMembers) { var description = member.Member; // C#: instance.<member> = <codec>.ReadValue(ref reader, header); // Codecs can either be static classes or injected into the constructor. // Either way, the member signatures are the same. var codec = codecs.First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, description.Type)); var memberType = description.Type; var staticCodec = libraryTypes.StaticCodecs.FirstOrDefault(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, memberType)); ExpressionSyntax codecExpression; if (staticCodec != null) { codecExpression = staticCodec.CodecType.ToNameSyntax(); } else { var instanceCodec = serializerFields.OfType<CodecFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType)); codecExpression = ThisExpression().Member(instanceCodec.FieldName); } ExpressionSyntax readValueExpression = InvocationExpression( codecExpression.Member("ReadValue"), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(headerVar) }))); if (!codec.UnderlyingType.Equals(member.TypeSyntax)) { // If the member type type differs from the codec type (eg because the member is an array), cast the result. readValueExpression = CastExpression(description.TypeSyntax, readValueExpression); } var memberAssignment = ExpressionStatement(member.GetSetter(instanceParam, readValueExpression)); var readHeaderMethodName = ReferenceEquals(member, lastMember) ? "ReadHeaderExpectingEndBaseOrEndObject" : "ReadHeader"; var readFieldHeader = ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(idVar.Identifier), InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName(readHeaderMethodName)), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(headerVar).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(idVar) }))))); var ifBody = Block(List(new StatementSyntax[] { memberAssignment, readFieldHeader })); // C#: if (id == <fieldId>) { ... } var ifStatement = IfStatement(BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(idVar.Identifier), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)description.FieldId))), ifBody); loopBody.Add(ifStatement); } // C#: if (id == -1) { break; } loopBody.Add(IfStatement(BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(idVar.Identifier), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(-1))), Block(List(new StatementSyntax[] { BreakStatement() })))); // Consume any unknown fields // C#: reader.ConsumeUnknownField(header); var consumeUnknown = ExpressionStatement(InvocationExpression(readerParam.Member("ConsumeUnknownField"), ArgumentList(SeparatedList(new[] { Argument(headerVar) })))); loopBody.Add(consumeUnknown); return loopBody; } } private static IEnumerable<StatementSyntax> AddSerializationCallbacks(ISerializableTypeDescription type, IdentifierNameSyntax instanceParam, string callbackMethodName) { for (var hookIndex = 0; hookIndex < type.SerializationHooks.Count; ++hookIndex) { var hookType = type.SerializationHooks[hookIndex]; var member = hookType.GetAllMembers<IMethodSymbol>(callbackMethodName, Accessibility.Public).FirstOrDefault(); if (member is null || member.Parameters.Length != 1) { continue; } var argument = Argument(instanceParam); if (member.Parameters[0].RefKind == RefKind.Ref) { argument = argument.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } yield return ExpressionStatement(InvocationExpression( ThisExpression().Member($"_hook{hookIndex}").Member(callbackMethodName), ArgumentList(SeparatedList(new[] { argument })))); } } private static MemberDeclarationSyntax GenerateCompoundTypeWriteFieldMethod( ISerializableTypeDescription type, LibraryTypes libraryTypes) { var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword)); var writerParam = "writer".ToIdentifierName(); var fieldIdDeltaParam = "fieldIdDelta".ToIdentifierName(); var expectedTypeParam = "expectedType".ToIdentifierName(); var valueParam = "value".ToIdentifierName(); var valueTypeField = "valueType".ToIdentifierName(); var innerBody = new List<StatementSyntax>(); if (type.IsValueType) { // C#: ReferenceCodec.MarkValueField(reader.Session); innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(writerParam.Member("Session"))))))); } else { if (type.TrackReferences) { // C#: if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } innerBody.Add( IfStatement( InvocationExpression( IdentifierName("ReferenceCodec").Member("TryWriteReferenceField"), ArgumentList(SeparatedList(new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldIdDeltaParam), Argument(expectedTypeParam), Argument(valueParam) }))), Block(ReturnStatement())) ); } else { // C#: if (value is null) { ReferenceCodec.WriteNullReference(ref writer, fieldIdDelta, expectedType); return; } innerBody.Add( IfStatement( IsPatternExpression(valueParam, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))), Block( ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("WriteNullReference"), ArgumentList(SeparatedList(new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldIdDeltaParam), Argument(expectedTypeParam) })))), ReturnStatement())) ); // C#: ReferenceCodec.MarkValueField(reader.Session); innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(writerParam.Member("Session"))))))); } } // Generate the most appropriate expression to get the field type. ExpressionSyntax valueTypeInitializer = type.IsValueType switch { true => IdentifierName(CodecFieldTypeFieldName), false => ConditionalAccessExpression(valueParam, InvocationExpression(MemberBindingExpression(IdentifierName("GetType")))) }; ExpressionSyntax valueTypeExpression = type.IsSealedType switch { true => IdentifierName(CodecFieldTypeFieldName), false => valueTypeField }; // C#: writer.WriteStartObject(fieldIdDelta, expectedType, fieldType); innerBody.Add( ExpressionStatement(InvocationExpression(writerParam.Member("WriteStartObject"), ArgumentList(SeparatedList(new[]{ Argument(fieldIdDeltaParam), Argument(expectedTypeParam), Argument(valueTypeExpression) }))) )); // C#: this.Serialize(ref writer, [ref] value); var valueParamArgument = type.IsValueType switch { true => Argument(valueParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), false => Argument(valueParam) }; innerBody.Add( ExpressionStatement( InvocationExpression( ThisExpression().Member(SerializeMethodName), ArgumentList( SeparatedList( new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), valueParamArgument }))))); // C#: writer.WriteEndObject(); innerBody.Add(ExpressionStatement(InvocationExpression(writerParam.Member("WriteEndObject")))); List<StatementSyntax> body; if (type.IsSealedType) { body = innerBody; } else { // For types which are not sealed/value types, add some extra logic to support sub-types: body = new List<StatementSyntax> { // C#: var fieldType = value?.GetType(); LocalDeclarationStatement( VariableDeclaration( libraryTypes.Type.ToTypeSyntax(), SingletonSeparatedList(VariableDeclarator(valueTypeField.Identifier) .WithInitializer(EqualsValueClause(valueTypeInitializer))))), // C#: if (fieldType is null || fieldType == typeof(TField)) { <inner body> } // C#: else { OrleansGeneratedCodeHelper.SerializeUnexpectedType(ref writer, fieldIdDelta, expectedType, value); } IfStatement( BinaryExpression(SyntaxKind.LogicalOrExpression, IsPatternExpression(valueTypeField, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))), BinaryExpression(SyntaxKind.EqualsExpression, valueTypeField, IdentifierName(CodecFieldTypeFieldName))), Block(innerBody), ElseClause(Block(new StatementSyntax[] { ExpressionStatement( InvocationExpression( IdentifierName("OrleansGeneratedCodeHelper").Member("SerializeUnexpectedType"), ArgumentList( SeparatedList(new [] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldIdDeltaParam), Argument(expectedTypeParam), Argument(valueParam) })))) }))) }; } var parameters = new[] { Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter("fieldIdDelta".ToIdentifier()).WithType(libraryTypes.UInt32.ToTypeSyntax()), Parameter("expectedType".ToIdentifier()).WithType(libraryTypes.Type.ToTypeSyntax()), Parameter("value".ToIdentifier()).WithType(type.TypeSyntax) }; return MethodDeclaration(returnType, WriteFieldMethodName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddTypeParameterListParameters(TypeParameter("TBufferWriter")) .AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax()))) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); } private static MemberDeclarationSyntax GenerateCompoundTypeReadValueMethod( ISerializableTypeDescription type, List<GeneratedFieldDescription> serializerFields, LibraryTypes libraryTypes) { var readerParam = "reader".ToIdentifierName(); var fieldParam = "field".ToIdentifierName(); var resultVar = "result".ToIdentifierName(); var readerInputTypeParam = ParseTypeName("TReaderInput"); var body = new List<StatementSyntax>(); var innerBody = new List<StatementSyntax>(); if (!type.IsValueType) { // C#: if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<TField, TReaderInput>(ref reader, field); } body.Add( IfStatement( BinaryExpression(SyntaxKind.EqualsExpression, fieldParam.Member("WireType"), libraryTypes.WireType.ToTypeSyntax().Member("Reference")), Block(ReturnStatement(InvocationExpression( IdentifierName("ReferenceCodec").Member("ReadReference", new[] { type.TypeSyntax, readerInputTypeParam }), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldParam), })))))) ); } ExpressionSyntax createValueExpression = type.UseActivator switch { true => InvocationExpression(serializerFields.OfType<ActivatorFieldDescription>().Single().FieldName.ToIdentifierName().Member("Create")), false => type.GetObjectCreationExpression(libraryTypes) }; // C#: TField result = _activator.Create(); // or C#: TField result = new TField(); innerBody.Add(LocalDeclarationStatement( VariableDeclaration( type.TypeSyntax, SingletonSeparatedList(VariableDeclarator(resultVar.Identifier) .WithInitializer(EqualsValueClause(createValueExpression)))))); if (type.TrackReferences) { // C#: ReferenceCodec.RecordObject(reader.Session, result); innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("RecordObject"), ArgumentList(SeparatedList(new[] { Argument(readerParam.Member("Session")), Argument(resultVar) }))))); } else { // C#: ReferenceCodec.MarkValueField(reader.Session); innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(readerParam.Member("Session"))))))); } // C#: this.Deserializer(ref reader, [ref] result); var resultArgument = type.IsValueType switch { true => Argument(resultVar).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), false => Argument(resultVar) }; innerBody.Add( ExpressionStatement( InvocationExpression( ThisExpression().Member(DeserializeMethodName), ArgumentList( SeparatedList( new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), resultArgument }))))); innerBody.Add(ReturnStatement(resultVar)); if (type.IsSealedType) { body.AddRange(innerBody); } else { // C#: var fieldType = field.FieldType; var valueTypeField = "valueType".ToIdentifierName(); body.Add( LocalDeclarationStatement( VariableDeclaration( libraryTypes.Type.ToTypeSyntax(), SingletonSeparatedList(VariableDeclarator(valueTypeField.Identifier) .WithInitializer(EqualsValueClause(fieldParam.Member("FieldType"))))))); body.Add( IfStatement( BinaryExpression(SyntaxKind.LogicalOrExpression, IsPatternExpression(valueTypeField, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))), BinaryExpression(SyntaxKind.EqualsExpression, valueTypeField, IdentifierName(CodecFieldTypeFieldName))), Block(innerBody))); body.Add(ReturnStatement( InvocationExpression( IdentifierName("OrleansGeneratedCodeHelper").Member("DeserializeUnexpectedType", new[] { readerInputTypeParam, type.TypeSyntax }), ArgumentList( SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldParam) }))))); } var parameters = new[] { Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(readerInputTypeParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter(fieldParam.Identifier).WithType(libraryTypes.Field.ToTypeSyntax()) }; return MethodDeclaration(type.TypeSyntax, ReadValueMethodName) .AddTypeParameterListParameters(TypeParameter("TReaderInput")) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); } private static MemberDeclarationSyntax GenerateEnumWriteMethod( ISerializableTypeDescription type, LibraryTypes libraryTypes) { var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword)); var writerParam = "writer".ToIdentifierName(); var fieldIdDeltaParam = "fieldIdDelta".ToIdentifierName(); var expectedTypeParam = "expectedType".ToIdentifierName(); var valueParam = "value".ToIdentifierName(); var body = new List<StatementSyntax>(); // Codecs can either be static classes or injected into the constructor. // Either way, the member signatures are the same. var staticCodec = libraryTypes.StaticCodecs.FirstOrDefault(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, type.BaseType)); var codecExpression = staticCodec.CodecType.ToNameSyntax(); body.Add( ExpressionStatement( InvocationExpression( codecExpression.Member("WriteField"), ArgumentList( SeparatedList( new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldIdDeltaParam), Argument(expectedTypeParam), Argument(CastExpression(type.BaseTypeSyntax, valueParam)), Argument(TypeOfExpression(type.TypeSyntax)) }))))); var parameters = new[] { Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter("fieldIdDelta".ToIdentifier()).WithType(libraryTypes.UInt32.ToTypeSyntax()), Parameter("expectedType".ToIdentifier()).WithType(libraryTypes.Type.ToTypeSyntax()), Parameter("value".ToIdentifier()).WithType(type.TypeSyntax) }; return MethodDeclaration(returnType, WriteFieldMethodName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddTypeParameterListParameters(TypeParameter("TBufferWriter")) .AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax()))) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); } private static MemberDeclarationSyntax GenerateEnumReadMethod( ISerializableTypeDescription type, LibraryTypes libraryTypes) { var readerParam = "reader".ToIdentifierName(); var fieldParam = "field".ToIdentifierName(); var staticCodec = libraryTypes.StaticCodecs.FirstOrDefault(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, type.BaseType)); ExpressionSyntax codecExpression = staticCodec.CodecType.ToNameSyntax(); ExpressionSyntax readValueExpression = InvocationExpression( codecExpression.Member("ReadValue"), ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldParam) }))); readValueExpression = CastExpression(type.TypeSyntax, readValueExpression); var body = new List<StatementSyntax> { ReturnStatement(readValueExpression) }; var genericParam = ParseTypeName("TReaderInput"); var parameters = new[] { Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(genericParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))), Parameter(fieldParam.Identifier).WithType(libraryTypes.Field.ToTypeSyntax()) }; return MethodDeclaration(type.TypeSyntax, ReadValueMethodName) .AddTypeParameterListParameters(TypeParameter("TReaderInput")) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(parameters) .AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax()))) .AddBodyStatements(body.ToArray()); } internal abstract class GeneratedFieldDescription { protected GeneratedFieldDescription(TypeSyntax fieldType, string fieldName) { FieldType = fieldType; FieldName = fieldName; } public TypeSyntax FieldType { get; } public string FieldName { get; } public abstract bool IsInjected { get; } } internal class BaseCodecFieldDescription : GeneratedFieldDescription { public BaseCodecFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName) { } public override bool IsInjected => true; } internal class ActivatorFieldDescription : GeneratedFieldDescription { public ActivatorFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName) { } public override bool IsInjected => true; } internal class CodecFieldDescription : GeneratedFieldDescription, ICodecDescription { public CodecFieldDescription(TypeSyntax fieldType, string fieldName, ITypeSymbol underlyingType) : base(fieldType, fieldName) { UnderlyingType = underlyingType; } public ITypeSymbol UnderlyingType { get; } public override bool IsInjected => false; } internal class TypeFieldDescription : GeneratedFieldDescription { public TypeFieldDescription(TypeSyntax fieldType, string fieldName, TypeSyntax underlyingTypeSyntax, ITypeSymbol underlyingType) : base(fieldType, fieldName) { UnderlyingType = underlyingType; UnderlyingTypeSyntax = underlyingTypeSyntax; } public TypeSyntax UnderlyingTypeSyntax { get; } public ITypeSymbol UnderlyingType { get; } public override bool IsInjected => false; } internal class CodecFieldTypeFieldDescription : GeneratedFieldDescription { public CodecFieldTypeFieldDescription(TypeSyntax fieldType, string fieldName, TypeSyntax codecFieldType) : base(fieldType, fieldName) { CodecFieldType = codecFieldType; } public TypeSyntax CodecFieldType { get; } public override bool IsInjected => false; } internal class SetterFieldDescription : GeneratedFieldDescription { public SetterFieldDescription(TypeSyntax fieldType, string fieldName, StatementSyntax initializationSyntax) : base(fieldType, fieldName) { InitializationSyntax = initializationSyntax; } public override bool IsInjected => false; public StatementSyntax InitializationSyntax { get; } } internal class GetterFieldDescription : GeneratedFieldDescription { public GetterFieldDescription(TypeSyntax fieldType, string fieldName, StatementSyntax initializationSyntax) : base(fieldType, fieldName) { InitializationSyntax = initializationSyntax; } public override bool IsInjected => false; public StatementSyntax InitializationSyntax { get; } } internal class SerializationHookFieldDescription : GeneratedFieldDescription { public SerializationHookFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName) { } public override bool IsInjected => true; } internal interface ISerializableMember { bool IsShallowCopyable { get; } bool IsValueType { get; } IMemberDescription Member { get; } /// <summary> /// Gets syntax representing the type of this field. /// </summary> TypeSyntax TypeSyntax { get; } /// <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> /// <returns>Syntax for retrieving the value of this field.</returns> ExpressionSyntax GetGetter(ExpressionSyntax instance); /// <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> ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value); GetterFieldDescription GetGetterFieldDescription(); SetterFieldDescription GetSetterFieldDescription(); } /// <summary> /// Represents a serializable member (field/property) of a type. /// </summary> internal class SerializableMethodMember : ISerializableMember { private readonly MethodParameterFieldDescription _member; public SerializableMethodMember(MethodParameterFieldDescription member) { _member = member; } public IMemberDescription Member => _member; private LibraryTypes LibraryTypes => _member.Method.ContainingInterface.CodeGenerator.LibraryTypes; public bool IsShallowCopyable => LibraryTypes.IsShallowCopyable(_member.Parameter.Type) || _member.Parameter.HasAnyAttribute(LibraryTypes.ImmutableAttributes); /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax TypeSyntax => _member.TypeSyntax; public bool IsValueType => _member.Type.IsValueType; /// <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> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(_member.FieldName); /// <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) => AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(_member.FieldName), value); public GetterFieldDescription GetGetterFieldDescription() => null; public SetterFieldDescription GetSetterFieldDescription() => null; } /// <summary> /// Represents a serializable member (field/property) of a type. /// </summary> internal class SerializableMember : ISerializableMember { private readonly SemanticModel _model; private readonly LibraryTypes _libraryTypes; private IPropertySymbol _property; private readonly IFieldDescription _fieldDescription; /// <summary> /// The ordinal assigned to this field. /// </summary> private readonly int _ordinal; public SerializableMember(LibraryTypes libraryTypes, ISerializableTypeDescription type, IFieldDescription member, int ordinal) { _libraryTypes = libraryTypes; _model = type.SemanticModel; _ordinal = ordinal; _fieldDescription = member; } public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(_fieldDescription.Type) || (Property is { } prop && prop.HasAnyAttribute(_libraryTypes.ImmutableAttributes)) || _fieldDescription.Field.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; public IMemberDescription Member => _fieldDescription; /// <summary> /// Gets the underlying <see cref="Field"/> instance. /// </summary> private IFieldSymbol Field => _fieldDescription.Field; public ITypeSymbol Type => _fieldDescription.Type; public INamedTypeSymbol ContainingType => _fieldDescription.Field.ContainingType; public string FieldName => _fieldDescription.Field.Name; /// <summary> /// Gets the name of the getter field. /// </summary> private string GetterFieldName => "getField" + _ordinal; /// <summary> /// Gets the name of the setter field. /// </summary> private string SetterFieldName => "setField" + _ordinal; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> private bool IsGettableProperty => Property?.GetMethod != null && _model.IsAccessible(0, Property.GetMethod) && !IsObsolete; /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> private bool IsSettableProperty => Property?.SetMethod is { } setMethod && _model.IsAccessible(0, setMethod) && !setMethod.IsInitOnly && !IsObsolete; /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax TypeSyntax => Field.Type.TypeKind == TypeKind.Dynamic ? PredefinedType(Token(SyntaxKind.ObjectKeyword)) : _fieldDescription.GetTypeSyntax(Field.Type); /// <summary> /// Gets the <see cref="Property"/> 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 IPropertySymbol Property { get { if (_property != null) { return _property; } return _property = PropertyUtility.GetMatchingProperty(Field); } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete => Field.HasAttribute(_libraryTypes.ObsoleteAttribute) || Property != null && Property.HasAttribute(_libraryTypes.ObsoleteAttribute); /// <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> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (IsGettableProperty) { result = instance.Member(Property.Name); } else if (Field.DeclaredAccessibility == Accessibility.Public && _model.IsAccessible(0, Field)) { result = instance.Member(Field.Name); } else { // Retrieve the field using the generated getter. result = InvocationExpression(IdentifierName(GetterFieldName)) .AddArgumentListArguments(Argument(instance)); } return result; } /// <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 (IsSettableProperty) { return AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(Property.Name), value); } if (!Field.IsReadOnly && IsDeclaredAccessible(Field) && _model.IsAccessible(0, Field)) { return AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(Field.Name), value); } var instanceArg = Argument(instance); if (Field.ContainingType != null && Field.ContainingType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); } return InvocationExpression(IdentifierName(SetterFieldName)) .AddArgumentListArguments(instanceArg, Argument(value)); } private static bool IsDeclaredAccessible(ISymbol symbol) => symbol.DeclaredAccessibility switch { Accessibility.Public => true, _ => false, }; public GetterFieldDescription GetGetterFieldDescription() { var getterType = _libraryTypes.Func_2.ToTypeSyntax(_fieldDescription.GetTypeSyntax(ContainingType), TypeSyntax); // Generate syntax to initialize the field in the constructor var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); var fieldInfo = GetGetFieldInfoExpression(ContainingType, FieldName); var accessorInvoke = CastExpression( getterType, InvocationExpression(fieldAccessorUtility.Member("GetGetter")).AddArgumentListArguments(Argument(fieldInfo))); var initializationSyntax = ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(GetterFieldName), accessorInvoke)); return new GetterFieldDescription(getterType, GetterFieldName, initializationSyntax); } public SetterFieldDescription GetSetterFieldDescription() { TypeSyntax fieldType; if (ContainingType != null && ContainingType.IsValueType) { fieldType = _libraryTypes.ValueTypeSetter_2.ToTypeSyntax(_fieldDescription.GetTypeSyntax(ContainingType), TypeSyntax); } else { fieldType = _libraryTypes.Action_2.ToTypeSyntax(_fieldDescription.GetTypeSyntax(ContainingType), TypeSyntax); } // Generate syntax to initialize the field in the constructor var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); var fieldInfo = GetGetFieldInfoExpression(ContainingType, FieldName); var isContainedByValueType = ContainingType != null && ContainingType.IsValueType; var accessorMethod = isContainedByValueType ? "GetValueSetter" : "GetReferenceSetter"; var accessorInvoke = CastExpression( fieldType, InvocationExpression(fieldAccessorUtility.Member(accessorMethod)) .AddArgumentListArguments(Argument(fieldInfo))); var initializationSyntax = ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(SetterFieldName), accessorInvoke)); return new SetterFieldDescription(fieldType, SetterFieldName, initializationSyntax); } public static InvocationExpressionSyntax GetGetFieldInfoExpression(INamedTypeSymbol containingType, string fieldName) { var bindingFlags = SymbolSyntaxExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); return InvocationExpression(TypeOfExpression(containingType.ToTypeSyntax()).Member("GetField")) .AddArgumentListArguments( Argument(fieldName.GetLiteralExpression()), Argument(bindingFlags)); } /// <summary> /// A comparer for <see cref="SerializableMember"/> which compares by name. /// </summary> public class Comparer : IComparer<SerializableMember> { /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get; } = new(); public int Compare(SerializableMember x, SerializableMember y) => string.Compare(x?.Field.Name, y?.Field.Name, StringComparison.Ordinal); } } } }
using System; using log4net; using Umbraco.Core.Logging; using System.IO; using System.Linq; using Umbraco.Core.IO; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Publishing; using umbraco.interfaces; namespace Umbraco.Core.Services { /// <summary> /// The Umbraco ServiceContext, which provides access to the following services: /// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>, /// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>. /// </summary> public class ServiceContext { private Lazy<IMigrationEntryService> _migrationEntryService; private Lazy<IPublicAccessService> _publicAccessService; private Lazy<ITaskService> _taskService; private Lazy<IDomainService> _domainService; private Lazy<IAuditService> _auditService; private Lazy<ILocalizedTextService> _localizedTextService; private Lazy<ITagService> _tagService; private Lazy<IContentService> _contentService; private Lazy<IUserService> _userService; private Lazy<IMemberService> _memberService; private Lazy<IMediaService> _mediaService; private Lazy<IContentTypeService> _contentTypeService; private Lazy<IDataTypeService> _dataTypeService; private Lazy<IFileService> _fileService; private Lazy<ILocalizationService> _localizationService; private Lazy<IPackagingService> _packagingService; private Lazy<IServerRegistrationService> _serverRegistrationService; private Lazy<IEntityService> _entityService; private Lazy<IRelationService> _relationService; private Lazy<IApplicationTreeService> _treeService; private Lazy<ISectionService> _sectionService; private Lazy<IMacroService> _macroService; private Lazy<IMemberTypeService> _memberTypeService; private Lazy<IMemberGroupService> _memberGroupService; private Lazy<INotificationService> _notificationService; private Lazy<IExternalLoginService> _externalLoginService; /// <summary> /// public ctor - will generally just be used for unit testing all items are optional and if not specified, the defaults will be used /// </summary> /// <param name="contentService"></param> /// <param name="mediaService"></param> /// <param name="contentTypeService"></param> /// <param name="dataTypeService"></param> /// <param name="fileService"></param> /// <param name="localizationService"></param> /// <param name="packagingService"></param> /// <param name="entityService"></param> /// <param name="relationService"></param> /// <param name="memberGroupService"></param> /// <param name="memberTypeService"></param> /// <param name="memberService"></param> /// <param name="userService"></param> /// <param name="sectionService"></param> /// <param name="treeService"></param> /// <param name="tagService"></param> /// <param name="notificationService"></param> /// <param name="localizedTextService"></param> /// <param name="auditService"></param> /// <param name="domainService"></param> /// <param name="taskService"></param> /// <param name="macroService"></param> /// <param name="publicAccessService"></param> /// <param name="externalLoginService"></param> /// <param name="migrationEntryService"></param> public ServiceContext( IContentService contentService = null, IMediaService mediaService = null, IContentTypeService contentTypeService = null, IDataTypeService dataTypeService = null, IFileService fileService = null, ILocalizationService localizationService = null, IPackagingService packagingService = null, IEntityService entityService = null, IRelationService relationService = null, IMemberGroupService memberGroupService = null, IMemberTypeService memberTypeService = null, IMemberService memberService = null, IUserService userService = null, ISectionService sectionService = null, IApplicationTreeService treeService = null, ITagService tagService = null, INotificationService notificationService = null, ILocalizedTextService localizedTextService = null, IAuditService auditService = null, IDomainService domainService = null, ITaskService taskService = null, IMacroService macroService = null, IPublicAccessService publicAccessService = null, IExternalLoginService externalLoginService = null, IMigrationEntryService migrationEntryService = null) { if (migrationEntryService != null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => migrationEntryService); if (externalLoginService != null) _externalLoginService = new Lazy<IExternalLoginService>(() => externalLoginService); if (auditService != null) _auditService = new Lazy<IAuditService>(() => auditService); if (localizedTextService != null) _localizedTextService = new Lazy<ILocalizedTextService>(() => localizedTextService); if (tagService != null) _tagService = new Lazy<ITagService>(() => tagService); if (contentService != null) _contentService = new Lazy<IContentService>(() => contentService); if (mediaService != null) _mediaService = new Lazy<IMediaService>(() => mediaService); if (contentTypeService != null) _contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService); if (dataTypeService != null) _dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService); if (fileService != null) _fileService = new Lazy<IFileService>(() => fileService); if (localizationService != null) _localizationService = new Lazy<ILocalizationService>(() => localizationService); if (packagingService != null) _packagingService = new Lazy<IPackagingService>(() => packagingService); if (entityService != null) _entityService = new Lazy<IEntityService>(() => entityService); if (relationService != null) _relationService = new Lazy<IRelationService>(() => relationService); if (sectionService != null) _sectionService = new Lazy<ISectionService>(() => sectionService); if (memberGroupService != null) _memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService); if (memberTypeService != null) _memberTypeService = new Lazy<IMemberTypeService>(() => memberTypeService); if (treeService != null) _treeService = new Lazy<IApplicationTreeService>(() => treeService); if (memberService != null) _memberService = new Lazy<IMemberService>(() => memberService); if (userService != null) _userService = new Lazy<IUserService>(() => userService); if (notificationService != null) _notificationService = new Lazy<INotificationService>(() => notificationService); if (domainService != null) _domainService = new Lazy<IDomainService>(() => domainService); if (taskService != null) _taskService = new Lazy<ITaskService>(() => taskService); if (macroService != null) _macroService = new Lazy<IMacroService>(() => macroService); if (publicAccessService != null) _publicAccessService = new Lazy<IPublicAccessService>(() => publicAccessService); } internal ServiceContext( RepositoryFactory repositoryFactory, IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache, ILogger logger) { BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache, repositoryFactory, logger); } /// <summary> /// Builds the various services /// </summary> private void BuildServiceCache( IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache, RepositoryFactory repositoryFactory, ILogger logger) { var provider = dbUnitOfWorkProvider; var fileProvider = fileUnitOfWorkProvider; if (_migrationEntryService == null) _migrationEntryService = new Lazy<IMigrationEntryService>(() => new MigrationEntryService(provider, repositoryFactory, logger)); if (_externalLoginService == null) _externalLoginService = new Lazy<IExternalLoginService>(() => new ExternalLoginService(provider, repositoryFactory, logger)); if (_publicAccessService == null) _publicAccessService = new Lazy<IPublicAccessService>(() => new PublicAccessService(provider, repositoryFactory, logger)); if (_taskService == null) _taskService = new Lazy<ITaskService>(() => new TaskService(provider, repositoryFactory, logger)); if (_domainService == null) _domainService = new Lazy<IDomainService>(() => new DomainService(provider, repositoryFactory, logger)); if (_auditService == null) _auditService = new Lazy<IAuditService>(() => new AuditService(provider, repositoryFactory, logger)); if (_localizedTextService == null) { _localizedTextService = new Lazy<ILocalizedTextService>(() => new LocalizedTextService( new Lazy<LocalizedTextServiceFileSources>(() => { var mainLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/")); var appPlugins = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)); var configLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config + "/lang/")); var pluginLangFolders = appPlugins.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : appPlugins.GetDirectories() .SelectMany(x => x.GetDirectories("Lang")) .SelectMany(x => x.GetFiles("*.xml", SearchOption.TopDirectoryOnly)) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 5) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, false)); //user defined langs that overwrite the default, these should not be used by plugin creators var userLangFolders = configLangFolder.Exists == false ? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>() : configLangFolder .GetFiles("*.user.xml", SearchOption.TopDirectoryOnly) .Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 10) .Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true)); return new LocalizedTextServiceFileSources( logger, cache.RuntimeCache, mainLangFolder, pluginLangFolders.Concat(userLangFolders)); }), logger)); } if (_notificationService == null) _notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger)); if (_serverRegistrationService == null) _serverRegistrationService = new Lazy<IServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory, logger)); if (_userService == null) _userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory, logger)); if (_memberService == null) _memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory, logger, _memberGroupService.Value, _dataTypeService.Value)); if (_contentService == null) _contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory, logger, publishingStrategy, _dataTypeService.Value, _userService.Value)); if (_mediaService == null) _mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory, logger, _dataTypeService.Value, _userService.Value)); if (_contentTypeService == null) _contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory, logger, _contentService.Value, _mediaService.Value)); if (_dataTypeService == null) _dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger)); if (_fileService == null) _fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory)); if (_localizationService == null) _localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger)); if (_packagingService == null) _packagingService = new Lazy<IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _userService.Value, repositoryFactory, provider)); if (_entityService == null) _entityService = new Lazy<IEntityService>(() => new EntityService( provider, repositoryFactory, logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value, cache.RuntimeCache)); if (_relationService == null) _relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory, logger, _entityService.Value)); if (_treeService == null) _treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(logger, cache)); if (_sectionService == null) _sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, provider, cache)); if (_macroService == null) _macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory, logger)); if (_memberTypeService == null) _memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory, logger, _memberService.Value)); if (_tagService == null) _tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory, logger)); if (_memberGroupService == null) _memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory, logger)); } /// <summary> /// Gets the <see cref="IMigrationEntryService"/> /// </summary> public IMigrationEntryService MigrationEntryService { get { return _migrationEntryService.Value; } } /// <summary> /// Gets the <see cref="IPublicAccessService"/> /// </summary> public IPublicAccessService PublicAccessService { get { return _publicAccessService.Value; } } /// <summary> /// Gets the <see cref="ITaskService"/> /// </summary> public ITaskService TaskService { get { return _taskService.Value; } } /// <summary> /// Gets the <see cref="IDomainService"/> /// </summary> public IDomainService DomainService { get { return _domainService.Value; } } /// <summary> /// Gets the <see cref="IAuditService"/> /// </summary> public IAuditService AuditService { get { return _auditService.Value; } } /// <summary> /// Gets the <see cref="ILocalizedTextService"/> /// </summary> public ILocalizedTextService TextService { get { return _localizedTextService.Value; } } /// <summary> /// Gets the <see cref="INotificationService"/> /// </summary> public INotificationService NotificationService { get { return _notificationService.Value; } } /// <summary> /// Gets the <see cref="ServerRegistrationService"/> /// </summary> public IServerRegistrationService ServerRegistrationService { get { return _serverRegistrationService.Value; } } /// <summary> /// Gets the <see cref="ITagService"/> /// </summary> public ITagService TagService { get { return _tagService.Value; } } /// <summary> /// Gets the <see cref="IMacroService"/> /// </summary> public IMacroService MacroService { get { return _macroService.Value; } } /// <summary> /// Gets the <see cref="IEntityService"/> /// </summary> public IEntityService EntityService { get { return _entityService.Value; } } /// <summary> /// Gets the <see cref="IRelationService"/> /// </summary> public IRelationService RelationService { get { return _relationService.Value; } } /// <summary> /// Gets the <see cref="IContentService"/> /// </summary> public IContentService ContentService { get { return _contentService.Value; } } /// <summary> /// Gets the <see cref="IContentTypeService"/> /// </summary> public IContentTypeService ContentTypeService { get { return _contentTypeService.Value; } } /// <summary> /// Gets the <see cref="IDataTypeService"/> /// </summary> public IDataTypeService DataTypeService { get { return _dataTypeService.Value; } } /// <summary> /// Gets the <see cref="IFileService"/> /// </summary> public IFileService FileService { get { return _fileService.Value; } } /// <summary> /// Gets the <see cref="ILocalizationService"/> /// </summary> public ILocalizationService LocalizationService { get { return _localizationService.Value; } } /// <summary> /// Gets the <see cref="IMediaService"/> /// </summary> public IMediaService MediaService { get { return _mediaService.Value; } } /// <summary> /// Gets the <see cref="PackagingService"/> /// </summary> public IPackagingService PackagingService { get { return _packagingService.Value; } } /// <summary> /// Gets the <see cref="UserService"/> /// </summary> public IUserService UserService { get { return _userService.Value; } } /// <summary> /// Gets the <see cref="MemberService"/> /// </summary> public IMemberService MemberService { get { return _memberService.Value; } } /// <summary> /// Gets the <see cref="SectionService"/> /// </summary> public ISectionService SectionService { get { return _sectionService.Value; } } /// <summary> /// Gets the <see cref="ApplicationTreeService"/> /// </summary> public IApplicationTreeService ApplicationTreeService { get { return _treeService.Value; } } /// <summary> /// Gets the MemberTypeService /// </summary> public IMemberTypeService MemberTypeService { get { return _memberTypeService.Value; } } /// <summary> /// Gets the MemberGroupService /// </summary> public IMemberGroupService MemberGroupService { get { return _memberGroupService.Value; } } public IExternalLoginService ExternalLoginService { get { return _externalLoginService.Value; } } } }
using UnityEngine; using System.Collections; /* * An algorithm to extrude an arbitrary mesh along a number of sections. The mesh extrusion has 2 steps: 1. Extracting an edge representation from an arbitrary mesh - A general edge extraction algorithm is employed. (Same algorithm as traditionally used for stencil shadows) Once all unique edges are found, all edges that connect to only one triangle are extracted. Thus we end up with the outline of the mesh. 2. extruding the mesh from the edge representation. We simply generate a segments joining the edges */ public class MeshExtrusion { public class Edge { // The indiex to each vertex public int[] vertexIndex = new int[2]; // The index into the face. // (faceindex[0] == faceindex[1] means the edge connects to only one triangle) public int[] faceIndex = new int[2]; } public static void ExtrudeMesh (Mesh srcMesh, Mesh extrudedMesh, Matrix4x4[] extrusion, bool invertFaces, bool buildCaps) { Edge[] edges = BuildManifoldEdges(srcMesh); ExtrudeMesh(srcMesh, extrudedMesh, extrusion, edges, invertFaces, buildCaps); } public static void ExtrudeMesh (Mesh srcMesh, Mesh extrudedMesh, Matrix4x4[] extrusion, Edge[] edges, bool invertFaces, bool buildCaps) { int extrudedVertexCount = edges.Length * 2 * extrusion.Length; int triIndicesPerStep = edges.Length * 6; int extrudedTriIndexCount = triIndicesPerStep * (extrusion.Length -1); Vector3[] inputVertices = srcMesh.vertices; Vector2[] inputUV = srcMesh.uv; int[] inputTriangles = srcMesh.triangles; Vector3[] vertices = new Vector3[extrudedVertexCount + srcMesh.vertexCount * 2]; Vector2[] uvs = new Vector2[vertices.Length]; int[] triangles = new int[extrudedTriIndexCount + inputTriangles.Length * 2]; // Build extruded vertices int v = 0; for (int i=0;i<extrusion.Length;i++) { Matrix4x4 matrix = extrusion[i]; float vcoord = (float)i / (extrusion.Length -1); foreach (Edge e in edges) { vertices[v+0] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[0]]); vertices[v+1] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[1]]); uvs[v+0] = new Vector2 (inputUV[e.vertexIndex[0]].x, vcoord); uvs[v+1] = new Vector2 (inputUV[e.vertexIndex[1]].x, vcoord); v += 2; } } // Build cap vertices // * The bottom mesh we scale along it's negative extrusion direction. This way extruding a half sphere results in a capsule. if (buildCaps) { for (int c = 0; c < 2; c++) { Matrix4x4 matrix = extrusion[c == 0 ? 0 : extrusion.Length - 1]; int firstCapVertex = c == 0 ? extrudedVertexCount : extrudedVertexCount + inputVertices.Length; for (int i = 0; i < inputVertices.Length; i++) { vertices[firstCapVertex + i] = matrix.MultiplyPoint(inputVertices[i]); uvs[firstCapVertex + i] = inputUV[i]; } } } // Build extruded triangles for (int i=0;i<extrusion.Length-1;i++) { int baseVertexIndex = (edges.Length * 2) * i; int nextVertexIndex = (edges.Length * 2) * (i+1); for (int e=0;e<edges.Length;e++) { int triIndex = i * triIndicesPerStep + e * 6; triangles[triIndex + 0] = baseVertexIndex + e * 2; triangles[triIndex + 1] = nextVertexIndex + e * 2; triangles[triIndex + 2] = baseVertexIndex + e * 2 + 1; triangles[triIndex + 3] = nextVertexIndex + e * 2; triangles[triIndex + 4] = nextVertexIndex + e * 2 + 1; triangles[triIndex + 5] = baseVertexIndex + e * 2 + 1; } } // build cap triangles int triCount = inputTriangles.Length / 3; // Top { int firstCapVertex = extrudedVertexCount; int firstCapTriIndex = extrudedTriIndexCount; for (int i=0;i<triCount;i++) { triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 1] + firstCapVertex; triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex; triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 0] + firstCapVertex; } } // Bottom { int firstCapVertex = extrudedVertexCount + inputVertices.Length; int firstCapTriIndex = extrudedTriIndexCount + inputTriangles.Length; for (int i=0;i<triCount;i++) { triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 0] + firstCapVertex; triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex; triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 1] + firstCapVertex; } } if (invertFaces) { for (int i=0;i<triangles.Length/3;i++) { int temp = triangles[i*3 + 0]; triangles[i*3 + 0] = triangles[i*3 + 1]; triangles[i*3 + 1] = temp; } } extrudedMesh.Clear(); extrudedMesh.name= "extruded"; extrudedMesh.vertices = vertices; extrudedMesh.uv = uvs; extrudedMesh.triangles = triangles; extrudedMesh.RecalculateNormals(); } /// Builds an array of edges that connect to only one triangle. /// In other words, the outline of the mesh public static Edge[] BuildManifoldEdges (Mesh mesh) { // Build a edge list for all unique edges in the mesh Edge[] edges = BuildEdges(mesh.vertexCount, mesh.triangles); // We only want edges that connect to a single triangle ArrayList culledEdges = new ArrayList(); foreach (Edge edge in edges) { if (edge.faceIndex[0] == edge.faceIndex[1]) { culledEdges.Add(edge); } } return culledEdges.ToArray(typeof(Edge)) as Edge[]; } /// Builds an array of unique edges /// This requires that your mesh has all vertices welded. However on import, Unity has to split /// vertices at uv seams and normal seams. Thus for a mesh with seams in your mesh you /// will get two edges adjoining one triangle. /// Often this is not a problem but you can fix it by welding vertices /// and passing in the triangle array of the welded vertices. public static Edge[] BuildEdges(int vertexCount, int[] triangleArray) { int maxEdgeCount = triangleArray.Length; int[] firstEdge = new int[vertexCount + maxEdgeCount]; int nextEdge = vertexCount; int triangleCount = triangleArray.Length / 3; for (int a = 0; a < vertexCount; a++) firstEdge[a] = -1; // First pass over all triangles. This finds all the edges satisfying the // condition that the first vertex index is less than the second vertex index // when the direction from the first vertex to the second vertex represents // a counterclockwise winding around the triangle to which the edge belongs. // For each edge found, the edge index is stored in a linked list of edges // belonging to the lower-numbered vertex index i. This allows us to quickly // find an edge in the second pass whose higher-numbered vertex index is i. Edge[] edgeArray = new Edge[maxEdgeCount]; int edgeCount = 0; for (int a = 0; a < triangleCount; a++) { int i1 = triangleArray[a*3 + 2]; for (int b = 0; b < 3; b++) { int i2 = triangleArray[a*3 + b]; if (i1 < i2) { Edge newEdge = new Edge(); newEdge.vertexIndex[0] = i1; newEdge.vertexIndex[1] = i2; newEdge.faceIndex[0] = a; newEdge.faceIndex[1] = a; edgeArray[edgeCount] = newEdge; int edgeIndex = firstEdge[i1]; if (edgeIndex == -1) { firstEdge[i1] = edgeCount; } else { while (true) { int index = firstEdge[nextEdge + edgeIndex]; if (index == -1) { firstEdge[nextEdge + edgeIndex] = edgeCount; break; } edgeIndex = index; } } firstEdge[nextEdge + edgeCount] = -1; edgeCount++; } i1 = i2; } } // Second pass over all triangles. This finds all the edges satisfying the // condition that the first vertex index is greater than the second vertex index // when the direction from the first vertex to the second vertex represents // a counterclockwise winding around the triangle to which the edge belongs. // For each of these edges, the same edge should have already been found in // the first pass for a different triangle. Of course we might have edges with only one triangle // in that case we just add the edge here // So we search the list of edges // for the higher-numbered vertex index for the matching edge and fill in the // second triangle index. The maximum number of comparisons in this search for // any vertex is the number of edges having that vertex as an endpoint. for (int a = 0; a < triangleCount; a++) { int i1 = triangleArray[a*3+2]; for (int b = 0; b < 3; b++) { int i2 = triangleArray[a*3+b]; if (i1 > i2) { bool foundEdge = false; for (int edgeIndex = firstEdge[i2]; edgeIndex != -1;edgeIndex = firstEdge[nextEdge + edgeIndex]) { Edge edge = edgeArray[edgeIndex]; if ((edge.vertexIndex[1] == i1) && (edge.faceIndex[0] == edge.faceIndex[1])) { edgeArray[edgeIndex].faceIndex[1] = a; foundEdge = true; break; } } if (!foundEdge) { Edge newEdge = new Edge(); newEdge.vertexIndex[0] = i1; newEdge.vertexIndex[1] = i2; newEdge.faceIndex[0] = a; newEdge.faceIndex[1] = a; edgeArray[edgeCount] = newEdge; edgeCount++; } } i1 = i2; } } Edge[] compactedEdges = new Edge[edgeCount]; for (int e=0;e<edgeCount;e++) compactedEdges[e] = edgeArray[e]; return compactedEdges; } }
// 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.Numerics; internal partial class VectorTest { private const int Pass = 100; private const int Fail = -1; // Matrix for test purposes only - no per-dim bounds checking, etc. public struct Matrix<T> where T : struct, IComparable<T>, IEquatable<T> { // data is a flattened matrix. private T[] _data; public int xCount, yCount; private int _xTileCount; private int _yTileCount; private int _flattenedCount; private static readonly int s_tileSize = Vector<T>.Count; public Matrix(int theXCount, int theYCount) { // Round up the dimensions so that we don't have to deal with remnants. int vectorCount = Vector<T>.Count; _xTileCount = (theXCount + vectorCount - 1) / vectorCount; _yTileCount = (theYCount + vectorCount - 1) / vectorCount; xCount = _xTileCount * vectorCount; yCount = _yTileCount * vectorCount; _flattenedCount = xCount * yCount; _data = new T[_flattenedCount]; } public T this[int indexX, int indexY] { get { return _data[(indexX * yCount) + indexY]; } set { _data[(indexX * yCount) + indexY] = value; } } public static void Transpose(Matrix<T> m, int xStart, int yStart, Vector<T>[] result) { int Count = result.Length; T[][] tempResult = new T[Count][]; if (Count != Vector<T>.Count) { throw new ArgumentException(); } for (int i = 0; i < Count; i++) { tempResult[i] = new T[Count]; } for (int i = 0; i < Count; i++) { for (int j = 0; j < Count; j++) { tempResult[j][i] = m[xStart + i, yStart + j]; } } for (int i = 0; i < Count; i++) { result[i] = new Vector<T>(tempResult[i]); } } public static Matrix<T> operator *(Matrix<T> left, Matrix<T> right) { int newXCount = left.xCount; int newYCount = right.yCount; int innerCount = left.yCount; Matrix<T> result = new Matrix<T>(newXCount, newYCount); Vector<T>[] temp = new Vector<T>[s_tileSize]; T[] temp2 = new T[s_tileSize]; T[] temp3 = new T[s_tileSize]; if (left.yCount != right.xCount) { throw new ArgumentException(); } for (int i = 0; i < result.xCount; i += s_tileSize) { for (int j = 0; j < result.yCount; j += s_tileSize) { for (int k = 0; k < right.xCount; k += s_tileSize) { // Compute the result for the tile: // Result[i,j] = Left[i,k] * Right[k,j] // Would REALLY like to have a Transpose intrinsic // that could use shuffles. Transpose(right, k, j, temp); Vector<T> dot = Vector<T>.Zero; for (int m = 0; m < s_tileSize; m++) { Vector<T> leftTileRow = new Vector<T>(left._data, (i + m) * left.yCount + k); for (int n = 0; n < s_tileSize; n++) { temp2[n] = Vector.Dot<T>(leftTileRow, temp[n]); } Vector<T> resultVector = new Vector<T>(result._data, (i + m) * result.yCount + j); resultVector += new Vector<T>(temp2); // Store the resultTile resultVector.CopyTo(result._data, ((i + m) * result.yCount + j)); } } } } return result; } public void Print() { Console.WriteLine("["); for (int i = 0; i < xCount; i++) { Console.Write(" ["); for (int j = 0; j < yCount; j++) { Console.Write(this[i, j]); if (j < (yCount - 1)) Console.Write(","); } Console.WriteLine("]"); } Console.WriteLine("]"); } } public static Matrix<T> GetRandomMatrix<T>(int xDim, int yDim, Random random) where T : struct, IComparable<T>, IEquatable<T> { Matrix<T> result = new Matrix<T>(xDim, yDim); for (int i = 0; i < xDim; i++) { for (int j = 0; j < yDim; j++) { int data = random.Next(100); result[i, j] = GetValueFromInt<T>(data); } } return result; } private static T compareMMPoint<T>(Matrix<T> left, Matrix<T> right, int i, int j) where T : struct, IComparable<T>, IEquatable<T> { T sum = Vector<T>.Zero[0]; for (int k = 0; k < right.xCount; k++) { T l = left[i, k]; T r = right[k, j]; sum = Add<T>(sum, Multiply<T>(l, r)); } return sum; } public static int VectorMatrix<T>(Matrix<T> left, Matrix<T> right) where T : struct, IComparable<T>, IEquatable<T> { int returnVal = Pass; Matrix<T> Result = left * right; for (int i = 0; i < left.xCount; i++) { for (int j = 0; j < right.yCount; j++) { T compareResult = compareMMPoint<T>(left, right, i, j); T testResult = Result[i, j]; if (!(CheckValue<T>(testResult, compareResult))) { Console.WriteLine(" Mismatch at [" + i + "," + j + "]: expected " + compareResult + " got " + testResult); returnVal = Fail; } } } if (returnVal == Fail) { Console.WriteLine("FAILED COMPARE"); Console.WriteLine("Left:"); left.Print(); Console.WriteLine("Right:"); right.Print(); Console.WriteLine("Result:"); Result.Print(); } return returnVal; } public static int Main() { int returnVal = Pass; Random random = new Random(100); // Float Matrix<float> AFloat = GetRandomMatrix<float>(3, 4, random); Matrix<float> BFloat = GetRandomMatrix<float>(4, 2, random); if (VectorMatrix<float>(AFloat, BFloat) != Pass) returnVal = Fail; AFloat = GetRandomMatrix<float>(33, 20, random); BFloat = GetRandomMatrix<float>(20, 17, random); if (VectorMatrix<float>(AFloat, BFloat) != Pass) returnVal = Fail; // Double Matrix<double> ADouble = GetRandomMatrix<double>(3, 4, random); Matrix<double> BDouble = GetRandomMatrix<double>(4, 2, random); if (VectorMatrix<double>(ADouble, BDouble) != Pass) returnVal = Fail; ADouble = GetRandomMatrix<double>(33, 20, random); BDouble = GetRandomMatrix<double>(20, 17, random); if (VectorMatrix<double>(ADouble, BDouble) != Pass) returnVal = Fail; return returnVal; } }
/* * 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.Text; using Microsoft.CSharp; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using System.CodeDom.Compiler; namespace OpenSim.Tools.LSL.Compiler { class Program { // Commented out because generated warning since m_positionMap could never be anything other than null // private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap; private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider(); static void Main(string[] args) { string source = null; if (args.Length == 0) { Console.WriteLine("No input file specified"); Environment.Exit(1); } if (!File.Exists(args[0])) { Console.WriteLine("Input file does not exist"); Environment.Exit(1); } try { ICodeConverter cvt = (ICodeConverter) new CSCodeGenerator(); source = cvt.Convert(File.ReadAllText(args[0])); } catch(Exception e) { Console.WriteLine("Conversion failed:\n"+e.Message); Environment.Exit(1); } source = CreateCSCompilerScript(source); try { Console.WriteLine(CompileFromDotNetText(source,"a.out")); } catch(Exception e) { Console.WriteLine("Conversion failed: "+e.Message); Environment.Exit(1); } Environment.Exit(0); } private static string CreateCSCompilerScript(string compileScript) { compileScript = String.Empty + "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" + String.Empty + "namespace SecondLife { " + String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + @"public Script() { } " + compileScript + "} }\r\n"; return compileScript; } private static string CompileFromDotNetText(string Script, string asset) { string OutFile = asset; string disp ="OK"; try { File.Delete(OutFile); } catch (Exception e) // NOTLEGIT - Should be just FileIOException { throw new Exception("Unable to delete old existing "+ "script-file before writing new. Compile aborted: " + e.ToString()); } // Do actual compile CompilerParameters parameters = new CompilerParameters(); parameters.IncludeDebugInformation = true; string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll")); parameters.GenerateExecutable = false; parameters.OutputAssembly = OutFile; parameters.IncludeDebugInformation = true; parameters.WarningLevel = 1; parameters.TreatWarningsAsErrors = false; CompilerResults results = CScodeProvider.CompileAssemblyFromSource(parameters, Script); if (results.Errors.Count > 0) { string errtext = String.Empty; foreach (CompilerError CompErr in results.Errors) { string severity = CompErr.IsWarning ? "Warning" : "Error"; KeyValuePair<int, int> lslPos; lslPos = FindErrorPosition(CompErr.Line, CompErr.Column); string text = CompErr.ErrorText; text = ReplaceTypes(CompErr.ErrorText); // The Second Life viewer's script editor begins // countingn lines and columns at 0, so we subtract 1. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n", lslPos.Key - 1, lslPos.Value - 1, CompErr.ErrorNumber, text, severity); } disp = "Completed with errors"; if (!File.Exists(OutFile)) { throw new Exception(errtext); } } if (!File.Exists(OutFile)) { string errtext = String.Empty; errtext += "No compile error. But not able to locate compiled file."; throw new Exception(errtext); } // Because windows likes to perform exclusive locks, we simply // write out a textual representation of the file here // // Read the binary file into a buffer // FileInfo fi = new FileInfo(OutFile); if (fi == null) { string errtext = String.Empty; errtext += "No compile error. But not able to stat file."; throw new Exception(errtext); } Byte[] data = new Byte[fi.Length]; try { FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read); fs.Read(data, 0, data.Length); fs.Close(); } catch (Exception) { string errtext = String.Empty; errtext += "No compile error. But not able to open file."; throw new Exception(errtext); } // Convert to base64 // string filetext = System.Convert.ToBase64String(data); Byte[] buf = Encoding.ASCII.GetBytes(filetext); FileStream sfs = File.Create(OutFile + ".text"); sfs.Write(buf, 0, buf.Length); sfs.Close(); string posmap = String.Empty; // if (m_positionMap != null) // { // foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in m_positionMap) // { // KeyValuePair<int, int> k = kvp.Key; // KeyValuePair<int, int> v = kvp.Value; // posmap += String.Format("{0},{1},{2},{3}\n", // k.Key, k.Value, v.Key, v.Value); // } // } buf = Encoding.ASCII.GetBytes(posmap); FileStream mfs = File.Create(OutFile + ".map"); mfs.Write(buf, 0, buf.Length); mfs.Close(); return disp; } private static string ReplaceTypes(string message) { message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString", "string"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger", "integer"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat", "float"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list", "list"); return message; } private static KeyValuePair<int, int> FindErrorPosition(int line, int col) { //return FindErrorPosition(line, col, m_positionMap); return FindErrorPosition(line, col, null); } private class kvpSorter : IComparer<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>> { public int Compare(KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> a, KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> b) { int kc = a.Key.Key.CompareTo(b.Key.Key); return (kc != 0) ? kc : a.Key.Value.CompareTo(b.Key.Value); } } public static KeyValuePair<int, int> FindErrorPosition(int line, int col, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap) { if (positionMap == null || positionMap.Count == 0) return new KeyValuePair<int, int>(line, col); KeyValuePair<int, int> ret = new KeyValuePair<int, int>(); if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col), out ret)) return ret; var sorted = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>(positionMap); sorted.Sort(new kvpSorter()); int l = 1; int c = 1; int pl = 1; foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> posmap in sorted) { //m_log.DebugFormat("[Compiler]: Scanning line map {0},{1} --> {2},{3}", posmap.Key.Key, posmap.Key.Value, posmap.Value.Key, posmap.Value.Value); int nl = posmap.Value.Key + line - posmap.Key.Key; // New, translated LSL line and column. int nc = posmap.Value.Value + col - posmap.Key.Value; // Keep going until we find the first point passed line,col. if (posmap.Key.Key > line) { //m_log.DebugFormat("[Compiler]: Line is larger than requested {0},{1}, returning {2},{3}", line, col, l, c); if (pl < line) { //m_log.DebugFormat("[Compiler]: Previous line ({0}) is less than requested line ({1}), setting column to 1.", pl, line); c = 1; } break; } if (posmap.Key.Key == line && posmap.Key.Value > col) { // Never move l,c backwards. if (nl > l || (nl == l && nc > c)) { //m_log.DebugFormat("[Compiler]: Using offset relative to this: {0} + {1} - {2}, {3} + {4} - {5} = {6}, {7}", // posmap.Value.Key, line, posmap.Key.Key, posmap.Value.Value, col, posmap.Key.Value, nl, nc); l = nl; c = nc; } //m_log.DebugFormat("[Compiler]: Column is larger than requested {0},{1}, returning {2},{3}", line, col, l, c); break; } pl = posmap.Key.Key; l = posmap.Value.Key; c = posmap.Value.Value; } return new KeyValuePair<int, int>(l, c); } } }
using System; using System.Text; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Appleseed.Framework; using Appleseed.Framework.Settings; namespace Appleseed.Framework.Web.UI.WebControls { /// <summary> /// ModuleButton. Custom control for Module buttons ... derives from HtmlAnchor. /// Allows text, image or both. Can be url hyperlink or postback button. /// Use ServerClick event to pick up on postback. /// </summary> public class ModuleButton : HtmlAnchor { /// <summary> /// /// </summary> protected HtmlAnchor moduleButton; #region Constructor /// <summary> /// Constructor /// </summary> public ModuleButton() { } #endregion #region Events /// <summary> /// Init event handler. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param> override protected void OnInit(EventArgs e) { this.EnableViewState = false; base.OnInit(e); } /// <summary> /// Load event handler /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (this.TranslationKey.Length != 0) this.InnerText = General.GetString(this.TranslationKey, this.EnglishName, this); if (this.InnerText == string.Empty) this.InnerText = this.EnglishName; this.HRef = HttpContext.Current.Server.HtmlEncode(this.HRef); switch (this.RenderAs) { case RenderOptions.TextOnly: this.Style.Add("display", "block"); this.Attributes.Add("class", this.CssClass); this.InnerHtml = string.Concat("<div class=\"btn-txt-only\">", this.InnerText, "</div>"); // Jes1111 - 27/Nov/2004 - changed popup window handling if (this.PopUp) { this.Attributes.Add("onclick", GetPopupCommand()); this.Attributes.Add("target", this.Target); this.Attributes.Add("class", string.Concat(this.CssClass, " btn-is-popup btn-txt-only")); } else this.Attributes.Add("class", string.Concat(this.CssClass, " btn-txt-only")); break; case RenderOptions.ImageAndTextCSS: this.Style.Add("display", "block"); this.Style.Add("background-image", string.Concat("url(", this.Image.ImageUrl, ")")); this.Style.Add("background-repeat", "no-repeat"); this.Style.Add("height", this.Image.Height.ToString()); this.Style.Add("width", this.Image.Width.ToString()); this.InnerHtml = string.Concat("<div class=\"btn-img-txt\">", this.InnerText, "</div>"); // Jes1111 - 27/Nov/2004 - changed popup window handling if (this.PopUp) { this.Attributes.Add("onclick", GetPopupCommand()); this.Attributes.Add("target", this.Target); this.Attributes.Add("class", string.Concat(this.CssClass, " btn-is-popup btn-img-txt")); } else this.Attributes.Add("class", string.Concat(this.CssClass, " btn-img-txt")); break; case RenderOptions.ImageOnlyCSS: this.Title = string.Concat(this.InnerText, "..."); this.Style.Add("display", "block"); this.Style.Add("background-image", string.Concat("url(", this.Image.ImageUrl, ")")); this.Style.Add("background-repeat", "no-repeat"); this.Style.Add("height", this.Image.Height.ToString()); this.Style.Add("width", this.Image.Width.ToString()); this.InnerHtml = string.Concat("<div class=\"btn-img-only-css\">", this.InnerText, "</div>"); // Jes1111 - 27/Nov/2004 - changed popup window handling if (this.PopUp) { this.Attributes.Add("onclick", GetPopupCommand()); this.Attributes.Add("target", this.Target); this.Attributes.Add("class", string.Concat(this.CssClass, " btn-is-popup btn-img-only-css")); } else this.Attributes.Add("class", string.Concat(this.CssClass, " btn-img-only-css")); break; case RenderOptions.ImageOnly: default: //this.Title = string.Concat(this.InnerText,"..."); //Manu FIX: Image caption was not showed in Image only style //this.Image.AlternateText = string.Concat(this.InnerText,"..."); // fixed again by Jes1111 - 18/01/2004 - tooltips were not showing in Gecko browsers this.Attributes.Add("title", string.Concat(this.InnerText, "...")); this.Style.Add("display", "block"); // Jes1111 - 27/Nov/2004 - changed popup window handling if (this.PopUp) { this.Attributes.Add("onclick", GetPopupCommand()); this.Attributes.Add("target", this.Target); this.Attributes.Add("class", string.Concat(this.CssClass, " btn-is-popup btn-img-only")); } else this.Attributes.Add("class", string.Concat(this.CssClass, " btn-img-only")); this.Image.BorderStyle = BorderStyle.None; // Hongwei Shen(hongwei.shen@gmail.com) 11/9/2005 // use the AlternateText to display the tool tip for the button this.image.AlternateText = this.InnerText; // end of modification this.InnerText = string.Empty; this.Controls.Add(this.Image); break; } this.EnsureChildControls(); base.OnLoad(e); } // Jes1111 - 27/Nov/2004 - changed popup window handling /// <summary> /// Builds Javascript popup command /// </summary> /// <returns>popup command as a string</returns> protected string GetPopupCommand() { // make sure the popup script is registered if (!((Page)this.Page).IsClientScriptRegistered("rb-popup")) ((Page)this.Page).RegisterClientScript("rb-popup", Path.ApplicationRoot + "/aspnet_client/popupHelper/popup.js"); // build the popup command StringBuilder sb = new StringBuilder(); sb.Append("link_popup(this"); if (this.PopUpOptions.Length != 0) { sb.Append(", '"); sb.Append(this.PopUpOptions); sb.Append("'"); } sb.Append(");return false;"); return sb.ToString(); } // Jes1111 - 27/Nov/2004 - changed popup window handling // protected override void OnPreRender(EventArgs e) // { // //popup removed until fixed // if ( this.PopUp ) // { // if ( !((Appleseed.Framework.Web.UI.Page)this.Page).IsClientScriptRegistered("rb-popup") ) // ((Appleseed.Framework.Web.UI.Page)this.Page).RegisterClientScript("rb-popup",Appleseed.Framework.Settings.Path.ApplicationRoot + "/aspnet_client/popupHelper/popup.js"); // // if ( !((Appleseed.Framework.Web.UI.Page)this.Page).IsClientPopUpEventListenerRegistered(this.Target) ) // { // StringBuilder sb = new StringBuilder(); // sb.Append("mlisten('click', getElementsByClass('"); // sb.Append(this.Target); // sb.Append("','a')"); // if ( this.PopUpOptions.Length != 0 ) // { // sb.Append(", event_popup_features('"); // sb.Append(this.PopUpOptions); // sb.Append("')"); // } // sb.Append(");"); // ((Appleseed.Framework.Web.UI.Page)this.Page).RegisterClientPopUpEventListener(this.Target, sb.ToString()); // } // } // //popup removed until fixed // base.OnPreRender(e); // } #endregion #region Properties private string targetID = string.Empty; /// <summary> /// Gets the target ID. /// </summary> /// <value>The target ID.</value> private string TargetID { get { if (HttpContext.Current != null) targetID = string.Concat(this.Target, ((Page)this.Page).PageID); return targetID; } } private bool popUp = false; /// <summary> /// Gets or sets a value indicating whether [pop up]. /// </summary> /// <value><c>true</c> if [pop up]; otherwise, <c>false</c>.</value> public bool PopUp { get { return popUp; } set { popUp = value; } } private string popUpOptions = string.Empty; /// <summary> /// Gets or sets the pop up options. /// </summary> /// <value>The pop up options.</value> public string PopUpOptions { get { return popUpOptions; } set { popUpOptions = value; } } private string name = string.Empty; /// <summary> /// Hides inherited Name /// </summary> /// <value></value> /// <returns>The bookmark name.</returns> new private string Name { get { return name; } set { name = value; } } private string cssClass = "rb_mod_btn"; /// <summary> /// Sets CSS Class on control /// </summary> /// <value>The CSS class.</value> public string CssClass { get { return cssClass; } set { cssClass = value; } } private ButtonGroup group = ButtonGroup.User; /// <summary> /// Holds Button group enum: User, Admin or Custom /// </summary> /// <value>The group.</value> public ButtonGroup Group { get { return group; } set { group = value; } } private Image image = new Image(); /// <summary> /// Button image /// </summary> /// <value>The image.</value> public Image Image { get { return image; } set { image = value; } } private string translation = string.Empty; /// <summary> /// Esperantus translation /// </summary> /// <value>The name of the english.</value> public string EnglishName { get { return translation; } set { translation = value; } } private string translationKey = string.Empty; /// <summary> /// Esperantus translation key /// </summary> /// <value>The translation key.</value> public string TranslationKey { get { return translationKey; } set { translationKey = value; } } private RenderOptions renderAs = RenderOptions.ImageOnly; /// <summary> /// Active RenderAs option /// </summary> /// <value>The render as.</value> public RenderOptions RenderAs { get { return renderAs; } set { renderAs = value; } } #endregion #region Enums /// <summary> /// Rendering options /// </summary> public enum RenderOptions : int { /// <summary> /// /// </summary> ImageOnly = 0, /// <summary> /// /// </summary> ImageOnlyCSS = 1, /// <summary> /// /// </summary> TextOnly = 2, /// <summary> /// /// </summary> ImageAndTextCSS = 3 } /// <summary> /// Group options /// </summary> public enum ButtonGroup : int { /// <summary> /// /// </summary> User = 0, /// <summary> /// /// </summary> Admin = 1, /// <summary> /// /// </summary> Custom = 2 } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Thread = Internal.Runtime.Augments.RuntimeThread; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ThreadLocal<ProcessingMode> m_threadProcessingMode = new ThreadLocal<ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exclusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recycling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static int DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private object ValueLock { get { return m_threadProcessingMode; } } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = int.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = int.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localThis = (ConcurrentExclusiveSchedulerPair)state; Debug.Assert(!localThis.m_completionState.Task.IsCompleted, "Completion should only happen once."); List<Exception> exceptions = localThis.m_completionState.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localThis.m_completionState.TrySetException(exceptions) : localThis.m_completionState.TrySetResult(default); Debug.Assert(success, "Expected to complete completion task."); localThis.m_threadProcessingMode.Dispose(); }, this); } } /// <summary>Initiates scheduler shutdown due to a worker task faulting.</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Debug.Assert(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Debug.Assert(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : TaskCompletionSource<VoidTaskResult> { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal List<Exception> m_exceptions; } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Debug.Assert(pair != null, "Scheduler must be associated with a valid pair."); Debug.Assert(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Debug.Assert( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().ToString()); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> internal void ExecuteTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. if (m_pair.m_threadProcessingMode.Value == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } finally { t.Dispose(); } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Debug.Assert(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Debug.Assert(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] private static void ContractAssertMonitorStatus(object syncObj, bool held) { Debug.Assert(syncObj != null, "The monitor object to check must be provided."); Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = TaskCreationOptions.DenyChildAttach; if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] private enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: FakeDataSource.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Entities=WPAppStudio.Entities; using EntitiesBase=WPAppStudio.Entities.Base; using RepositoriesBase=WPAppStudio.Repositories.Base; using WPAppStudio.Shared; namespace WPAppStudio.Repositories { /// <summary> /// Fake PhotoAlbumCollectionSchema data source. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public class FakePhotoAlbum_PhotoAlbumCollection : IPhotoAlbum_PhotoAlbumCollection { private const int MaxResults = 10; /// <summary> /// Retrieves the data from a fake. /// </summary> /// <returns>An observable collection of Entities.PhotoAlbumCollectionSchema items.</returns> public async Task<ObservableCollection<Entities.PhotoAlbumCollectionSchema>> GetData(int pageNumber = 0) { return await Task.Factory.StartNew(()=>new ObservableCollection<Entities.PhotoAlbumCollectionSchema>(new ObservableCollection<Entities.PhotoAlbumCollectionSchema>().Skip(MaxResults*pageNumber).Take(MaxResults)) { new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, }); } /// <summary> /// Refresh the data from a fake. /// </summary> /// <returns>An observable collection of Entities.PhotoAlbumCollectionSchema items.</returns> public async Task<ObservableCollection<Entities.PhotoAlbumCollectionSchema>> Refresh() { return await Task.Factory.StartNew(()=>new ObservableCollection<Entities.PhotoAlbumCollectionSchema>(new ObservableCollection<Entities.PhotoAlbumCollectionSchema>().Take(MaxResults)) { new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, new Entities.PhotoAlbumCollectionSchema() { Title = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Subtitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", Image = "..\\Images\\Logo.png", Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book", }, }); } /// <summary> /// Checks if data source has a element before the passed as parameter /// </summary> /// <param name="current">Current element</param> /// <returns>True, if there is a previous element, false if there is not</returns> public bool HasPrevious(Entities.PhotoAlbumCollectionSchema current) { var data = new List<Entities.PhotoAlbumCollectionSchema>(); if (current == null || !data.Any()) return false; return data.IndexOf(current) > 0; } /// <summary> /// Checks if data source has a element after the passed as parameter /// </summary> /// <param name="current">Current element</param> /// <returns>True, if there is a next element, false if there is not</returns> public async Task<bool> HasNext(Entities.PhotoAlbumCollectionSchema current) { var data = await GetData(); if (current == null || !data.Any()) return false; return data.IndexOf(current) < data.Count - 1; } /// <summary> /// Retrieves the previous element from source. /// </summary> /// <param name="current">Current element</param> /// <returns>The previous element from items, if it exists. Otherwise, returns null</returns> public Entities.PhotoAlbumCollectionSchema Previous(Entities.PhotoAlbumCollectionSchema current) { var data = new List<Entities.PhotoAlbumCollectionSchema>(); if (current == null) return data.FirstOrDefault(); if (data.Any() && data.First().Equals(current)) return null; return data[data.IndexOf(current) - 1]; } /// <summary> /// Retrieves the next element from source. /// </summary> /// <param name="current">Current element</param> /// <returns>The next element from items, if it exists. Otherwise, returns null</returns> public async Task<Entities.PhotoAlbumCollectionSchema> Next(Entities.PhotoAlbumCollectionSchema current) { var data = await GetData(); if (current == null) return data.FirstOrDefault(); if (data.Any() && data.Last().Equals(current)) return null; return data[data.IndexOf(current) + 1]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static volatile StrongBox<CURLMcode> s_supportsMaxConnectionsPerServer; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeaderLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (NetEventSource.IsEnabled) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates => _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } // Make sure the libcurl version we're using supports the option, by setting the value on a temporary multi handle. // We do this once and cache the result. StrongBox<CURLMcode> supported = s_supportsMaxConnectionsPerServer; // benign race condition to read and set this if (supported == null) { using (Interop.Http.SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate()) { s_supportsMaxConnectionsPerServer = supported = new StrongBox<CURLMcode>( Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, value)); } } if (supported.Value != CURLMcode.CURLM_OK) { throw new PlatformNotSupportedException(CurlException.GetCurlErrorString((int)supported.Value, isMulti: true)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return false; } set { } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy, agent: _agent); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookie) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } if (NetEventSource.IsEnabled) NetEventSource.Log.HandlerMessage( (agent?.RunningWorkerId).GetValueOrDefault(), easy != null ? easy.Task.Id : 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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 SharpDX.XAudio2 { public partial class Voice { protected readonly XAudio2 device; protected Voice(XAudio2 device) : base(IntPtr.Zero) { this.device = device; } /// <summary> /// <p>Returns information about the creation flags, input channels, and sample rate of a voice.</p> /// </summary> /// <include file='Documentation\CodeComments.xml' path="/comments/comment[@id='IXAudio2Voice::GetVoiceDetails']/*"/> /// <msdn-id>microsoft.directx_sdk.ixaudio2voice.ixaudio2voice.getvoicedetails</msdn-id> /// <unmanaged>GetVoiceDetails</unmanaged> /// <unmanaged-short>GetVoiceDetails</unmanaged-short> /// <unmanaged>void IXAudio2Voice::GetVoiceDetails([Out] XAUDIO2_VOICE_DETAILS* pVoiceDetails)</unmanaged> public SharpDX.XAudio2.VoiceDetails VoiceDetails { get { SharpDX.XAudio2.VoiceDetails __output__; GetVoiceDetails(out __output__); // Handle 2.7 version changes here if (device.Version == XAudio2Version.Version27) { __output__.InputSampleRate = __output__.InputChannelCount; __output__.InputChannelCount = __output__.ActiveFlags; __output__.ActiveFlags = 0; } return __output__; } } /// <summary> /// Enables the effect at a given position in the effect chain of the voice. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::EnableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged> public void EnableEffect(int effectIndex) { EnableEffect(effectIndex, 0); } /// <summary> /// Disables the effect at a given position in the effect chain of the voice. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::DisableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged> public void DisableEffect(int effectIndex) { DisableEffect(effectIndex, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <returns>Returns the current values of the effect-specific parameters.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public T GetEffectParameters<T>(int effectIndex) where T : struct { unsafe { var effectParameter = default(T); byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()]; GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, Utilities.SizeOf<T>()); Utilities.Read((IntPtr)pEffectParameter, ref effectParameter); return effectParameter; } } /// <summary> /// Returns the current effect-specific parameters of a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameters">[out] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::GetEffectParameters([None] UINT32 EffectIndex,[Out, Buffer] void* pParameters,[None] UINT32 ParametersByteSize)</unmanaged> public void GetEffectParameters(int effectIndex, byte[] effectParameters) { unsafe { fixed (void* pEffectParameter = &effectParameters[0]) GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameters.Length); } } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters(int effectIndex, byte[] effectParameter) { SetEffectParameters(effectIndex, effectParameter, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters(int effectIndex, byte[] effectParameter, int operationSet) { unsafe { fixed (void* pEffectParameter = &effectParameter[0]) SetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameter.Length, operationSet); } } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters<T>(int effectIndex, T effectParameter) where T : struct { this.SetEffectParameters<T>(effectIndex, effectParameter, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters<T>(int effectIndex, T effectParameter, int operationSet) where T : struct { unsafe { byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()]; Utilities.Write((IntPtr)pEffectParameter, ref effectParameter); SetEffectParameters(effectIndex, (IntPtr) pEffectParameter, Utilities.SizeOf<T>(), operationSet); } } /// <summary> /// Replaces the effect chain of the voice. /// </summary> /// <param name="effectDescriptors">[in, optional] an array of <see cref="SharpDX.XAudio2.EffectDescriptor"/> structure that describes the new effect chain to use. If NULL is passed, the current effect chain is removed. If array is non null, its length must be at least of 1. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectChain([In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged> public void SetEffectChain(params EffectDescriptor[] effectDescriptors) { unsafe { if (effectDescriptors != null) { var tempSendDescriptor = new EffectChain(); var effectDescriptorNatives = new EffectDescriptor.__Native[effectDescriptors.Length]; for (int i = 0; i < effectDescriptorNatives.Length; i++) effectDescriptors[i].__MarshalTo(ref effectDescriptorNatives[i]); tempSendDescriptor.EffectCount = effectDescriptorNatives.Length; fixed (void* pEffectDescriptors = &effectDescriptorNatives[0]) { tempSendDescriptor.EffectDescriptorPointer = (IntPtr)pEffectDescriptors; SetEffectChain(tempSendDescriptor); } } else { SetEffectChain((EffectChain?) null); } } } /// <summary> /// Designates a new set of submix or mastering voices to receive the output of the voice. /// </summary> /// <param name="outputVoices">[in] Array of <see cref="VoiceSendDescriptor"/> structure pointers to destination voices. If outputVoices is NULL, the voice will send its output to the current mastering voice. To set the voice to not send its output anywhere set an array of length 0. All of the voices in a send list must have the same input sample rate, see {{XAudio2 Sample Rate Conversions}} for additional information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputVoices([In, Optional] const XAUDIO2_VOICE_SENDS* pSendList)</unmanaged> public void SetOutputVoices(params VoiceSendDescriptor[] outputVoices) { unsafe { if (outputVoices != null) { var tempSendDescriptor = new VoiceSendDescriptors {SendCount = outputVoices.Length}; if(outputVoices.Length > 0) { fixed(void* pVoiceSendDescriptors = &outputVoices[0]) { tempSendDescriptor.SendPointer = (IntPtr)pVoiceSendDescriptors; SetOutputVoices(tempSendDescriptor); } } else { tempSendDescriptor.SendPointer = IntPtr.Zero; } } else { SetOutputVoices((VoiceSendDescriptors?) null); } } } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef) { this.SetOutputMatrix(sourceChannels, destinationChannels, levelMatrixRef, 0); } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="destinationVoiceRef">[in] Pointer to a destination <see cref="SharpDX.XAudio2.Voice"/> for which to set volume levels. Note If the voice sends to a single target voice then specifying NULL will cause SetOutputMatrix to operate on that target voice. </param> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(SharpDX.XAudio2.Voice destinationVoiceRef, int sourceChannels, int destinationChannels, float[] levelMatrixRef) { this.SetOutputMatrix(destinationVoiceRef, sourceChannels, destinationChannels, levelMatrixRef, 0); } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef, int operationSet) { this.SetOutputMatrix(null, sourceChannels, destinationChannels, levelMatrixRef, operationSet); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Extensions.ReplicationConstants.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Extensions { /* * public class ReplicationConstants */ /// <summary> Contains a collection of constants used by the replication management /// in Novell Ldap extensions. /// </summary> public class ReplicationConstants { /// <summary> A constant for the SplitPartitionRequest OID.</summary> public const System.String CREATE_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.3"; /// <summary> A constant for the SplitPartitionResponse OID.</summary> public const System.String CREATE_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.4"; /// <summary> A constant for the mergePartitionRequest OID.</summary> public const System.String MERGE_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.5"; /// <summary> A constant for the mergePartitionResponse OID.</summary> public const System.String MERGE_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.6"; /// <summary> A constant for the addReplicaRequest OID.</summary> public const System.String ADD_REPLICA_REQ = "2.16.840.1.113719.1.27.100.7"; /// <summary> A constant for the addReplicaResponse OID.</summary> public const System.String ADD_REPLICA_RES = "2.16.840.1.113719.1.27.100.8"; /// <summary> A constant for the refreshServerRequest OID.</summary> public const System.String REFRESH_SERVER_REQ = "2.16.840.1.113719.1.27.100.9"; /// <summary> A constant for the refreshServerResponse OID.</summary> public const System.String REFRESH_SERVER_RES = "2.16.840.1.113719.1.27.100.10"; /// <summary> A constant for the removeReplicaRequest OID.</summary> public const System.String DELETE_REPLICA_REQ = "2.16.840.1.113719.1.27.100.11"; /// <summary> A constant for the removeReplicaResponse OID.</summary> public const System.String DELETE_REPLICA_RES = "2.16.840.1.113719.1.27.100.12"; /// <summary> A constant for the partitionEntryCountRequest OID.</summary> public const System.String NAMING_CONTEXT_COUNT_REQ = "2.16.840.1.113719.1.27.100.13"; /// <summary> A constant for the partitionEntryCountResponse OID.</summary> public const System.String NAMING_CONTEXT_COUNT_RES = "2.16.840.1.113719.1.27.100.14"; /// <summary> A constant for the changeReplicaTypeRequest OID.</summary> public const System.String CHANGE_REPLICA_TYPE_REQ = "2.16.840.1.113719.1.27.100.15"; /// <summary> A constant for the changeReplicaTypeResponse OID.</summary> public const System.String CHANGE_REPLICA_TYPE_RES = "2.16.840.1.113719.1.27.100.16"; /// <summary> A constant for the getReplicaInfoRequest OID.</summary> public const System.String GET_REPLICA_INFO_REQ = "2.16.840.1.113719.1.27.100.17"; /// <summary> A constant for the getReplicaInfoResponse OID.</summary> public const System.String GET_REPLICA_INFO_RES = "2.16.840.1.113719.1.27.100.18"; /// <summary> A constant for the listReplicaRequest OID.</summary> public const System.String LIST_REPLICAS_REQ = "2.16.840.1.113719.1.27.100.19"; /// <summary> A constant for the listReplicaResponse OID.</summary> public const System.String LIST_REPLICAS_RES = "2.16.840.1.113719.1.27.100.20"; /// <summary> A constant for the receiveAllUpdatesRequest OID.</summary> public const System.String RECEIVE_ALL_UPDATES_REQ = "2.16.840.1.113719.1.27.100.21"; /// <summary> A constant for the receiveAllUpdatesResponse OID.</summary> public const System.String RECEIVE_ALL_UPDATES_RES = "2.16.840.1.113719.1.27.100.22"; /// <summary> A constant for the sendAllUpdatesRequest OID.</summary> public const System.String SEND_ALL_UPDATES_REQ = "2.16.840.1.113719.1.27.100.23"; /// <summary> A constant for the sendAllUpdatesResponse OID.</summary> public const System.String SEND_ALL_UPDATES_RES = "2.16.840.1.113719.1.27.100.24"; /// <summary> A constant for the requestPartitionSyncRequest OID.</summary> public const System.String NAMING_CONTEXT_SYNC_REQ = "2.16.840.1.113719.1.27.100.25"; /// <summary> A constant for the requestPartitionSyncResponse OID.</summary> public const System.String NAMING_CONTEXT_SYNC_RES = "2.16.840.1.113719.1.27.100.26"; /// <summary> A constant for the requestSchemaSyncRequest OID.</summary> public const System.String SCHEMA_SYNC_REQ = "2.16.840.1.113719.1.27.100.27"; /// <summary> A constant for the requestSchemaSyncResponse OID.</summary> public const System.String SCHEMA_SYNC_RES = "2.16.840.1.113719.1.27.100.28"; /// <summary> A constant for the abortPartitionOperationRequest OID.</summary> public const System.String ABORT_NAMING_CONTEXT_OP_REQ = "2.16.840.1.113719.1.27.100.29"; /// <summary> A constant for the abortPartitionOperationResponse OID.</summary> public const System.String ABORT_NAMING_CONTEXT_OP_RES = "2.16.840.1.113719.1.27.100.30"; /// <summary> A constant for the getContextIdentityNameRequest OID.</summary> public const System.String GET_IDENTITY_NAME_REQ = "2.16.840.1.113719.1.27.100.31"; /// <summary> A constant for the getContextIdentityNameResponse OID.</summary> public const System.String GET_IDENTITY_NAME_RES = "2.16.840.1.113719.1.27.100.32"; /// <summary> A constant for the getEffectivePrivilegesRequest OID.</summary> public const System.String GET_EFFECTIVE_PRIVILEGES_REQ = "2.16.840.1.113719.1.27.100.33"; /// <summary> A constant for the getEffectivePrivilegesResponse OID.</summary> public const System.String GET_EFFECTIVE_PRIVILEGES_RES = "2.16.840.1.113719.1.27.100.34"; /// <summary> A constant for the setReplicationFilterRequest OID.</summary> public const System.String SET_REPLICATION_FILTER_REQ = "2.16.840.1.113719.1.27.100.35"; /// <summary> A constant for the setReplicationFilterResponse OID.</summary> public const System.String SET_REPLICATION_FILTER_RES = "2.16.840.1.113719.1.27.100.36"; /// <summary> A constant for the getReplicationFilterRequest OID.</summary> public const System.String GET_REPLICATION_FILTER_REQ = "2.16.840.1.113719.1.27.100.37"; /// <summary> A constant for the getReplicationFilterResponse OID.</summary> public const System.String GET_REPLICATION_FILTER_RES = "2.16.840.1.113719.1.27.100.38"; /// <summary> A constant for the splitOrphanPartitionRequest OID.</summary> public const System.String CREATE_ORPHAN_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.39"; /// <summary> A constant for the splitOrphanPartitionResponse OID.</summary> public const System.String CREATE_ORPHAN_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.40"; /// <summary> A constant for the removeOrphanPartitionRequest OID.</summary> public const System.String REMOVE_ORPHAN_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.41"; /// <summary> A constant for the removeOrphanPartitionResponse OID.</summary> public const System.String REMOVE_ORPHAN_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.42"; /// <summary> A constant for the triggerBackLinkerRequest OID.</summary> public const System.String TRIGGER_BKLINKER_REQ = "2.16.840.1.113719.1.27.100.43"; /// <summary> A constant for the triggerBackLinkerResponse OID.</summary> public const System.String TRIGGER_BKLINKER_RES = "2.16.840.1.113719.1.27.100.44"; /// <summary> A constant for the triggerJanitorRequest OID.</summary> public const System.String TRIGGER_JANITOR_REQ = "2.16.840.1.113719.1.27.100.47"; /// <summary> A constant for the triggerJanitorResponse OID.</summary> public const System.String TRIGGER_JANITOR_RES = "2.16.840.1.113719.1.27.100.48"; /// <summary> A constant for the triggerLimberRequest OID.</summary> public const System.String TRIGGER_LIMBER_REQ = "2.16.840.1.113719.1.27.100.49"; /// <summary> A constant for the triggerLimberResponse OID.</summary> public const System.String TRIGGER_LIMBER_RES = "2.16.840.1.113719.1.27.100.50"; /// <summary> A constant for the triggerSkulkerRequest OID.</summary> public const System.String TRIGGER_SKULKER_REQ = "2.16.840.1.113719.1.27.100.51"; /// <summary> A constant for the triggerSkulkerResponse OID.</summary> public const System.String TRIGGER_SKULKER_RES = "2.16.840.1.113719.1.27.100.52"; /// <summary> A constant for the triggerSchemaSyncRequest OID.</summary> public const System.String TRIGGER_SCHEMA_SYNC_REQ = "2.16.840.1.113719.1.27.100.53"; /// <summary> A constant for the triggerSchemaSyncResponse OID.</summary> public const System.String TRIGGER_SCHEMA_SYNC_RES = "2.16.840.1.113719.1.27.100.54"; /// <summary> A constant for the triggerPartitionPurgeRequest OID.</summary> public const System.String TRIGGER_PART_PURGE_REQ = "2.16.840.1.113719.1.27.100.55"; /// <summary> A constant for the triggerPartitionPurgeResponse OID.</summary> public const System.String TRIGGER_PART_PURGE_RES = "2.16.840.1.113719.1.27.100.56"; /// <summary> A constant that specifies that all servers in a replica ring must be /// running for a partition operation to proceed. /// </summary> public const int Ldap_ENSURE_SERVERS_UP = 1; /// <summary> Identifies this replica as the master replica of the partition. /// /// On this type of replica, entries can be modified, and partition /// operations can be performed. /// </summary> public const int Ldap_RT_MASTER = 0; /// <summary> Identifies this replica as a secondary replica of the partition. /// /// On this type of replica, read and write operations can be performed, /// and entries can be modified. /// </summary> public const int Ldap_RT_SECONDARY = 1; /// <summary> Identifies this replica as a read-only replica of the partition. /// /// Only Novell eDirectory synchronization processes can modified /// entries on this replica. /// </summary> public const int Ldap_RT_READONLY = 2; /// <summary> Identifies this replica as a subordinate reference replica of the /// partition. /// /// NOvell eDirectory automatically adds these replicas to a server /// when the server does not contain replicas of all child partitions. /// Only eDirectory can modify information on these types of replicas. /// </summary> public const int Ldap_RT_SUBREF = 3; /// <summary> Identifies this replica as a read/write replica of the partition, /// but the replica contains sparse data. /// /// The replica has been configured to contain only specified object types /// and attributes. On this type of replica, only the attributes and objects /// contained in the sparse data can be modified. /// </summary> public const int Ldap_RT_SPARSE_WRITE = 4; /// <summary> Identifies this replica as a read-only replica of the partition, /// but the replica contains sparse data. /// /// The replica has been configured to contain only specified object types /// and attributes. On this type of replica, only Novell eDirectory /// synchronization processes can modify the sparse data. /// </summary> public const int Ldap_RT_SPARSE_READ = 5; //Replica States /// <summary> Indicates that the replica is fully functioning and capable of responding /// to requests. /// </summary> public const int Ldap_RS_ON = 0; /// <summary> Indicates that a new replica has been added but has not received a full /// download of information from the replica ring. /// </summary> public const int Ldap_RS_NEW_REPLICA = 1; /// <summary> Indicates that the replica is being deleted and that the request has /// been received. /// </summary> public const int Ldap_RS_DYING_REPLICA = 2; /// <summary> Indicates that the replica is locked. The move operation uses this state /// to lock the parent partition of the child partition that is moving. /// </summary> public const int Ldap_RS_LOCKED = 3; /// <summary> Indicates that a new replica has finished receiving its download from the /// master replica and is now receiving synchronization updates from other /// replicas. /// </summary> public const int Ldap_RS_TRANSITION_ON = 6; /// <summary> Indicates that the dying replica needs to synchronize with another replica /// before being converted either to an external reference, if a root replica, /// or to a subordinate reference, if a non-root replica. /// </summary> public const int Ldap_RS_DEAD_REPLICA = 7; /// <summary> Indicates that the subordinate references of the new replica are being /// added. /// </summary> public const int Ldap_RS_BEGIN_ADD = 8; /// <summary> Indicates that a partition is receiving a new master replica. /// /// The replica that will be the new master replica is set to this state. /// </summary> public const int Ldap_RS_MASTER_START = 11; /// <summary> Indicates that a partition has a new master replica. /// /// When the new master is set to this state, Novell eDirectory knows /// that the replica is now the master and changes its replica type to /// master and the old master to read/write. /// </summary> public const int Ldap_RS_MASTER_DONE = 12; /// <summary> Indicates that the partition is going to split into two partitions. /// /// In this state, other replicas of the partition are informed of the /// pending split. /// </summary> public const int Ldap_RS_SS_0 = 48; // Replica splitting 0 /// <summary> Indicates that that the split partition operation has started. /// /// When the split is finished, the state will change to RS_ON. /// </summary> public const int Ldap_RS_SS_1 = 49; // Replica splitting 1 /// <summary> Indicates that that two partitions are in the process of joining /// into one partition. /// /// In this state, the replicas that are affected are informed of the join /// operation. The master replica of the parent and child partitions are /// first set to this state and then all the replicas of the parent and child. /// New replicas are added where needed. /// </summary> public const int Ldap_RS_JS_0 = 64; // Replica joining 0 /// <summary> Indicates that that two partitions are in the process of joining /// into one partition. /// /// This state indicates that the join operation is waiting for the new /// replicas to synchronize and move to the RS_ON state. /// </summary> public const int Ldap_RS_JS_1 = 65; // Replica joining 1 /// <summary> Indicates that that two partitions are in the process of joining /// into one partition. /// /// This state indicates that all the new replicas are in the RS_ON state /// and that the rest of the work can be completed. /// </summary> public const int Ldap_RS_JS_2 = 66; // Replica joining 2 // Values for flags used in the replica info class structure /// <summary> Indicates that the replica is involved with a partition operation, /// for example, merging a tree or moving a subtree. /// </summary> public const int Ldap_DS_FLAG_BUSY = 0x0001; /// <summary> Indicates that this partition is on the DNS federation boundary. /// This flag is only set on DNS trees. /// </summary> public const int Ldap_DS_FLAG_BOUNDARY = 0x0002; public ReplicationConstants() { } } }
using System; using System.ComponentModel; using System.Data.Linq; using System.Linq; using System.Data.Linq.Mapping; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using System.Runtime.Serialization; using System.Reflection; using Dg.Deblazer; using Dg.Deblazer.Validation; using Dg.Deblazer.CodeAnnotation; using Dg.Deblazer.Api; using Dg.Deblazer.Visitors; using Dg.Deblazer.Cache; using Dg.Deblazer.SqlGeneration; using Deblazer.WideWorldImporter.DbLayer.Queries; using Deblazer.WideWorldImporter.DbLayer.Wrappers; using Dg.Deblazer.Read; namespace Deblazer.WideWorldImporter.DbLayer { public partial class Warehouse_PackageType : DbEntity, IId { private DbValue<System.Int32> _PackageTypeID = new DbValue<System.Int32>(); private DbValue<System.String> _PackageTypeName = new DbValue<System.String>(); private DbValue<System.Int32> _LastEditedBy = new DbValue<System.Int32>(); private DbValue<System.DateTime> _ValidFrom = new DbValue<System.DateTime>(); private DbValue<System.DateTime> _ValidTo = new DbValue<System.DateTime>(); private IDbEntitySet<Purchasing_PurchaseOrderLine> _Purchasing_PurchaseOrderLines; private IDbEntitySet<Sales_InvoiceLine> _Sales_InvoiceLines; private IDbEntitySet<Sales_OrderLine> _Sales_OrderLines; private IDbEntityRef<Application_People> _Application_People; private IDbEntitySet<Warehouse_StockItem> _Warehouse_StockItems; private IDbEntitySet<Warehouse_StockItem> _PackageTypes; public int Id => PackageTypeID; long ILongId.Id => PackageTypeID; [Validate] public System.Int32 PackageTypeID { get { return _PackageTypeID.Entity; } set { _PackageTypeID.Entity = value; } } [StringColumn(50, false)] [Validate] public System.String PackageTypeName { get { return _PackageTypeName.Entity; } set { _PackageTypeName.Entity = value; } } [Validate] public System.Int32 LastEditedBy { get { return _LastEditedBy.Entity; } set { _LastEditedBy.Entity = value; } } [StringColumn(7, false)] [Validate] public System.DateTime ValidFrom { get { return _ValidFrom.Entity; } set { _ValidFrom.Entity = value; } } [StringColumn(7, false)] [Validate] public System.DateTime ValidTo { get { return _ValidTo.Entity; } set { _ValidTo.Entity = value; } } [Validate] public IDbEntitySet<Purchasing_PurchaseOrderLine> Purchasing_PurchaseOrderLines { get { if (_Purchasing_PurchaseOrderLines == null) { if (_getChildrenFromCache) { _Purchasing_PurchaseOrderLines = new DbEntitySetCached<Warehouse_PackageType, Purchasing_PurchaseOrderLine>(() => _PackageTypeID.Entity); } } else _Purchasing_PurchaseOrderLines = new DbEntitySet<Purchasing_PurchaseOrderLine>(_db, false, new Func<long ? >[]{() => _PackageTypeID.Entity}, new[]{"[PackageTypeID]"}, (member, root) => member.Warehouse_PackageType = root as Warehouse_PackageType, this, _lazyLoadChildren, e => e.Warehouse_PackageType = this, e => { var x = e.Warehouse_PackageType; e.Warehouse_PackageType = null; new UpdateSetVisitor(true, new[]{"PackageTypeID"}, false).Process(x); } ); return _Purchasing_PurchaseOrderLines; } } [Validate] public IDbEntitySet<Sales_InvoiceLine> Sales_InvoiceLines { get { if (_Sales_InvoiceLines == null) { if (_getChildrenFromCache) { _Sales_InvoiceLines = new DbEntitySetCached<Warehouse_PackageType, Sales_InvoiceLine>(() => _PackageTypeID.Entity); } } else _Sales_InvoiceLines = new DbEntitySet<Sales_InvoiceLine>(_db, false, new Func<long ? >[]{() => _PackageTypeID.Entity}, new[]{"[PackageTypeID]"}, (member, root) => member.Warehouse_PackageType = root as Warehouse_PackageType, this, _lazyLoadChildren, e => e.Warehouse_PackageType = this, e => { var x = e.Warehouse_PackageType; e.Warehouse_PackageType = null; new UpdateSetVisitor(true, new[]{"PackageTypeID"}, false).Process(x); } ); return _Sales_InvoiceLines; } } [Validate] public IDbEntitySet<Sales_OrderLine> Sales_OrderLines { get { if (_Sales_OrderLines == null) { if (_getChildrenFromCache) { _Sales_OrderLines = new DbEntitySetCached<Warehouse_PackageType, Sales_OrderLine>(() => _PackageTypeID.Entity); } } else _Sales_OrderLines = new DbEntitySet<Sales_OrderLine>(_db, false, new Func<long ? >[]{() => _PackageTypeID.Entity}, new[]{"[PackageTypeID]"}, (member, root) => member.Warehouse_PackageType = root as Warehouse_PackageType, this, _lazyLoadChildren, e => e.Warehouse_PackageType = this, e => { var x = e.Warehouse_PackageType; e.Warehouse_PackageType = null; new UpdateSetVisitor(true, new[]{"PackageTypeID"}, false).Process(x); } ); return _Sales_OrderLines; } } [Validate] public Application_People Application_People { get { Action<Application_People> beforeRightsCheckAction = e => e.Warehouse_PackageTypes.Add(this); if (_Application_People != null) { return _Application_People.GetEntity(beforeRightsCheckAction); } _Application_People = GetDbEntityRef(true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, beforeRightsCheckAction); return (Application_People != null) ? _Application_People.GetEntity(beforeRightsCheckAction) : null; } set { if (_Application_People == null) { _Application_People = new DbEntityRef<Application_People>(_db, true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, _lazyLoadChildren, _getChildrenFromCache); } AssignDbEntity<Application_People, Warehouse_PackageType>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.PersonID}, _Application_People, new long ? []{_LastEditedBy.Entity}, new Action<long ? >[]{x => LastEditedBy = (int ? )x ?? default (int)}, x => x.Warehouse_PackageTypes, null, LastEditedByChanged); } } void LastEditedByChanged(object sender, EventArgs eventArgs) { if (sender is Application_People) _LastEditedBy.Entity = (int)((Application_People)sender).Id; } [Validate] public IDbEntitySet<Warehouse_StockItem> Warehouse_StockItems { get { if (_Warehouse_StockItems == null) { if (_getChildrenFromCache) { _Warehouse_StockItems = new DbEntitySetCached<Warehouse_PackageType, Warehouse_StockItem>(() => _PackageTypeID.Entity); } } else _Warehouse_StockItems = new DbEntitySet<Warehouse_StockItem>(_db, false, new Func<long ? >[]{() => _PackageTypeID.Entity}, new[]{"[OuterPackageID]"}, (member, root) => member.Warehouse_PackageType = root as Warehouse_PackageType, this, _lazyLoadChildren, e => e.Warehouse_PackageType = this, e => { var x = e.Warehouse_PackageType; e.Warehouse_PackageType = null; new UpdateSetVisitor(true, new[]{"OuterPackageID"}, false).Process(x); } ); return _Warehouse_StockItems; } } [Validate] public IDbEntitySet<Warehouse_StockItem> PackageTypes { get { if (_PackageTypes == null) { if (_getChildrenFromCache) { _PackageTypes = new DbEntitySetCached<Warehouse_PackageType, Warehouse_StockItem>(() => _PackageTypeID.Entity); } } else _PackageTypes = new DbEntitySet<Warehouse_StockItem>(_db, false, new Func<long ? >[]{() => _PackageTypeID.Entity}, new[]{"[UnitPackageID]"}, (member, root) => member.Warehouse_PackageType = root as Warehouse_PackageType, this, _lazyLoadChildren, e => e.Warehouse_PackageType = this, e => { var x = e.Warehouse_PackageType; e.Warehouse_PackageType = null; new UpdateSetVisitor(true, new[]{"UnitPackageID"}, false).Process(x); } ); return _PackageTypes; } } protected override void ModifyInternalState(FillVisitor visitor) { SendIdChanging(); _PackageTypeID.Load(visitor.GetInt32()); SendIdChanged(); _PackageTypeName.Load(visitor.GetValue<System.String>()); _LastEditedBy.Load(visitor.GetInt32()); _ValidFrom.Load(visitor.GetDateTime()); _ValidTo.Load(visitor.GetDateTime()); this._db = visitor.Db; isLoaded = true; } protected sealed override void CheckProperties(IUpdateVisitor visitor) { _PackageTypeID.Welcome(visitor, "PackageTypeID", "Int NOT NULL", false); _PackageTypeName.Welcome(visitor, "PackageTypeName", "NVarChar(50) NOT NULL", false); _LastEditedBy.Welcome(visitor, "LastEditedBy", "Int NOT NULL", false); _ValidFrom.Welcome(visitor, "ValidFrom", "DateTime2(7) NOT NULL", false); _ValidTo.Welcome(visitor, "ValidTo", "DateTime2(7) NOT NULL", false); } protected override void HandleChildren(DbEntityVisitorBase visitor) { visitor.ProcessAssociation(this, _Purchasing_PurchaseOrderLines); visitor.ProcessAssociation(this, _Sales_InvoiceLines); visitor.ProcessAssociation(this, _Sales_OrderLines); visitor.ProcessAssociation(this, _Application_People); visitor.ProcessAssociation(this, _Warehouse_StockItems); visitor.ProcessAssociation(this, _PackageTypes); } } public static class Db_Warehouse_PackageTypeQueryGetterExtensions { public static Warehouse_PackageTypeTableQuery<Warehouse_PackageType> Warehouse_PackageTypes(this IDb db) { var query = new Warehouse_PackageTypeTableQuery<Warehouse_PackageType>(db as IDb); return query; } } } namespace Deblazer.WideWorldImporter.DbLayer.Queries { public class Warehouse_PackageTypeQuery<K, T> : Query<K, T, Warehouse_PackageType, Warehouse_PackageTypeWrapper, Warehouse_PackageTypeQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId { public Warehouse_PackageTypeQuery(IDb db): base (db) { } protected sealed override Warehouse_PackageTypeWrapper GetWrapper() { return Warehouse_PackageTypeWrapper.Instance; } public Purchasing_PurchaseOrderLineQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinPurchasing_PurchaseOrderLines(JoinType joinType = JoinType.Inner, bool attach = false) { var joinedQuery = new Purchasing_PurchaseOrderLineQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return JoinSet(() => new Purchasing_PurchaseOrderLineTableQuery<Purchasing_PurchaseOrderLine>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[PurchaseOrderLines] AS {1} {0} ON", "{2}.[PackageTypeID] = {1}.[PackageTypeID]"), (p, ids) => ((Purchasing_PurchaseOrderLineWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Warehouse_PackageType)o).Purchasing_PurchaseOrderLines.Attach(v.Cast<Purchasing_PurchaseOrderLine>()), p => (long)((Purchasing_PurchaseOrderLine)p).PackageTypeID, attach); } public Sales_InvoiceLineQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinSales_InvoiceLines(JoinType joinType = JoinType.Inner, bool attach = false) { var joinedQuery = new Sales_InvoiceLineQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return JoinSet(() => new Sales_InvoiceLineTableQuery<Sales_InvoiceLine>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[InvoiceLines] AS {1} {0} ON", "{2}.[PackageTypeID] = {1}.[PackageTypeID]"), (p, ids) => ((Sales_InvoiceLineWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Warehouse_PackageType)o).Sales_InvoiceLines.Attach(v.Cast<Sales_InvoiceLine>()), p => (long)((Sales_InvoiceLine)p).PackageTypeID, attach); } public Sales_OrderLineQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinSales_OrderLines(JoinType joinType = JoinType.Inner, bool attach = false) { var joinedQuery = new Sales_OrderLineQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return JoinSet(() => new Sales_OrderLineTableQuery<Sales_OrderLine>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Sales].[OrderLines] AS {1} {0} ON", "{2}.[PackageTypeID] = {1}.[PackageTypeID]"), (p, ids) => ((Sales_OrderLineWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Warehouse_PackageType)o).Sales_OrderLines.Attach(v.Cast<Sales_OrderLine>()), p => (long)((Sales_OrderLine)p).PackageTypeID, attach); } public Application_PeopleQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinApplication_People(JoinType joinType = JoinType.Inner, bool preloadEntities = false) { var joinedQuery = new Application_PeopleQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[People] AS {1} {0} ON", "{2}.[LastEditedBy] = {1}.[PersonID]"), o => ((Warehouse_PackageType)o)?.Application_People, (e, fv, ppe) => { var child = (Application_People)ppe(QueryHelpers.Fill<Application_People>(null, fv)); if (e != null) { ((Warehouse_PackageType)e).Application_People = child; } return child; } , typeof (Application_People), preloadEntities); } public Warehouse_StockItemQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinWarehouse_StockItems(JoinType joinType = JoinType.Inner, bool attach = false) { var joinedQuery = new Warehouse_StockItemQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return JoinSet(() => new Warehouse_StockItemTableQuery<Warehouse_StockItem>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Warehouse].[StockItems] AS {1} {0} ON", "{2}.[PackageTypeID] = {1}.[OuterPackageID]"), (p, ids) => ((Warehouse_StockItemWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Warehouse_PackageType)o).Warehouse_StockItems.Attach(v.Cast<Warehouse_StockItem>()), p => (long)((Warehouse_StockItem)p).OuterPackageID, attach); } public Warehouse_StockItemQuery<Warehouse_PackageTypeQuery<K, T>, T> JoinPackageTypes(JoinType joinType = JoinType.Inner, bool attach = false) { var joinedQuery = new Warehouse_StockItemQuery<Warehouse_PackageTypeQuery<K, T>, T>(Db); return JoinSet(() => new Warehouse_StockItemTableQuery<Warehouse_StockItem>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Warehouse].[StockItems] AS {1} {0} ON", "{2}.[PackageTypeID] = {1}.[UnitPackageID]"), (p, ids) => ((Warehouse_StockItemWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Warehouse_PackageType)o).PackageTypes.Attach(v.Cast<Warehouse_StockItem>()), p => (long)((Warehouse_StockItem)p).UnitPackageID, attach); } } public class Warehouse_PackageTypeTableQuery<T> : Warehouse_PackageTypeQuery<Warehouse_PackageTypeTableQuery<T>, T> where T : DbEntity, ILongId { public Warehouse_PackageTypeTableQuery(IDb db): base (db) { } } } namespace Deblazer.WideWorldImporter.DbLayer.Helpers { public class Warehouse_PackageTypeHelper : QueryHelper<Warehouse_PackageType>, IHelper<Warehouse_PackageType> { string[] columnsInSelectStatement = new[]{"{0}.PackageTypeID", "{0}.PackageTypeName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"}; public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement; string[] columnsInInsertStatement = new[]{"{0}.PackageTypeID", "{0}.PackageTypeName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"}; public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement; private static readonly string createTempTableCommand = "CREATE TABLE #Warehouse_PackageType ([PackageTypeID] Int NOT NULL,[PackageTypeName] NVarChar(50) NOT NULL,[LastEditedBy] Int NOT NULL,[ValidFrom] DateTime2(7) NOT NULL,[ValidTo] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)"; public sealed override string CreateTempTableCommand => createTempTableCommand; public sealed override string FullTableName => "[Warehouse].[PackageTypes]"; public sealed override bool IsForeignKeyTo(Type other) { return other == typeof (Purchasing_PurchaseOrderLine) || other == typeof (Sales_InvoiceLine) || other == typeof (Sales_OrderLine) || other == typeof (Warehouse_StockItem) || other == typeof (Warehouse_StockItem); } private const string insertCommand = "INSERT INTO [Warehouse].[PackageTypes] ([{TableName = \"Warehouse].[PackageTypes\";}].[PackageTypeID], [{TableName = \"Warehouse].[PackageTypes\";}].[PackageTypeName], [{TableName = \"Warehouse].[PackageTypes\";}].[LastEditedBy], [{TableName = \"Warehouse].[PackageTypes\";}].[ValidFrom], [{TableName = \"Warehouse].[PackageTypes\";}].[ValidTo]) VALUES ([@PackageTypeID],[@PackageTypeName],[@LastEditedBy],[@ValidFrom],[@ValidTo]); SELECT SCOPE_IDENTITY()"; public sealed override void FillInsertCommand(SqlCommand sqlCommand, Warehouse_PackageType _Warehouse_PackageType) { sqlCommand.CommandText = insertCommand; sqlCommand.Parameters.AddWithValue("@PackageTypeID", _Warehouse_PackageType.PackageTypeID); sqlCommand.Parameters.AddWithValue("@PackageTypeName", _Warehouse_PackageType.PackageTypeName ?? (object)DBNull.Value); sqlCommand.Parameters.AddWithValue("@LastEditedBy", _Warehouse_PackageType.LastEditedBy); sqlCommand.Parameters.AddWithValue("@ValidFrom", _Warehouse_PackageType.ValidFrom); sqlCommand.Parameters.AddWithValue("@ValidTo", _Warehouse_PackageType.ValidTo); } public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Warehouse_PackageType _Warehouse_PackageType) { using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess)) { sqlDataReader.Read(); _Warehouse_PackageType.PackageTypeID = Convert.ToInt32(sqlDataReader.GetValue(0)); } } private static Warehouse_PackageTypeWrapper _wrapper = Warehouse_PackageTypeWrapper.Instance; public QueryWrapper Wrapper { get { return _wrapper; } } } } namespace Deblazer.WideWorldImporter.DbLayer.Wrappers { public class Warehouse_PackageTypeWrapper : QueryWrapper<Warehouse_PackageType> { public readonly QueryElMemberId<Application_People> LastEditedBy = new QueryElMemberId<Application_People>("LastEditedBy"); public readonly QueryElMember<System.String> PackageTypeName = new QueryElMember<System.String>("PackageTypeName"); public readonly QueryElMemberStruct<System.DateTime> ValidFrom = new QueryElMemberStruct<System.DateTime>("ValidFrom"); public readonly QueryElMemberStruct<System.DateTime> ValidTo = new QueryElMemberStruct<System.DateTime>("ValidTo"); public static readonly Warehouse_PackageTypeWrapper Instance = new Warehouse_PackageTypeWrapper(); private Warehouse_PackageTypeWrapper(): base ("[Warehouse].[PackageTypes]", "Warehouse_PackageType") { } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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 // https://github.com/enyim/EnyimMemcached/wiki/MemcachedClient-Usage using System; using Enyim.Caching.Memcached; using System.Collections.Generic; namespace Contoso.Abstract { public partial class MemcachedServiceCache { /// <summary> /// ITagMapper /// </summary> public interface ITagMapper { /// <summary> /// Toes the add opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="cas">The cas.</param> /// <param name="opvalue">The opvalue.</param> /// <returns></returns> TagMapper.AddOpcode ToAddOpcode(object tag, ref string name, out ulong cas, out object opvalue); /// <summary> /// Toes the set opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="cas">The cas.</param> /// <param name="opvalue">The opvalue.</param> /// <param name="storeMode">The store mode.</param> /// <returns></returns> TagMapper.SetOpcode ToSetOpcode(object tag, ref string name, out ulong cas, out object opvalue, out StoreMode storeMode); /// <summary> /// Toes the get opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="opvalue">The opvalue.</param> /// <returns></returns> TagMapper.GetOpcode ToGetOpcode(object tag, out object opvalue); } /// <summary> /// TagMapper /// </summary> public class TagMapper : ITagMapper { /// <summary> /// AddOpcode /// </summary> public enum AddOpcode { /// <summary> /// Append /// </summary> Append, /// <summary> /// AppendCas /// </summary> AppendCas, /// <summary> /// Store /// </summary> Store, /// <summary> /// Cas /// </summary> Cas, } /// <summary> /// SetOpcode /// </summary> public enum SetOpcode { /// <summary> /// Prepend /// </summary> Prepend, /// <summary> /// PrependCas /// </summary> PrependCas, /// <summary> /// Store /// </summary> Store, /// <summary> /// Cas /// </summary> Cas, /// <summary> /// Decrement /// </summary> Decrement, /// <summary> /// DecrementCas /// </summary> DecrementCas, /// <summary> /// Increment /// </summary> Increment, /// <summary> /// IncrementCas /// </summary> IncrementCas } /// <summary> /// GetOpcode /// </summary> public enum GetOpcode { /// <summary> /// Get /// </summary> Get, //PerformMultiGet, } /// <summary> /// Toes the add opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="cas">The cas.</param> /// <param name="opvalue">The opvalue.</param> /// <returns></returns> public AddOpcode ToAddOpcode(object tag, ref string name, out ulong cas, out object opvalue) { if (name == null) throw new ArgumentNullException("name"); // determine flag, striping name if needed bool flag = name.StartsWith("#"); if (flag) name = name.Substring(1); // store if (tag == null) { cas = 0; opvalue = null; return AddOpcode.Store; } // if (tag is CasResult<object>) { var plainCas = (CasResult<object>)tag; cas = plainCas.Cas; opvalue = null; return AddOpcode.Cas; } // append if (tag is ArraySegment<byte>) { cas = 0; opvalue = tag; return AddOpcode.Append; } else if (tag is CasResult<ArraySegment<byte>>) { var appendCas = (CasResult<ArraySegment<byte>>)tag; cas = appendCas.Cas; opvalue = appendCas.Result; return AddOpcode.AppendCas; } throw new InvalidOperationException(); } /// <summary> /// Toes the set opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="cas">The cas.</param> /// <param name="opvalue">The opvalue.</param> /// <param name="storeMode">The store mode.</param> /// <returns></returns> public SetOpcode ToSetOpcode(object tag, ref string name, out ulong cas, out object opvalue, out StoreMode storeMode) { if (name == null) throw new ArgumentNullException("name"); // determine flag, striping name if needed bool flag = name.StartsWith("#"); if (flag) { storeMode = StoreMode.Replace; name = name.Substring(1); } else storeMode = StoreMode.Set; // store if (tag == null) { cas = 0; opvalue = null; return SetOpcode.Store; } // if (tag is CasResult<object>) { var plainCas = (CasResult<object>)tag; cas = plainCas.Cas; opvalue = null; return SetOpcode.Cas; } // prepend if (tag is ArraySegment<byte>) { cas = 0; opvalue = tag; return SetOpcode.Prepend; } else if (tag is CasResult<ArraySegment<byte>>) { var appendCas = (CasResult<ArraySegment<byte>>)tag; cas = appendCas.Cas; opvalue = appendCas.Result; return SetOpcode.PrependCas; } // decrement else if (tag is DecrementTag) { cas = 0; opvalue = (DecrementTag)tag; return SetOpcode.Decrement; } else if (tag is CasResult<DecrementTag>) { var decrementCas = (CasResult<DecrementTag>)tag; cas = decrementCas.Cas; opvalue = decrementCas.Result; return SetOpcode.DecrementCas; } // increment else if (tag is IncrementTag) { cas = 0; opvalue = (IncrementTag)tag; return SetOpcode.Increment; } else if (tag is CasResult<IncrementTag>) { var incrementCas = (CasResult<IncrementTag>)tag; cas = incrementCas.Cas; opvalue = incrementCas.Result; return SetOpcode.IncrementCas; } throw new InvalidOperationException(); } /// <summary> /// Toes the get opcode. /// </summary> /// <param name="tag">The tag.</param> /// <param name="opvalue">The opvalue.</param> /// <returns></returns> public GetOpcode ToGetOpcode(object tag, out object opvalue) { opvalue = tag; return GetOpcode.Get; // (tag is Func<IMultiGetOperation, KeyValuePair<string, CacheItem>, object> ? GetOpcode.PerformMultiGet : GetOpcode.Get); } } } }
// // DocumentTest.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin 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.Collections.Generic; using Couchbase.Lite.Internal; using NUnit.Framework; using Couchbase.Lite.Revisions; using System; using System.Linq; using Couchbase.Lite.Util; using System.Diagnostics; using System.Threading; namespace Couchbase.Lite { [TestFixture("ForestDB")] public class DocumentTest : LiteTestCase { public DocumentTest(string storageType) : base(storageType) {} [Test] public void TestExpireDocument() { Log.Domains.Database.Level = Log.LogLevel.None; var future = DateTime.UtcNow.AddSeconds(12345); Trace.WriteLine($"Now is {DateTime.UtcNow}"); var doc = CreateDocumentWithProperties(database, new Dictionary<string, object> { { "foo", 17 } }); Assert.IsNull(doc.GetExpirationDate()); database.RunInTransaction(() => { doc.ExpireAt(future); return true; }); var exp = doc.GetExpirationDate(); Trace.WriteLine($"Doc expiration is {exp}"); Assert.IsNotNull(exp); Assert.IsTrue(Math.Abs((exp.Value - future).TotalSeconds) < 1.0); var next = database.Storage.NextDocumentExpiry(); Trace.WriteLine($"Next expiry at {next}"); database.RunInTransaction(() => { doc.ExpireAt(null); return true; }); Assert.IsNull(doc.GetExpirationDate()); Assert.IsNull(database.Storage.NextDocumentExpiry()); Trace.WriteLine("Creating documents"); CreateDocuments(database, 10000); var cd = new CountdownEvent(1000); database.Changed += (sender, args) => { foreach(var change in args.Changes) { if(change.IsExpiration) { cd.Signal(); } } }; Trace.WriteLine("Marking docs for expiration"); int total = 0, marked = 0; database.RunInTransaction(() => { foreach(var row in database.CreateAllDocumentsQuery().Run()) { var resultDoc = row.Document; var sequence = resultDoc.GetProperty<long>("sequence"); if((sequence % 10) == 6) { resultDoc.ExpireAfter(TimeSpan.FromSeconds(2)); ++marked; } else if((sequence % 10) == 3) { resultDoc.ExpireAt(future); } ++total; } return true; }); Assert.AreEqual(10001, total); Assert.AreEqual(1000, marked); next = database.Storage.NextDocumentExpiry(); Trace.WriteLine($"Next expiration at {next}"); //Assert.IsTrue(next - DateTime.UtcNow <= TimeSpan.FromSeconds(2)); //Assert.IsTrue(next - DateTime.UtcNow >= TimeSpan.FromSeconds(-10)); Trace.WriteLine("Waiting for auto expiration"); cd.Wait(TimeSpan.FromSeconds(10)); Assert.AreEqual(9001, database.GetDocumentCount()); total = 0; foreach(var row in database.CreateAllDocumentsQuery().Run()) { var resultDoc = row.Document; var sequence = resultDoc.GetProperty<long>("sequence"); Assert.AreNotEqual(6, sequence % 10); ++total; } Assert.AreEqual(9001, total); next = database.Storage.NextDocumentExpiry(); Trace.WriteLine($"Next expiration is {next}"); Assert.IsTrue(Math.Abs((next.Value - future).TotalSeconds) < 1.0); } [Test] // #447 public void TestDocumentArraysMaintainOrder() { List<int> dateArray = new List<int> { 2015, 6, 14, 1, 10, 0 }; var props = new Dictionary<string, object> { { "starttime", dateArray } }; var doc = database.CreateDocument(); var docId = doc.Id; doc.PutProperties(props); var doc2 = database.GetExistingDocument(docId); Assert.AreEqual(dateArray, doc2.UserProperties["starttime"].AsList<int>()); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestNewDocumentHasCurrentRevision() { var document = database.CreateDocument(); var properties = new Dictionary<string, object>() { {"foo", "foo"}, {"bar", false} }; document.PutProperties(properties); Assert.IsNotNull(document.CurrentRevisionId); Assert.IsNotNull(document.CurrentRevision); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestGetNonExistentDocument() { Assert.IsNull(database.GetExistingDocument("missing")); var doc = database.GetDocument("missing"); Assert.IsNotNull(doc); Assert.IsNull(database.GetExistingDocument("missing")); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestUnsavedDocumentReturnsNullValues() { var document = database.CreateDocument(); try { Assert.IsNull(document.Properties); Assert.IsNull(document.CurrentRevisionId); Assert.IsNull(document.CurrentRevision); Assert.IsNull(document.RevisionHistory); Assert.IsNull(document.GetRevision("doc2")); } catch { Assert.Fail("Document getter threw an exception"); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestSavedDocumentHasCurrentRevision() { var document = database.CreateDocument(); var properties = new Dictionary<string, object>(); properties["foo"] = "foo"; properties["bar"] = false; document.PutProperties(properties); Assert.IsNotNull(document.CurrentRevisionId); Assert.IsNotNull(document.CurrentRevision); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestPutDeletedDocument() { Document document = database.CreateDocument(); var properties = new Dictionary<string, object>(); properties["foo"] = "foo"; properties["bar"] = false; document.PutProperties(properties); Assert.IsNotNull(document.CurrentRevision); var docId = document.Id; properties.SetRevID(document.CurrentRevisionId); properties["_deleted"] = true; properties["mykey"] = "myval"; var newRev = document.PutProperties(properties); newRev.LoadProperties(); Assert.IsTrue(newRev.Properties.ContainsKey("mykey")); Assert.IsTrue(document.Deleted); var featchedDoc = database.GetExistingDocument(docId); Assert.IsNull(featchedDoc); var queryAllDocs = database.CreateAllDocumentsQuery(); var queryEnumerator = queryAllDocs.Run(); foreach(QueryRow row in queryEnumerator) { Assert.AreNotEqual(row.Document.Id, docId); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestDeleteDocument() { var document = database.CreateDocument(); var properties = new Dictionary<string, object>(); properties["foo"] = "foo"; properties["bar"] = false; document.PutProperties(properties); Assert.IsNotNull(document.CurrentRevision); var docId = document.Id; document.Delete(); Assert.IsTrue(document.Deleted); Document fetchedDoc = database.GetExistingDocument(docId); Assert.IsNull(fetchedDoc); // query all docs and make sure we don't see that document Query queryAllDocs = database.CreateAllDocumentsQuery(); QueryEnumerator queryEnumerator = queryAllDocs.Run(); foreach (var row in queryEnumerator) { Assert.IsFalse(row.Document.Id.Equals(docId)); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestDocumentWithRemovedProperty() { var props = new Dictionary<string, object>() { {"_id", "fakeid"}, {"_removed", true}, {"foo", "bar"} }; var doc = CreateDocumentWithProperties(database, props); Assert.IsNotNull(doc); var docFetched = database.GetDocument(doc.Id); var fetchedProps = docFetched.CurrentRevision.Properties; Assert.IsNotNull(fetchedProps["_removed"]); Assert.IsTrue(docFetched.CurrentRevision.IsGone); } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [Test] public void TestLoadRevisionBody() { var document = database.CreateDocument(); var properties = new Dictionary<string, object>(); properties["foo"] = "foo"; properties["bar"] = false; properties["_id"] = document.Id; document.PutProperties(properties); properties.SetRevID(document.CurrentRevisionId); Assert.IsNotNull(document.CurrentRevision); var revisionInternal = new RevisionInternal( document.Id, document.CurrentRevisionId.AsRevID(), false); database.LoadRevisionBody(revisionInternal); Assert.AreEqual(properties, revisionInternal.GetProperties()); revisionInternal.SetBody(null); // now lets purge the document, and then try to load the revision body again document.Purge(); var gotExpectedException = false; try { database.LoadRevisionBody(revisionInternal); } catch (CouchbaseLiteException e) { gotExpectedException |= e.CBLStatus.Code == StatusCode.NotFound; } Assert.IsTrue(gotExpectedException); } } }
// *********************************************************************** // Copyright (c) 2007 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.Collections.Generic; using System.Reflection; using System.Xml; using NUnit.Framework.Api; using NUnit.Framework.Internal.Commands; #if true #endif namespace NUnit.Framework.Internal { /// <summary> /// The TestMethod class represents a Test implemented as a method. /// Because of how exceptions are handled internally, this class /// must incorporate processing of expected exceptions. A change to /// the Test interface might make it easier to process exceptions /// in an object that aggregates a TestMethod in the future. /// </summary> public class TestMethod : Test { #region Fields /// <summary> /// The test method /// </summary> internal MethodInfo method; /// <summary> /// A list of all decorators applied to the test by attributes or parameterset arguments /// </summary> #if true private List<ICommandDecorator> decorators = new List<ICommandDecorator>(); #else private System.Collections.ArrayList decorators = new System.Collections.ArrayList(); #endif /// <summary> /// Indicated whether the method has an expected result. /// </summary> internal bool hasExpectedResult; /// <summary> /// The result that the test method is expected to return. /// </summary> internal object expectedResult; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="TestMethod"/> class. /// </summary> /// <param name="method">The method to be used as a test.</param> public TestMethod(MethodInfo method) : this(method, null) { } /// <summary> /// Initializes a new instance of the <see cref="TestMethod"/> class. /// </summary> /// <param name="method">The method to be used as a test.</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> public TestMethod(MethodInfo method, Test parentSuite) : base( method.ReflectedType ) { this.Name = method.Name; this.FullName += "." + this.Name; // Disambiguate call to base class methods // TODO: This should not be here - it's a presentation issue if( method.DeclaringType != method.ReflectedType) this.Name = method.DeclaringType.Name + "." + method.Name; // Needed to give proper fullname to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. string prefix = method.ReflectedType.FullName; if (parentSuite != null) { prefix = parentSuite.FullName; this.FullName = prefix + "." + this.Name; } this.method = method; } #endregion #region Properties /// <summary> /// Gets the method. /// </summary> /// <value>The method that performs the test.</value> public MethodInfo Method { get { return method; } } /// <summary> /// Gets a list of custom decorators for this test. /// </summary> #if true public IList<ICommandDecorator> CustomDecorators #else public System.Collections.IList CustomDecorators #endif { get { return decorators; } } #endregion #region Test Overrides /// <summary> /// Overridden to return a TestCaseResult. /// </summary> /// <returns>A TestResult for this test.</returns> public override TestResult MakeTestResult() { return new TestCaseResult(this); } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public override bool HasChildren { get { return false; } } #if !NUNITLITE && false /// <summary> /// Gets a boolean value indicating whether this /// test should run on it's own thread. /// </summary> internal override bool ShouldRunOnOwnThread { get { if (base.ShouldRunOnOwnThread) return true; int timeout = TestExecutionContext.CurrentContext.TestCaseTimeout; if (Properties.ContainsKey(PropertyNames.Timeout)) timeout = (int)Properties.Get(PropertyNames.Timeout); // TODO: Remove this kluge! else if (Parent != null && Parent.Properties.ContainsKey(PropertyNames.Timeout)) timeout = (int)Parent.Properties.Get(PropertyNames.Timeout); return timeout > 0; } } #endif /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public override XmlNode AddToXml(XmlNode parentNode, bool recursive) { XmlNode thisNode = XmlHelper.AddElement(parentNode, XmlElementName); PopulateTestNode(thisNode, recursive); return thisNode; } /// <summary> /// Gets this test's child tests /// </summary> /// <value>A list of child tests</value> #if true public override IList<ITest> Tests #else public override System.Collections.IList Tests #endif { get { return new ITest[0]; } } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public override string XmlElementName { get { return "test-case"; } } protected override TestCommand MakeTestCommand(ITestFilter filter) { TestCommand command = new TestMethodCommand(this); command = ApplyDecoratorsToCommand(command); return command; } #endregion #region Helper Methods private TestCommand ApplyDecoratorsToCommand(TestCommand command) { CommandDecoratorList decorators = new CommandDecoratorList(); // Add Standard stuff decorators.Add(new SetUpTearDownDecorator()); #if !NUNITLITE && false if (ShouldRunOnOwnThread) decorators.Add(new ThreadedTestDecorator()); #endif // Add Decorators supplied by attributes and parameter sets foreach (ICommandDecorator decorator in CustomDecorators) decorators.Add(decorator); decorators.OrderByStage(); foreach (ICommandDecorator decorator in decorators) { command = decorator.Decorate(command); } return command; } #endregion } }
using NetDimension.NanUI.Logging; using Xilium.CefGlue; namespace NetDimension.NanUI; public sealed class ChromiumEnvironmentBuilder { private string _libCefDir; private string _resourceDir; const string RESOURCE_DIR = "Resources"; const string LOCALES_DIR = "locales"; const string DEFAULT_CEF_DIR = "fx"; const string UP_LEVEL_DIR = ".."; ExternalSubprocessConfiguration _externalSubprocessConfiguration = null; CefBinaryFilePathConfiguration _cefBinaryFilePaths = null; private Action<CefCommandLine> _cefCommandLineConfigurations; private Action<CefSettings> _cefSettingConfigurations; private Action<CefBrowserSettings> _cefCefBrowserSettingConfigurations; private List<Func<PlatformArchitecture, string>> _ifLibCefNotFound = new List<Func<PlatformArchitecture, string>>(); private bool _forceHighDpiSupportDisabled; public ServiceContainer Container { get; } private readonly RuntimeBuilderContext _context; internal ChromiumEnvironmentBuilder(RuntimeBuilderContext runtimeBuilderContext) { _context = runtimeBuilderContext; Container = (ServiceContainer)_context.Properties[typeof(ServiceContainer)]; } private void AutoDetectCefBinaryPath() { DetectLibCefFilesPath(); DetectLibCefResourceFilesPath(); } private bool EnsureLibCefExists(string path) => File.Exists(Path.Combine(path, "libcef.dll")); private bool EnsureLibCefResourceDirExists(string path) => Directory.Exists(path) && Directory.GetFiles(path, "*.pak", SearchOption.TopDirectoryOnly).Length > 0 && Directory.Exists(Path.Combine(path, "locales")) && Directory.GetFiles(Path.Combine(path, "locales"), "*.pak", SearchOption.TopDirectoryOnly).Length > 0; private string CheckLibCefPath(string path) { var searchPaths = new string[] { path, Path.Combine(path, WinFormium.PlatformArchitecture.ToString()), Path.Combine(path, DEFAULT_CEF_DIR, WinFormium.PlatformArchitecture.ToString()) }; foreach (var dir in searchPaths) { if (EnsureLibCefExists(dir)) { return dir; } } return null; } private string CheckLibCefResourceFilesPath(string path) { var searchPaths = new string[] { path, Path.GetFullPath(Path.Combine(path, UP_LEVEL_DIR)), Path.GetFullPath(Path.Combine(path, UP_LEVEL_DIR, RESOURCE_DIR)), Path.Combine(path, RESOURCE_DIR) }; foreach (var dir in searchPaths) { if (EnsureLibCefResourceDirExists(dir)) { return dir; } } return null; } private void DetectLibCefFilesPath() { var args = Environment.GetCommandLineArgs(); var libCefPathArg = args?.FirstOrDefault(x => x.StartsWith("--libcef-dir-path"))?.Split('='); if (libCefPathArg != null && libCefPathArg.Length == 2 && EnsureLibCefExists(libCefPathArg[1])) { _libCefDir = libCefPathArg[1]; return; } var searchPaths = new string[] { Path.Combine(WinFormium.CommonCefRuntimeDirectory, WinFormium.PlatformArchitecture.ToString()), WinFormium.ApplicationRunningDirectory, Path.Combine(WinFormium.ApplicationRunningDirectory, WinFormium.PlatformArchitecture.ToString()), Path.Combine(WinFormium.ApplicationRunningDirectory, DEFAULT_CEF_DIR, WinFormium.PlatformArchitecture.ToString()), }; foreach (var path in searchPaths) { if (EnsureLibCefExists(path)) { _libCefDir = path; break; } } } private void DetectLibCefResourceFilesPath() { if (string.IsNullOrEmpty(_libCefDir)) return; var searchPaths = new string[] { _libCefDir, Path.GetFullPath(Path.Combine(_libCefDir, UP_LEVEL_DIR)), Path.GetFullPath(Path.Combine(_libCefDir, UP_LEVEL_DIR, RESOURCE_DIR)), Path.Combine(_libCefDir, RESOURCE_DIR) }; foreach (var path in searchPaths) { if (EnsureLibCefResourceDirExists(path)) { _resourceDir = path; break; } } } /// <summary> /// Handle the process if files of libcef are not found automatically. /// </summary> /// <param name="libCefNotFoundHanlder">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder IfLibCefNotFound(Func<PlatformArchitecture, string> libCefNotFoundHanlder) { _ifLibCefNotFound.Add(libCefNotFoundHanlder); return this; } /// <summary> /// Force the HighDpi support in CEF disabled. /// </summary> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder ForceHighDpiSupportDisabled() { _forceHighDpiSupportDisabled = true; return this; } /// <summary> /// Use a custom location of CEF binary files. /// </summary> /// <param name="useCustomCefBinaryPaths">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder UseCustomCefBinaryPath(Action<CefBinaryFilePathConfiguration> useCustomCefBinaryPaths) { if (_cefBinaryFilePaths == null) { _cefBinaryFilePaths = new CefBinaryFilePathConfiguration(); } useCustomCefBinaryPaths?.Invoke(_cefBinaryFilePaths); _libCefDir = CheckLibCefPath(_cefBinaryFilePaths.CefBinaryFileDirectory); _resourceDir = CheckLibCefResourceFilesPath(_cefBinaryFilePaths.CefBinaryFileDirectory); return this; } /// <summary> /// Use a subprocess to run CEF processes. /// </summary> /// <param name="useExternalSubprocessConfiguration">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder UseExternalSubprocess(Action<ExternalSubprocessConfiguration> useExternalSubprocessConfiguration) { if (_externalSubprocessConfiguration == null) _externalSubprocessConfiguration = new ExternalSubprocessConfiguration(); useExternalSubprocessConfiguration?.Invoke(_externalSubprocessConfiguration); return this; } /// <summary> /// Custom the CommandLine arguments of CEF. /// </summary> /// <param name="configureCefCommandLineArguments">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder CustomCefCommandLineArguments(Action<CefCommandLine> configureCefCommandLineArguments) { if (configureCefCommandLineArguments != null) { _cefCommandLineConfigurations += configureCefCommandLineArguments; } return this; } /// <summary> /// Custom the default settings of CEF. /// </summary> /// <param name="configureCefSettings">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder CustomCefSettings(Action<CefSettings> configureCefSettings) { if (configureCefSettings != null) { _cefSettingConfigurations += configureCefSettings; } return this; } /// <summary> /// Custom the default settings of CefBrowser. /// </summary> /// <param name="configureDefaultBrowserSettings">A delegate that handles the process.</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder CustomDefaultBrowserSettings(Action<CefBrowserSettings> configureDefaultBrowserSettings) { if (configureDefaultBrowserSettings != null) { _cefCefBrowserSettingConfigurations += configureDefaultBrowserSettings; } return this; } /// <summary> /// Use a logger. /// </summary> /// <typeparam name="T">ILogger</typeparam> /// <param name="logger">The instance that inherits ILogger</param> /// <returns>The ChromiumEnvironmentBuilder instance.</returns> public ChromiumEnvironmentBuilder UseLogger<T>(ILogger logger = null) where T : ILogger { if (logger == null) { logger = (T)Activator.CreateInstance(typeof(T)); } Container.RegisterInstance(logger); return this; } internal ChromiumEnvironment Build() { var env = new ChromiumEnvironment(); if (_cefBinaryFilePaths == null) { AutoDetectCefBinaryPath(); } if (string.IsNullOrEmpty(_libCefDir) || string.IsNullOrEmpty(_resourceDir)) { foreach (var handle in _ifLibCefNotFound) { var path = handle?.Invoke(WinFormium.PlatformArchitecture); _libCefDir = CheckLibCefPath(path); _resourceDir = CheckLibCefResourceFilesPath(path); if (!string.IsNullOrEmpty(_libCefDir) && !string.IsNullOrEmpty(_resourceDir)) { break; } } if (string.IsNullOrEmpty(_libCefDir) || string.IsNullOrEmpty(_resourceDir)) { throw new DirectoryNotFoundException(Resources.Messages.Runtime_CefNotFound); } } env.LibCefDir = _libCefDir; env.LibCefResourceDir = _resourceDir; env.LibCefLocaleDir = Path.Combine(_resourceDir, LOCALES_DIR); if (_externalSubprocessConfiguration != null) { if (!File.Exists(_externalSubprocessConfiguration.SubprocessPath)) { throw new FileNotFoundException($"Can't find the path {_externalSubprocessConfiguration.SubprocessPath}."); } else { env.SubprocessPath = _externalSubprocessConfiguration.SubprocessPath; } } env.CommandLineConfigurations = _cefCommandLineConfigurations; env.SettingConfigurations = _cefSettingConfigurations; env.CefBrowserSettingConfigurations = _cefCefBrowserSettingConfigurations; env.ForceHighDpiSupportDisabled = _forceHighDpiSupportDisabled; return env; } } public sealed class CefBinaryFilePathConfiguration { public PlatformArchitecture PlatformArchitecture => PlatformArchitecture; public string CurrentApplicationRunningDirectory => WinFormium.ApplicationRunningDirectory; public string CefBinaryFileDirectory { internal get; set; } } public sealed class ExternalSubprocessConfiguration { public PlatformArchitecture PlatformArchitecture => PlatformArchitecture; internal string SubprocessPath { get; private set; } public void UseCustomSubprocessPath(string subprocessPath) { if (File.Exists(subprocessPath)) { SubprocessPath = subprocessPath; return; } throw new FileNotFoundException($"Can't find the path {subprocessPath}."); } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Common; namespace Sleet { public abstract class FileSystemBase : ISleetFileSystem { /// <summary> /// URI written to files. /// </summary> public Uri BaseURI { get; private set; } /// <summary> /// Actual URI /// </summary> public Uri Root { get; private set; } public LocalCache LocalCache { get; private set; } public ConcurrentDictionary<Uri, ISleetFile> Files { get; private set; } = new ConcurrentDictionary<Uri, ISleetFile>(); public string FeedSubPath { get; protected set; } private readonly string[] _roots; protected FileSystemBase(LocalCache cache, Uri root) : this(cache, root, root) { } protected FileSystemBase(LocalCache cache, Uri root, Uri baseUri, string feedSubPath = null) { BaseURI = baseUri ?? throw new ArgumentNullException(nameof(baseUri)); LocalCache = cache ?? throw new ArgumentNullException(nameof(cache)); Root = root ?? throw new ArgumentNullException(nameof(root)); FeedSubPath = feedSubPath; BaseURI = UriUtility.EnsureTrailingSlash(BaseURI); Root = UriUtility.EnsureTrailingSlash(Root); // Ensure the longest root is first to avoid conflicts in StartsWith _roots = (new[] { BaseURI.AbsoluteUri, Root.AbsoluteUri }) .Distinct(StringComparer.Ordinal) .OrderByDescending(e => e.Length) .ThenBy(e => e, StringComparer.Ordinal) .ToArray(); } public abstract ISleetFileSystemLock CreateLock(ILogger log); public abstract ISleetFile Get(Uri path); public abstract Task<IReadOnlyList<ISleetFile>> GetFiles(ILogger log, CancellationToken token); public abstract Task<bool> Validate(ILogger log, CancellationToken token); public async Task<bool> Commit(ILogger log, CancellationToken token) { var perfTracker = LocalCache.PerfTracker; // Find all files with changes var withChanges = Files.Values.Where(e => e.HasChanges).ToList(); // Order files so that nupkgs are pushed first to help clients avoid // missing files during the push. withChanges.Sort(new SleetFileComparer()); if (withChanges.Count > 0) { var bytes = withChanges.Select(e => e as FileBase) .Where(e => e != null) .Sum(e => e.LocalFileSizeIfExists); // Create tasks to run in parallel var tasks = withChanges.Select(e => GetCommitFileFunc(e, log, token)); var message = $"Files committed: {withChanges.Count} Size: {PrintUtility.GetBytesString(bytes)} Total upload time: " + "{0}"; using (var timer = PerfEntryWrapper.CreateSummaryTimer(message, perfTracker)) { // Push in parallel await TaskUtils.RunAsync( tasks: tasks, useTaskRun: true, maxThreads: 8, token: token); } } return true; } private static Func<Task> GetCommitFileFunc(ISleetFile file, ILogger log, CancellationToken token) { return new Func<Task>(() => file.Push(log, token)); } public virtual async Task<bool> Destroy(ILogger log, CancellationToken token) { var success = true; var files = await GetFiles(log, token); foreach (var file in Files.Values) { try { log.LogInformation($"Deleting {file.EntityUri.AbsoluteUri}"); file.Delete(log, token); } catch { log.LogError($"Unable to delete {file.EntityUri.AbsoluteUri}"); success = false; } } return success; } public ISleetFile Get(string relativePath) { return Get(GetPath(relativePath)); } public Uri GetPath(string relativePath) { if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } return UriUtility.GetPath(BaseURI, relativePath); } public virtual string GetRelativePath(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var path = uri.AbsoluteUri; // The root can be either the display root (BaseURI) or the actual root. foreach (var prefix in _roots) { // This must have a trailing slash already. if (path.StartsWith(prefix, StringComparison.Ordinal)) { return path.Replace(prefix, string.Empty); } } throw new InvalidOperationException($"Unable to make '{uri.AbsoluteUri}' relative to '{BaseURI}'."); } /// <summary> /// Create a file and add it to Files /// </summary> protected ISleetFile GetOrAddFile(Uri path, bool caseSensitive, Func<SleetUriPair, ISleetFile> createFile) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var file = Files.GetOrAdd(path, (uri) => { return createFile(GetUriPair(path, caseSensitive)); }); return file; } /// <summary> /// Inspect a URI and determine the correct root and display URIs /// </summary> protected SleetUriPair GetUriPair(Uri path, bool caseSensitive) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var isRoot = UriUtility.HasRoot(Root, path, caseSensitive); var isDisplay = UriUtility.HasRoot(BaseURI, path, caseSensitive); if (!isRoot && !isDisplay) { throw new InvalidOperationException($"URI does not match the feed root or baseURI: {path.AbsoluteUri}"); } var pair = new SleetUriPair() { BaseURI = path, Root = path }; if (!isRoot) { pair.Root = UriUtility.ChangeRoot(BaseURI, Root, path); } if (!isDisplay) { pair.BaseURI = UriUtility.ChangeRoot(Root, BaseURI, path); } return pair; } /// <summary> /// Clear all tracked files /// </summary> public void Reset() { // Mark all files as invalid so that any external users will fail when trying to use them. foreach (var file in Files.Values) { file.Invalidate(); } // Clear all tracked filed Files.Clear(); } public abstract Task<bool> HasBucket(ILogger log, CancellationToken token); public abstract Task CreateBucket(ILogger log, CancellationToken token); public abstract Task DeleteBucket(ILogger log, CancellationToken token); } }
/* ** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #define lauxlib_c #define LUA_LIB using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; namespace KopiLua { using LuaNumberType = System.Double; using LuaIntegerType = System.Int32; public partial class Lua { #if LUA_COMPAT_GETN public static int LuaLGetN(LuaState L, int t); public static void LuaLSetN(LuaState L, int t, int n); #else public static int LuaLGetN(LuaState L, int i) {return (int)LuaObjectLen(L, i);} public static void LuaLSetN(LuaState L, int i, int j) {} /* no op! */ #endif #if LUA_COMPAT_OPENLIB //#define luaI_openlib luaL_openlib #endif /* extra error code for `luaL_load' */ public const int LUA_ERRFILE = (LUA_ERRERR+1); public class LuaLReg { public LuaLReg(CharPtr name, LuaNativeFunction func) { this.name = name; this.func = func; } public CharPtr name; public LuaNativeFunction func; }; /* ** =============================================================== ** some useful macros ** =============================================================== */ public static void LuaLArgCheck(LuaState L, bool cond, int numarg, string extramsg) { if (!cond) LuaLArgError(L, numarg, extramsg); } public static CharPtr LuaLCheckString(LuaState L, int n) { return LuaLCheckLString(L, n); } public static CharPtr LuaLOptString(LuaState L, int n, CharPtr d) { uint len; return LuaLOptLString(L, n, d, out len); } public static int LuaLCheckInt(LuaState L, int n) {return (int)LuaLCheckInteger(L, n);} public static int LuaLOptInt(LuaState L, int n, LuaIntegerType d) {return (int)LuaLOptInteger(L, n, d);} public static long LuaLCheckLong(LuaState L, int n) {return LuaLCheckInteger(L, n);} public static long LuaLOptLong(LuaState L, int n, LuaIntegerType d) {return LuaLOptInteger(L, n, d);} public static CharPtr LuaLTypeName(LuaState L, int i) {return LuaTypeName(L, LuaType(L,i));} //#define luaL_dofile(L, fn) \ // (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) //#define luaL_dostring(L, s) \ // (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) public static void LuaLGetMetatable(LuaState L, CharPtr n) { LuaGetField(L, LUA_REGISTRYINDEX, n); } public delegate LuaNumberType LuaLOptDelegate (LuaState L, int narg); public static LuaNumberType LuaLOpt(LuaState L, LuaLOptDelegate f, int n, LuaNumberType d) { return LuaIsNoneOrNil(L, (n != 0) ? d : f(L, n)) ? 1 : 0;} public delegate LuaIntegerType LuaLOptDelegateInteger(LuaState L, int narg); public static LuaIntegerType LuaLOptInteger(LuaState L, LuaLOptDelegateInteger f, int n, LuaNumberType d) { return (LuaIntegerType)(LuaIsNoneOrNil(L, n) ? d : f(L, (n))); } /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ public class LuaLBuffer { public int p; /* current position in buffer */ public int lvl; /* number of strings in the stack (level) */ public LuaState L; public CharPtr buffer = new char[LUAL_BUFFERSIZE]; }; public static void LuaLAddChar(LuaLBuffer B, char c) { if (B.p >= LUAL_BUFFERSIZE) LuaLPrepBuffer(B); B.buffer[B.p++] = c; } ///* compatibility only */ public static void LuaLPutChar(LuaLBuffer B, char c) {LuaLAddChar(B,c);} public static void LuaLAddSize(LuaLBuffer B, int n) {B.p += n;} /* }====================================================== */ /* compatibility with ref system */ /* pre-defined references */ public const int LUA_NOREF = (-2); public const int LUA_REFNIL = (-1); //#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ // (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) //#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) //#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) //#define luaL_reg luaL_Reg /* This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ //#define lauxlib_c //#define LUA_LIB public const int FREELIST_REF = 0; /* free list of references */ /* convert a stack index to positive */ public static int AbsIndex(LuaState L, int i) { return ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : LuaGetTop(L) + (i) + 1); } /* ** {====================================================== ** Error-report functions ** ======================================================= */ public static int LuaLArgError (LuaState L, int narg, CharPtr extramsg) { LuaDebug ar = new LuaDebug(); if (LuaGetStack(L, 0, ref ar)==0) /* no stack frame? */ return LuaLError(L, "bad argument #%d (%s)", narg, extramsg); LuaGetInfo(L, "n", ref ar); if (strcmp(ar.namewhat, "method") == 0) { narg--; /* do not count `self' */ if (narg == 0) /* error is in the self argument itself? */ return LuaLError(L, "calling " + LUA_QS + " on bad self ({1})", ar.name, extramsg); } if (ar.name == null) ar.name = "?"; return LuaLError(L, "bad argument #%d to " + LUA_QS + " (%s)", narg, ar.name, extramsg); } public static int LuaLTypeError (LuaState L, int narg, CharPtr tname) { CharPtr msg = LuaPushFString(L, "%s expected, got %s", tname, LuaLTypeName(L, narg)); return LuaLArgError(L, narg, msg); } private static void TagError (LuaState L, int narg, int tag) { LuaLTypeError(L, narg, LuaTypeName(L, tag)); } public static void LuaLWhere (LuaState L, int level) { LuaDebug ar = new LuaDebug(); if (LuaGetStack(L, level, ref ar) != 0) { /* check function at level */ LuaGetInfo(L, "Sl", ref ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ LuaPushFString(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } LuaPushLiteral(L, ""); /* else, no information available... */ } public static int LuaLError(LuaState L, CharPtr fmt, params object[] p) { LuaLWhere(L, 1); LuaPushVFString(L, fmt, p); LuaConcat(L, 2); return LuaError(L); } /* }====================================================== */ public static int LuaLCheckOption (LuaState L, int narg, CharPtr def, CharPtr [] lst) { CharPtr name = (def != null) ? LuaLOptString(L, narg, def) : LuaLCheckString(L, narg); int i; for (i=0; i<lst.Length; i++) if (strcmp(lst[i], name)==0) return i; return LuaLArgError(L, narg, LuaPushFString(L, "invalid option " + LUA_QS, name)); } public static int LuaLNewMetatable (LuaState L, CharPtr tname) { LuaGetField(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ if (!LuaIsNil(L, -1)) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ LuaPop(L, 1); LuaNewTable(L); /* create metatable */ LuaPushValue(L, -1); LuaSetField(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ return 1; } public static object LuaLCheckUData (LuaState L, int ud, CharPtr tname) { object p = LuaToUserData(L, ud); if (p != null) { /* value is a userdata? */ if (LuaGetMetatable(L, ud) != 0) { /* does it have a metatable? */ LuaGetField(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ if (LuaRawEqual(L, -1, -2) != 0) { /* does it have the correct mt? */ LuaPop(L, 2); /* remove both metatables */ return p; } } } LuaLTypeError(L, ud, tname); /* else error */ return null; /* to avoid warnings */ } public static void LuaLCheckStack (LuaState L, int space, CharPtr mes) { if (LuaCheckStack(L, space) == 0) LuaLError(L, "stack overflow (%s)", mes); } public static void LuaLCheckType (LuaState L, int narg, int t) { if (LuaType(L, narg) != t) TagError(L, narg, t); } public static void LuaLCheckAny (LuaState L, int narg) { if (LuaType(L, narg) == LUA_TNONE) LuaLArgError(L, narg, "value expected"); } public static CharPtr LuaLCheckLString(LuaState L, int narg) {uint len; return LuaLCheckLString(L, narg, out len);} [CLSCompliantAttribute(false)] public static CharPtr LuaLCheckLString (LuaState L, int narg, out uint len) { CharPtr s = LuaToLString(L, narg, out len); if (s==null) TagError(L, narg, LUA_TSTRING); return s; } public static CharPtr LuaLOptLString (LuaState L, int narg, CharPtr def) { uint len; return LuaLOptLString (L, narg, def, out len); } [CLSCompliantAttribute(false)] public static CharPtr LuaLOptLString (LuaState L, int narg, CharPtr def, out uint len) { if (LuaIsNoneOrNil(L, narg)) { len = (uint)((def != null) ? strlen(def) : 0); return def; } else return LuaLCheckLString(L, narg, out len); } public static LuaNumberType LuaLCheckNumber (LuaState L, int narg) { LuaNumberType d = LuaToNumber(L, narg); if ((d == 0) && (LuaIsNumber(L, narg)==0)) /* avoid extra test when d is not 0 */ TagError(L, narg, LUA_TNUMBER); return d; } public static LuaNumberType LuaLOptNumber (LuaState L, int narg, LuaNumberType def) { return LuaLOpt(L, LuaLCheckNumber, narg, def); } public static LuaIntegerType LuaLCheckInteger (LuaState L, int narg) { LuaIntegerType d = LuaToInteger(L, narg); if (d == 0 && LuaIsNumber(L, narg)==0) /* avoid extra test when d is not 0 */ TagError(L, narg, LUA_TNUMBER); return d; } public static LuaIntegerType LuaLOptInteger (LuaState L, int narg, LuaIntegerType def) { return LuaLOptInteger(L, LuaLCheckInteger, narg, def); } public static int LuaLGetMetafield (LuaState L, int obj, CharPtr event_) { if (LuaGetMetatable(L, obj)==0) /* no metatable? */ return 0; LuaPushString(L, event_); LuaRawGet(L, -2); if (LuaIsNil(L, -1)) { LuaPop(L, 2); /* remove metatable and metafield */ return 0; } else { LuaRemove(L, -2); /* remove only metatable */ return 1; } } public static int LuaLCallMeta (LuaState L, int obj, CharPtr event_) { obj = AbsIndex(L, obj); if (LuaLGetMetafield(L, obj, event_)==0) /* no metafield? */ return 0; LuaPushValue(L, obj); LuaCall(L, 1, 1); return 1; } public static void LuaLRegister(LuaState L, CharPtr libname, LuaLReg[] l) { LuaIOpenLib(L, libname, l, 0); } // we could just take the .Length member here, but let's try // to keep it as close to the C implementation as possible. private static int LibSize (LuaLReg[] l) { int size = 0; for (; l[size].name!=null; size++); return size; } public static void LuaIOpenLib (LuaState L, CharPtr libname, LuaLReg[] l, int nup) { if (libname!=null) { int size = LibSize(l); /* check whether lib already exists */ LuaLFindTable(L, LUA_REGISTRYINDEX, "_LOADED", 1); LuaGetField(L, -1, libname); /* get _LOADED[libname] */ if (!LuaIsTable(L, -1)) { /* not found? */ LuaPop(L, 1); /* remove previous result */ /* try global variable (and create one if it does not exist) */ if (LuaLFindTable(L, LUA_GLOBALSINDEX, libname, size) != null) LuaLError(L, "name conflict for module " + LUA_QS, libname); LuaPushValue(L, -1); LuaSetField(L, -3, libname); /* _LOADED[libname] = new table */ } LuaRemove(L, -2); /* remove _LOADED table */ LuaInsert(L, -(nup+1)); /* move library table to below upvalues */ } int reg_num = 0; for (; l[reg_num].name!=null; reg_num++) { int i; for (i=0; i<nup; i++) /* copy upvalues to the top */ LuaPushValue(L, -nup); LuaPushCClosure(L, l[reg_num].func, nup); LuaSetField(L, -(nup+2), l[reg_num].name); } LuaPop(L, nup); /* remove upvalues */ } /* ** {====================================================== ** getn-setn: size for arrays ** ======================================================= */ #if LUA_COMPAT_GETN static int checkint (LuaState L, int topop) { int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1; lua_pop(L, topop); return n; } static void getsizes (LuaState L) { lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); if (lua_isnil(L, -1)) { /* no `size' table? */ lua_pop(L, 1); /* remove nil */ lua_newtable(L); /* create it */ lua_pushvalue(L, -1); /* `size' will be its own metatable */ lua_setmetatable(L, -2); lua_pushliteral(L, "kv"); lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */ } } public static void luaL_setn (LuaState L, int t, int n) { t = abs_index(L, t); lua_pushliteral(L, "n"); lua_rawget(L, t); if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ lua_pushliteral(L, "n"); /* use it */ lua_pushinteger(L, n); lua_rawset(L, t); } else { /* use `sizes' */ getsizes(L); lua_pushvalue(L, t); lua_pushinteger(L, n); lua_rawset(L, -3); /* sizes[t] = n */ lua_pop(L, 1); /* remove `sizes' */ } } public static int luaL_getn (LuaState L, int t) { int n; t = abs_index(L, t); lua_pushliteral(L, "n"); /* try t.n */ lua_rawget(L, t); if ((n = checkint(L, 1)) >= 0) return n; getsizes(L); /* else try sizes[t] */ lua_pushvalue(L, t); lua_rawget(L, -2); if ((n = checkint(L, 2)) >= 0) return n; return (int)lua_objlen(L, t); } #endif /* }====================================================== */ public static CharPtr LuaLGSub (LuaState L, CharPtr s, CharPtr p, CharPtr r) { CharPtr wild; uint l = (uint)strlen(p); LuaLBuffer b = new LuaLBuffer(); LuaLBuffInit(L, b); while ((wild = strstr(s, p)) != null) { LuaLAddLString(b, s, (uint)(wild - s)); /* push prefix */ LuaLAddString(b, r); /* push replacement in place of pattern */ s = wild + l; /* continue after `p' */ } LuaLAddString(b, s); /* push last suffix */ LuaLPushResult(b); return LuaToString(L, -1); } public static CharPtr LuaLFindTable (LuaState L, int idx, CharPtr fname, int szhint) { CharPtr e; LuaPushValue(L, idx); do { e = strchr(fname, '.'); if (e == null) e = fname + strlen(fname); LuaPushLString(L, fname, (uint)(e - fname)); LuaRawGet(L, -2); if (LuaIsNil(L, -1)) { /* no such field? */ LuaPop(L, 1); /* remove this nil */ LuaCreateTable(L, 0, (e == '.' ? 1 : szhint)); /* new table for field */ LuaPushLString(L, fname, (uint)(e - fname)); LuaPushValue(L, -2); LuaSetTable(L, -4); /* set new table into field */ } else if (!LuaIsTable(L, -1)) { /* field has a non-table value? */ LuaPop(L, 2); /* remove table and value */ return fname; /* return problematic part of the name */ } LuaRemove(L, -2); /* remove previous table */ fname = e + 1; } while (e == '.'); return null; } /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ private static int BufferLen(LuaLBuffer B) {return B.p;} private static int BufferFree(LuaLBuffer B) {return LUAL_BUFFERSIZE - BufferLen(B);} public const int LIMIT = LUA_MINSTACK / 2; private static int EmptyBuffer (LuaLBuffer B) { uint l = (uint)BufferLen(B); if (l == 0) return 0; /* put nothing on stack */ else { LuaPushLString(B.L, B.buffer, l); B.p = 0; B.lvl++; return 1; } } private static void AdjustStack (LuaLBuffer B) { if (B.lvl > 1) { LuaState L = B.L; int toget = 1; /* number of levels to concat */ uint toplen = LuaStrLen(L, -1); do { uint l = LuaStrLen(L, -(toget+1)); if (B.lvl - toget + 1 >= LIMIT || toplen > l) { toplen += l; toget++; } else break; } while (toget < B.lvl); LuaConcat(L, toget); B.lvl = B.lvl - toget + 1; } } public static CharPtr LuaLPrepBuffer (LuaLBuffer B) { if (EmptyBuffer(B) != 0) AdjustStack(B); return new CharPtr(B.buffer, B.p); } [CLSCompliantAttribute(false)] public static void LuaLAddLString (LuaLBuffer B, CharPtr s, uint l) { while (l-- != 0) { char c = s[0]; s = s.next(); LuaLAddChar(B, c); } } public static void LuaLAddString (LuaLBuffer B, CharPtr s) { LuaLAddLString(B, s, (uint)strlen(s)); } public static void LuaLPushResult (LuaLBuffer B) { EmptyBuffer(B); LuaConcat(B.L, B.lvl); B.lvl = 1; } public static void LuaLAddValue (LuaLBuffer B) { LuaState L = B.L; uint vl; CharPtr s = LuaToLString(L, -1, out vl); if (vl <= BufferFree(B)) { /* fit into buffer? */ CharPtr dst = new CharPtr(B.buffer.chars, B.buffer.index + B.p); CharPtr src = new CharPtr(s.chars, s.index); for (uint i = 0; i < vl; i++) dst[i] = src[i]; B.p += (int)vl; LuaPop(L, 1); /* remove from stack */ } else { if (EmptyBuffer(B) != 0) LuaInsert(L, -2); /* put buffer before new value */ B.lvl++; /* add new value into B stack */ AdjustStack(B); } } public static void LuaLBuffInit (LuaState L, LuaLBuffer B) { B.L = L; B.p = /*B.buffer*/ 0; B.lvl = 0; } /* }====================================================== */ public static int LuaLRef (LuaState L, int t) { int ref_; t = AbsIndex(L, t); if (LuaIsNil(L, -1)) { LuaPop(L, 1); /* remove from stack */ return LUA_REFNIL; /* `nil' has a unique fixed reference */ } LuaRawGetI(L, t, FREELIST_REF); /* get first free element */ ref_ = (int)LuaToInteger(L, -1); /* ref = t[FREELIST_REF] */ LuaPop(L, 1); /* remove it from stack */ if (ref_ != 0) { /* any free element? */ LuaRawGetI(L, t, ref_); /* remove it from list */ LuaRawSetI(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */ } else { /* no free elements */ ref_ = (int)LuaObjectLen(L, t); ref_++; /* create new reference */ } LuaRawSetI(L, t, ref_); return ref_; } public static void LuaLUnref (LuaState L, int t, int ref_) { if (ref_ >= 0) { t = AbsIndex(L, t); LuaRawGetI(L, t, FREELIST_REF); LuaRawSetI(L, t, ref_); /* t[ref] = t[FREELIST_REF] */ LuaPushInteger(L, ref_); LuaRawSetI(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */ } } /* ** {====================================================== ** Load functions ** ======================================================= */ public class LoadF { public int extraline; public Stream f; public CharPtr buff = new char[LUAL_BUFFERSIZE]; }; [CLSCompliantAttribute(false)] public static CharPtr GetF (LuaState L, object ud, out uint size) { size = 0; LoadF lf = (LoadF)ud; //(void)L; if (lf.extraline != 0) { lf.extraline = 0; size = 1; return "\n"; } if (feof(lf.f) != 0) return null; size = (uint)fread(lf.buff, 1, lf.buff.chars.Length, lf.f); return (size > 0) ? new CharPtr(lf.buff) : null; } private static int ErrFile (LuaState L, CharPtr what, int fnameindex) { CharPtr serr = strerror(errno()); CharPtr filename = LuaToString(L, fnameindex) + 1; LuaPushFString(L, "cannot %s %s: %s", what, filename, serr); LuaRemove(L, fnameindex); return LUA_ERRFILE; } public static int LuaLLoadFile (LuaState L, CharPtr filename) { LoadF lf = new LoadF(); int status, readstatus; int c; int fnameindex = LuaGetTop(L) + 1; /* index of filename on the stack */ lf.extraline = 0; if (filename == null) { LuaPushLiteral(L, "=stdin"); lf.f = stdin; } else { LuaPushFString(L, "@%s", filename); lf.f = fopen(filename, "r"); if (lf.f == null) return ErrFile(L, "open", fnameindex); } c = getc(lf.f); if (c == '#') { /* Unix exec. file? */ lf.extraline = 1; while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ if (c == '\n') c = getc(lf.f); } if (c == LUA_SIGNATURE[0] && (filename!=null)) { /* binary file? */ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ if (lf.f == null) return ErrFile(L, "reopen", fnameindex); /* skip eventual `#!...' */ while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ; lf.extraline = 0; } ungetc(c, lf.f); status = LuaLoad(L, GetF, lf, LuaToString(L, -1)); readstatus = ferror(lf.f); if (filename != null) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus != 0) { LuaSetTop(L, fnameindex); /* ignore results from `lua_load' */ return ErrFile(L, "read", fnameindex); } LuaRemove(L, fnameindex); return status; } public class LoadS { public CharPtr s; [CLSCompliantAttribute(false)] public uint size; }; static CharPtr GetS (LuaState L, object ud, out uint size) { LoadS ls = (LoadS)ud; //(void)L; //if (ls.size == 0) return null; size = ls.size; ls.size = 0; return ls.s; } [CLSCompliantAttribute(false)] public static int LuaLLoadBuffer(LuaState L, CharPtr buff, uint size, CharPtr name) { LoadS ls = new LoadS(); ls.s = new CharPtr(buff); ls.size = size; return LuaLoad(L, GetS, ls, name); } public static int LuaLLoadString(LuaState L, CharPtr s) { return LuaLLoadBuffer(L, s, (uint)strlen(s), s); } /* }====================================================== */ private static object LuaAlloc (Type t) { return System.Activator.CreateInstance(t); } private static int Panic (LuaState L) { //(void)L; /* to avoid warnings */ fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", LuaToString(L, -1)); return 0; } public static LuaState LuaLNewState() { LuaState L = LuaNewState(LuaAlloc, null); if (L != null) LuaAtPanic(L, Panic); return L; } } }
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) using System; using System.Collections.Generic; using System.Text; using Aga.Controls.Tree; using System.IO; using System.Drawing; using System.ComponentModel; using System.Threading; namespace NodeEditor { public class TreeViewArchiveModel : ITreeModel { ///////////////////////////////////////////////// public abstract class BaseItem { private string _path = ""; public string ItemPath { get { return _path; } set { _path = value; } } private Image _icon; public Image Icon { get { return _icon; } set { _icon = value; } } private long _size = 0; public long Size { get { return _size; } set { _size = value; } } private DateTime _date; public DateTime Date { get { return _date; } set { _date = value; } } private BaseItem _parent; public BaseItem Parent { get { return _parent; } set { _parent = value; } } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { _isChecked = value; if (Owner != null) Owner.OnNodesChanged(this); } } private TreeViewArchiveModel _owner; public TreeViewArchiveModel Owner { get { return _owner; } set { _owner = value; } } public override string ToString() { return _path; } } private static Bitmap ResizeImage(Bitmap imgToResize, Size size) { // (handy utility function; thanks to http://stackoverflow.com/questions/10839358/resize-bitmap-image) try { Bitmap b = new Bitmap(size.Width, size.Height); using (Graphics g = Graphics.FromImage((Image)b)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, size.Width, size.Height); } return b; } catch { } return null; } private static Image ProcessImage(Bitmap img) { const int normalHeight = 32; return ResizeImage(img, new Size(normalHeight * img.Width / img.Height, normalHeight)); } static Image folderIcon = null; static Image shaderFileIcon = null; static Image shaderFragmentIcon = null; static Image parameterIcon = null; private static Image GetFolderIcon() { if (folderIcon == null) { folderIcon = ProcessImage(Properties.Resources.icon_triangle); } return folderIcon; } private static Image GetShaderFileIcon() { if (shaderFileIcon == null) { shaderFileIcon = ProcessImage(Properties.Resources.icon_paper); } return shaderFileIcon; } private static Image GetShaderFragmentIcon() { if (shaderFragmentIcon == null) { shaderFragmentIcon = ProcessImage(Properties.Resources.icon_circle); } return shaderFragmentIcon; } private static Image GetParameterIcon() { if (parameterIcon == null) { parameterIcon = ProcessImage(Properties.Resources.icon_hexagon); } return parameterIcon; } public class FolderItem : BaseItem { public string FunctionName { get; set; } public string Name { get { return FunctionName; } } public FolderItem(string name, BaseItem parent, TreeViewArchiveModel owner) { Icon = GetFolderIcon(); ItemPath = name; FunctionName = Path.GetFileName(name); Parent = parent; Owner = owner; } } public class ShaderFileItem : BaseItem { private string _exceptionString = ""; public string ExceptionString { get { return _exceptionString; } set { _exceptionString = value; } } public string FileName { get; set; } public string Name { get { return FileName; } } public ShaderFileItem(string name, BaseItem parent, TreeViewArchiveModel owner) { Icon = GetShaderFileIcon(); Parent = parent; ItemPath = name; FileName = Path.GetFileName(name); } } public class ShaderFragmentItem : BaseItem { public string _returnType = ""; public string ReturnType { get { return _returnType; } set { _returnType = value; } } public string _parameters = ""; public string Parameters { get { return _parameters; } set { _parameters = value; } } public string FunctionName { get; set; } public string ArchiveName { get; set; } public string Name { get { return FunctionName; } } public ShaderFragmentItem(BaseItem parent, TreeViewArchiveModel owner) { Icon = GetShaderFragmentIcon(); Parent = parent; Owner = owner; } } public class ParameterStructItem : BaseItem { public string _parameters = ""; public string Parameters { get { return _parameters; } set { _parameters = value; } } public string StructName { get; set; } public string ArchiveName { get; set; } public string Name { get { return StructName; } } public ParameterStructItem(BaseItem parent, TreeViewArchiveModel owner) { Icon = GetParameterIcon(); Parent = parent; Owner = owner; } } ///////////////////////////////////////////////// private BackgroundWorker _worker; private List<BaseItem> _itemsToRead; private Dictionary<string, List<BaseItem>> _cache = new Dictionary<string, List<BaseItem>>(); public TreeViewArchiveModel() { _itemsToRead = new List<BaseItem>(); _worker = new BackgroundWorker(); _worker.WorkerReportsProgress = true; _worker.DoWork += new DoWorkEventHandler(ReadFilesProperties); // _worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged); (this causes bugs when expanding items) } void ReadFilesProperties(object sender, DoWorkEventArgs e) { while(_itemsToRead.Count > 0) { BaseItem item = _itemsToRead[0]; _itemsToRead.RemoveAt(0); if (item is FolderItem) { DirectoryInfo info = new DirectoryInfo(item.ItemPath); item.Date = info.CreationTime; } else if (item is ShaderFileItem) { FileInfo info = new FileInfo(item.ItemPath); item.Size = info.Length; item.Date = info.CreationTime; // We open the file and create children for functions in // the GetChildren function } /*else if (item is ParameterItem) { FileInfo info = new FileInfo(item.ItemPath); item.Size = info.Length; item.Date = info.CreationTime; var parameter = ShaderFragmentArchive.Archive.GetParameter(item.ItemPath); ParameterItem sfi = (ParameterItem)item; sfi.FileName = Path.GetFileNameWithoutExtension(item.ItemPath); sfi.FunctionName = parameter.Name; sfi.ReturnType = parameter.Type; sfi.ExceptionString = parameter.ExceptionString; }*/ _worker.ReportProgress(0, item); } } void ProgressChanged(object sender, ProgressChangedEventArgs e) { OnNodesChanged(e.UserState as BaseItem); } private TreePath GetPath(BaseItem item) { if (item == null) return TreePath.Empty; else { Stack<object> stack = new Stack<object>(); return new TreePath(stack.ToArray()); } } public System.Collections.IEnumerable GetChildren(TreePath treePath) { const string FragmentArchiveDirectoryRoot = "game/xleres/"; string basePath = null; BaseItem parent = null; List<BaseItem> items = null; if (treePath.IsEmpty()) { if (_cache.ContainsKey("ROOT")) items = _cache["ROOT"]; else { basePath = FragmentArchiveDirectoryRoot; } } else { parent = treePath.LastNode as BaseItem; if (parent != null) { basePath = parent.ItemPath; } } if (basePath!=null) { if (_cache.ContainsKey(basePath)) items = _cache[basePath]; else { items = new List<BaseItem>(); var fileAttributes = File.GetAttributes(basePath); if ((fileAttributes & FileAttributes.Directory) == FileAttributes.Directory) { // It's a directory... // Try to find the files within and create child nodes try { foreach (string str in Directory.GetDirectories(basePath)) items.Add(new FolderItem(str, parent, this)); foreach (string str in Directory.GetFiles(basePath)) { var extension = Path.GetExtension(str); if (extension.Equals(".shader", StringComparison.CurrentCultureIgnoreCase) || extension.Equals(".h", StringComparison.CurrentCultureIgnoreCase) || extension.Equals(".vsh", StringComparison.CurrentCultureIgnoreCase) || extension.Equals(".psh", StringComparison.CurrentCultureIgnoreCase) || extension.Equals(".gsh", StringComparison.CurrentCultureIgnoreCase) || extension.Equals(".sh", StringComparison.CurrentCultureIgnoreCase) ) { var sfi = new ShaderFileItem(str, parent, this); sfi.FileName = Path.GetFileName(str); items.Add(sfi); } /*else if (extension.Equals(".param", StringComparison.CurrentCultureIgnoreCase)) { items.Add(new ParameterItem(str, parent, this)); }*/ } } catch (IOException) { return null; } } else { // It's a file. Let's try to parse it as a shader file and get the information within var fragment = ShaderFragmentArchive.Archive.GetFragment(basePath); ShaderFileItem sfi = (ShaderFileItem)parent; sfi.ExceptionString = fragment.ExceptionString; foreach (var f in fragment.Functions) { ShaderFragmentItem fragItem = new ShaderFragmentItem(parent, this); fragItem.FunctionName = f.Name; if (f.Outputs.Count!=0) fragItem.ReturnType = f.Outputs[0].Type; fragItem.Parameters = f.BuildParametersString(); fragItem.ArchiveName = basePath + ":" + f.Name; items.Add(fragItem); } foreach (var p in fragment.ParameterStructs) { ParameterStructItem paramItem = new ParameterStructItem(parent, this); paramItem.StructName = p.Name; paramItem.Parameters = p.BuildBodyString(); paramItem.ArchiveName = basePath + ":" + p.Name; items.Add(paramItem); } fragment.ChangeEvent += new ShaderFragmentArchive.ChangeEventHandler(OnStructureChanged); } _cache.Add(basePath, items); _itemsToRead.AddRange(items); if (!_worker.IsBusy) _worker.RunWorkerAsync(); } } return items; } public bool IsLeaf(TreePath treePath) { return treePath.LastNode is ShaderFragmentItem || treePath.LastNode is ParameterStructItem; } public event EventHandler<TreeModelEventArgs> NodesChanged; internal void OnNodesChanged(BaseItem item) { if (NodesChanged != null) { TreePath path = GetPath(item.Parent); NodesChanged(this, new TreeModelEventArgs(path, new object[] { item })); } } public event EventHandler<TreeModelEventArgs> NodesInserted; public event EventHandler<TreeModelEventArgs> NodesRemoved; public event EventHandler<TreePathEventArgs> StructureChanged; public void OnStructureChanged(Object sender) { _cache = new Dictionary<string, List<BaseItem>>(); if (StructureChanged != null) StructureChanged(this, new TreePathEventArgs()); } } }
/*************************************************************************** * Feed.cs * * Copyright (C) 2007 Michael C. Urbanski * Written by Mike Urbanski <michael.c.urbanski@gmail.com> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Generic; using Mono.Unix; using Hyena.Data.Sqlite; namespace Migo.Syndication { public enum FeedAutoDownload : int { All = 0, One = 1, None = 2 } // TODO remove this, way too redundant with DownloadStatus public enum PodcastFeedActivity : int { Updating = 0, UpdatePending = 1, UpdateFailed = 2, ItemsDownloading = 4, ItemsQueued = 5, None = 6 } public class FeedProvider : CacheableSqliteModelProvider<Feed> { public FeedProvider (HyenaSqliteConnection connection) : base (connection, "PodcastSyndications") { } protected override void CreateTable () { base.CreateTable (); CreateIndex ("PodcastSyndicationsIndex", "IsSubscribed, Title"); } protected override int ModelVersion { get { return 4; } } protected override void MigrateTable (int old_version) { CheckTable (); if (old_version < 2) { Connection.Execute (String.Format ("UPDATE {0} SET IsSubscribed=1", TableName)); } if (old_version < 3) { CreateIndex ("PodcastSyndicationsIndex", "IsSubscribed, Title"); } if (old_version < 4) { Connection.Execute (String.Format ("UPDATE {0} SET MaxItemCount=0 WHERE MaxItemCount=200", TableName)); } } } public class Feed : CacheableItem<Feed> { private static FeedProvider provider; public static FeedProvider Provider { get { return provider; } } public static void Init () { provider = new FeedProvider (FeedsManager.Instance.Connection); } public static bool Exists (string url) { return Provider.Connection.Query<int> (String.Format ("select count(*) from {0} where url = ?", Provider.TableName), url) != 0; } //private bool canceled; //private bool deleted; //private bool updating; //private ManualResetEvent updatingHandle = new ManualResetEvent (true); private readonly object sync = new object (); private string copyright; private string description; private string image_url; private int update_period_minutes = 24 * 60; private string language; private DateTime last_build_date = DateTime.MinValue; private FeedDownloadError lastDownloadError; private DateTime last_download_time = DateTime.MinValue; private string link; //private string local_enclosure_path; private long dbid = -1; private long maxItemCount = 0; private DateTime pubDate; private FeedSyncSetting syncSetting; private string title; private string url; private string keywords, category; #region Database-bound Properties [DatabaseColumn ("FeedID", Constraints = DatabaseColumnConstraints.PrimaryKey)] public override long DbId { get { return dbid; } protected set { dbid = value; } } public static string UnknownPodcastTitle = Catalog.GetString ("Unknown Podcast"); [DatabaseColumn] public string Title { get { return title ?? UnknownPodcastTitle; } set { title = value; } } [DatabaseColumn] public string Description { get { return description; } set { description = value; } } [DatabaseColumn] public string Url { get { return url; } set { url = value; } } [DatabaseColumn] public string Keywords { get { return keywords; } set { keywords = value; } } [DatabaseColumn] public string Category { get { return category; } set { category = value; } } [DatabaseColumn] public string Copyright { get { return copyright; } set { copyright = value; } } [DatabaseColumn] public string ImageUrl { get { return image_url; } set { image_url = value; } } [DatabaseColumn] public int UpdatePeriodMinutes { get { return update_period_minutes; } set { update_period_minutes = value; } } [DatabaseColumn] public string Language { get { return language; } set { language = value; } } [DatabaseColumn] public FeedDownloadError LastDownloadError { get { return lastDownloadError; } set { lastDownloadError = value; } } [DatabaseColumn] public DateTime LastDownloadTime { get { return last_download_time; } set { last_download_time = value; } } [DatabaseColumn] public string Link { get { return link; } set { link = value; } } //[DatabaseColumn] public string LocalEnclosurePath { get { string escaped = Hyena.StringUtil.EscapeFilename (Title); return Path.Combine (FeedsManager.Instance.PodcastStorageDirectory, escaped); } //set { local_enclosure_path = value; } } [DatabaseColumn] public long MaxItemCount { get { return maxItemCount; } set { maxItemCount = value; } } [DatabaseColumn] public DateTime PubDate { get { return pubDate; } set { pubDate = value; } } [DatabaseColumn] public DateTime LastBuildDate { get { return last_build_date; } set { last_build_date = value; } } /*private DateTime last_downloaded; [DatabaseColumn] public DateTime LastDownloaded { get { return last_downloaded; } set { last_downloaded = value; } }*/ [DatabaseColumn] public FeedSyncSetting SyncSetting { get { return syncSetting; } set { syncSetting = value; } } [DatabaseColumn] protected DateTime last_auto_download = DateTime.MinValue; public DateTime LastAutoDownload { get { return last_auto_download; } set { last_auto_download = value; } } [DatabaseColumn("AutoDownload")] protected FeedAutoDownload auto_download = FeedAutoDownload.None; public FeedAutoDownload AutoDownload { get { return auto_download; } set { if (value == auto_download) return; auto_download = value; CheckForItemsToDownload (); } } [DatabaseColumn("DownloadStatus")] private FeedDownloadStatus download_status; public FeedDownloadStatus DownloadStatus { get { return download_status; } set { download_status = value; } } [DatabaseColumn("IsSubscribed")] private bool is_subscribed; public bool IsSubscribed { get { return is_subscribed; } set { is_subscribed = value; } } #endregion #region Other Properties // TODO remove this, way too redundant with DownloadStatus /*public PodcastFeedActivity Activity { get { return activity; } PodcastFeedActivity ret = PodcastFeedActivity.None; if (this == All) { return ret; } switch (DownloadStatus) { case FeedDownloadStatus.Pending: ret = PodcastFeedActivity.UpdatePending; break; case FeedDownloadStatus.Downloading: ret = PodcastFeedActivity.Updating; break; case FeedDownloadStatus.DownloadFailed: ret = PodcastFeedActivity.UpdateFailed; break; } if (ret != PodcastFeedActivity.Updating) { if (ActiveDownloadCount > 0) { ret = PodcastFeedActivity.ItemsDownloading; } else if (QueuedDownloadCount > 0) { ret = PodcastFeedActivity.ItemsQueued; } } return ret; } }*/ public IEnumerable<FeedItem> Items { get { if (DbId > 0) { foreach (FeedItem item in FeedItem.Provider.FetchAllMatching (String.Format ("{0}.FeedID = {1} ORDER BY {0}.PubDate DESC", FeedItem.Provider.TableName, DbId))) { yield return item; } } } } #endregion private static FeedManager Manager { get { return FeedsManager.Instance.FeedManager; } } #region Constructors public Feed (string url, FeedAutoDownload auto_download) : this () { Url = url; this.auto_download = auto_download; } public Feed () { } #endregion #region Internal Methods // Removing a FeedItem means removing the downloaded file. /*public void Remove (FeedItem item) { if (item == null) { throw new ArgumentNullException ("item"); } if (items.Remove (item)) { inactive_items.Add (item); OnFeedItemRemoved (item); } } }*/ /*public void Remove (IEnumerable<FeedItem> itms) { if (removedItems.Count > 0) { OnItemsChanged (); } } }*/ #endregion #region Private Methods public void SetItems (IEnumerable<FeedItem> items) { bool added_any = false; foreach (FeedItem item in items) { added_any |= AddItem (item); } if (added_any) { CheckForItemsToArchive (); Manager.OnFeedsChanged (); CheckForItemsToDownload (); } } private bool AddItem (FeedItem item) { try { if (!FeedItem.Exists (this.DbId, item.Guid)) { item.Feed = this; item.Save (); return true; } } catch (Exception e) { Hyena.Log.Error (e); } return false; } /*private void UpdateItems (IEnumerable<FeedItem> new_items) { ICollection<FeedItem> tmpNew = null; List<FeedItem> zombies = new List<FeedItem> (); if (items.Count == 0 && inactive_items.Count == 0) { tmpNew = new List<FeedItem> (new_items); } else { // Get remote items that aren't in the items list tmpNew = Diff (items, new_items); // Of those, remove the ones that are in our inactive list tmpNew = Diff (inactive_items, tmpNew); // Get a list of inactive items that aren't in the remote list any longer ICollection<FeedItem> doubleKilledZombies = Diff ( new_items, inactive_items ); foreach (FeedItem zombie in doubleKilledZombies) { inactive_items.Remove (zombie); } zombies.AddRange (doubleKilledZombies); foreach (FeedItem fi in Diff (new_items, items)) { if (fi.Enclosure != null && !String.IsNullOrEmpty (fi.Enclosure.LocalPath)) { // A hack for the podcast plugin, keeps downloaded items // from being deleted when they are no longer in the feed. continue; } zombies.Add (fi); } } if (tmpNew.Count > 0) { Add (tmpNew); } // TODO merge...should we really be deleting these items? if (zombies.Count > 0) { foreach (FeedItem item in zombies) { if (item.Active) { zombie.Delete (); } } // TODO merge //ItemsTableManager.Delete (zombies); } } // Written before LINQ, will update. private ICollection<FeedItem> Diff (IEnumerable<FeedItem> baseSet, IEnumerable<FeedItem> overlay) { bool found; List<FeedItem> diff = new List<FeedItem> (); foreach (FeedItem opi in overlay) { found = false; foreach (FeedItem bpi in baseSet) { if (opi.Title == bpi.Title && opi.Description == bpi.Description) { found = true; break; } } if (!found) { diff.Add (opi); } } return diff; }*/ #endregion #region Public Methods public void Update () { Manager.QueueUpdate (this); } public void Delete () { Delete (true); Manager.OnFeedsChanged (); } public void Delete (bool deleteEnclosures) { lock (sync) { //if (deleted) // return; //if (updating) { // Manager.CancelUpdate (this); //} foreach (FeedItem item in Items) { item.Delete (deleteEnclosures); } Provider.Delete (this); } //updatingHandle.WaitOne (); Manager.OnFeedsChanged (); } public void MarkAllItemsRead () { lock (sync) { foreach (FeedItem i in Items) { i.IsRead = true; } } } public override string ToString () { return String.Format ("Title: {0} - Url: {1}", Title, Url); } public void Save () { Save (true); } public void Save (bool notify) { Save (notify, true); } public void Save (bool notify, bool download_items) { Provider.Save (this); CheckForItemsToArchive (); if (download_items && (LastBuildDate > LastAutoDownload)) { CheckForItemsToDownload (); } if (notify) { Manager.OnFeedsChanged (); } } private void CheckForItemsToArchive () { if (MaxItemCount == 0) return; int i = 0; foreach (var item in Items) { if (!item.IsRead) { if (i++ >= MaxItemCount) { item.IsRead = true; item.Save (false); } } } } private void CheckForItemsToDownload () { if (LastDownloadError != FeedDownloadError.None || AutoDownload == FeedAutoDownload.None) return; bool only_first = (AutoDownload == FeedAutoDownload.One); bool any = false; foreach (FeedItem item in Items) { if (item.Enclosure != null && item.Active && item.Enclosure.DownloadStatus != FeedDownloadStatus.Downloaded && item.PubDate > LastAutoDownload) { item.Enclosure.AsyncDownload (); any = true; if (only_first) break; } } if (any) { LastAutoDownload = DateTime.Now; // We don't want Save to call CheckForItemsToDownload again Save (true, false); } } /*private bool SetCanceled () { bool ret = false; if (!canceled && updating) { ret = canceled = true; } return ret; }*/ #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; namespace System { public class RandomDataGenerator { private Random _rand = new Random(); private int? _seed = null; public int? Seed { get { return _seed; } set { if (!_seed.HasValue && value.HasValue) { _seed = value; _rand = new Random(value.Value); } } } // returns a byte array of random data public void GetBytes(int newSeed, byte[] buffer) { Seed = newSeed; GetBytes(buffer); } public void GetBytes(byte[] buffer) { _rand.NextBytes(buffer); } // returns a non-negative Int64 between 0 and Int64.MaxValue public long GetInt64(int newSeed) { Seed = newSeed; return GetInt64(); } public long GetInt64() { byte[] buffer = new byte[8]; GetBytes(buffer); long result = BitConverter.ToInt64(buffer, 0); return result != long.MinValue ? Math.Abs(result) : long.MaxValue; } // returns a non-negative Int32 between 0 and Int32.MaxValue public int GetInt32(int new_seed) { Seed = new_seed; return GetInt32(); } public int GetInt32() { return _rand.Next(); } // returns a non-negative Int16 between 0 and Int16.MaxValue public short GetInt16(int new_seed) { Seed = new_seed; return GetInt16(); } public short GetInt16() { return (short)_rand.Next(1 + short.MaxValue); } // returns a non-negative Byte between 0 and Byte.MaxValue public byte GetByte(int new_seed) { Seed = new_seed; return GetByte(); } public byte GetByte() { return (byte)_rand.Next(1 + byte.MaxValue); } // returns a non-negative Double between 0.0 and 1.0 public double GetDouble(int new_seed) { Seed = new_seed; return GetDouble(); } public double GetDouble() { return _rand.NextDouble(); } // returns a non-negative Single between 0.0 and 1.0 public float GetSingle(int newSeed) { Seed = newSeed; return GetSingle(); } public float GetSingle() { return (float)_rand.NextDouble(); } // returns a valid char that is a letter public char GetCharLetter(int newSeed) { Seed = newSeed; return GetCharLetter(); } public char GetCharLetter() { return GetCharLetter(allowSurrogate: true); } // returns a valid char that is a letter // if allowsurrogate is true then surrogates are valid return values public char GetCharLetter(int newSeed, bool allowSurrogate) { Seed = newSeed; return GetCharLetter(allowSurrogate); } public char GetCharLetter(bool allowSurrogate) { return GetCharLetter(allowSurrogate, allowNoWeight: true); } // returns a valid char that is a letter // if allowsurrogate is true then surrogates are valid return values // if allownoweight is true, then no-weight characters are valid return values public char GetCharLetter(int newSeed, bool allowSurrogate, bool allowNoWeight) { Seed = newSeed; return GetCharLetter(allowSurrogate, allowNoWeight); } public char GetCharLetter(bool allowSurrogate, bool allowNoWeight) { short iVal; char c = 'a'; int counter; bool loopCondition = true; // attempt to randomly find a letter counter = 100; do { counter--; iVal = GetInt16(); if (false == allowNoWeight) { throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = allowSurrogate ? (!char.IsLetter(c)) : (!char.IsLetter(c) || char.IsSurrogate(c)); } while (loopCondition && 0 < counter); if (!char.IsLetter(c)) { // we tried and failed to get a letter // Grab an ASCII letter c = Convert.ToChar(GetInt16() % 26 + 'A'); } return c; } // returns a valid char that is a number public char GetCharNumber(int newSeed) { Seed = newSeed; return GetCharNumber(); } public char GetCharNumber() { return GetCharNumber(true); } // returns a valid char that is a number // if allownoweight is true, then no-weight characters are valid return values public char GetCharNumber(int newSeed, bool allowNoWeight) { Seed = newSeed; return GetCharNumber(allowNoWeight); } public char GetCharNumber(bool allowNoWeight) { char c = '0'; int counter; short iVal; bool loopCondition = true; // attempt to randomly find a number counter = 100; do { counter--; iVal = GetInt16(); if (false == allowNoWeight) { throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = !char.IsNumber(c); } while (loopCondition && 0 < counter); if (!char.IsNumber(c)) { // we tried and failed to get a letter // Grab an ASCII number c = Convert.ToChar(GetInt16() % 10 + '0'); } return c; } // returns a valid char public char GetChar(int newSeed) { Seed = newSeed; return GetChar(); } public char GetChar() { return GetChar(allowSurrogate: true); } // returns a valid char // if allowsurrogate is true then surrogates are valid return values public char GetChar(int newSeed, bool allowSurrogate) { Seed = newSeed; return GetChar(allowSurrogate); } public char GetChar(bool allowSurrogate) { return GetChar(allowSurrogate, allowNoWeight: true); } // returns a valid char // if allowsurrogate is true then surrogates are valid return values // if allownoweight characters then noweight characters are valid return values public char GetChar(int newSeed, bool allowSurrogate, bool allowNoWeight) { Seed = newSeed; return GetChar(allowSurrogate, allowNoWeight); } public char GetChar(bool allowSurrogate, bool allowNoWeight) { short iVal = GetInt16(); char c = (char)(iVal); if (!char.IsLetter(c)) { // we tried and failed to get a letter // Just grab an ASCII letter c = (char)(GetInt16() % 26 + 'A'); } return c; } // returns a string. If "validPath" is set, only valid path characters // will be included public string GetString(int newSeed, bool validPath, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, minLength, maxLength); } public string GetString(bool validPath, int minLength, int maxLength) { return GetString(validPath, true, true, minLength, maxLength); } public string GetString(int newSeed, bool validPath, bool allowNulls, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, allowNulls, minLength, maxLength); } public string GetString(bool validPath, bool allowNulls, int minLength, int maxLength) { return GetString(validPath, allowNulls, true, minLength, maxLength); } public string GetString(int newSeed, bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength); } public string GetString(bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength) { StringBuilder sVal = new StringBuilder(); char c; int length; if (0 == minLength && 0 == maxLength) return String.Empty; if (minLength > maxLength) return null; length = minLength; if (minLength != maxLength) { length = (GetInt32() % (maxLength - minLength)) + minLength; } for (int i = 0; length > i; i++) { if (validPath) { if (0 == (GetByte() % 2)) { c = GetCharLetter(true, allowNoWeight); } else { c = GetCharNumber(allowNoWeight); } } else if (!allowNulls) { do { c = GetChar(true, allowNoWeight); } while (c == '\u0000'); } else { c = GetChar(true, allowNoWeight); } sVal.Append(c); } string s = sVal.ToString(); return s; } public string[] GetStrings(int newSeed, bool validPath, int minLength, int maxLength) { Seed = newSeed; return GetStrings(validPath, minLength, maxLength); } public string[] GetStrings(bool validPath, int minLength, int maxLength) { string validString; const char c_LATIN_A = '\u0100'; const char c_LOWER_A = 'a'; const char c_UPPER_A = 'A'; const char c_ZERO_WEIGHT = '\uFEFF'; const char c_DOUBLE_WIDE_A = '\uFF21'; const string c_SURROGATE_UPPER = "\uD801\uDC00"; const string c_SURROGATE_LOWER = "\uD801\uDC28"; const char c_LOWER_SIGMA1 = (char)0x03C2; const char c_LOWER_SIGMA2 = (char)0x03C3; const char c_UPPER_SIGMA = (char)0x03A3; const char c_SPACE = ' '; if (2 >= minLength && 2 >= maxLength || minLength > maxLength) return null; validString = GetString(validPath, minLength - 1, maxLength - 1); string[] retStrings = new string[12]; retStrings[0] = GetString(validPath, minLength, maxLength); retStrings[1] = validString + c_LATIN_A; retStrings[2] = validString + c_LOWER_A; retStrings[3] = validString + c_UPPER_A; retStrings[4] = validString + c_ZERO_WEIGHT; retStrings[5] = validString + c_DOUBLE_WIDE_A; retStrings[6] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER; retStrings[7] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER; retStrings[8] = validString + c_LOWER_SIGMA1; retStrings[9] = validString + c_LOWER_SIGMA2; retStrings[10] = validString + c_UPPER_SIGMA; retStrings[11] = validString + c_SPACE; return retStrings; } public static void VerifyRandomDistribution(byte[] random) { // Better tests for randomness are available. For now just use a simple // check that compares the number of 0s and 1s in the bits. VerifyNeutralParity(random); } private static void VerifyNeutralParity(byte[] random) { int zeroCount = 0, oneCount = 0; for (int i = 0; i < random.Length; i++) { for (int j = 0; j < 8; j++) { if (((random[i] >> j) & 1) == 1) { oneCount++; } else { zeroCount++; } } } // Over the long run there should be about as many 1s as 0s. // This isn't a guarantee, just a statistical observation. // Allow a 7% tolerance band before considering it to have gotten out of hand. double bitDifference = Math.Abs(zeroCount - oneCount) / (double)(zeroCount + oneCount); const double AllowedTolerance = 0.07; if (bitDifference > AllowedTolerance) { throw new InvalidOperationException("Expected bitDifference < " + AllowedTolerance + ", got " + bitDifference + "."); } } } }
#nullable enable using Serilog.Core; using Serilog.Core.Pipeline; using Serilog.Events; using Serilog.Tests.Support; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Xunit; using Xunit.Sdk; #if FEATURE_DEFAULT_INTERFACE using System.Reflection.Emit; // ReSharper disable PossibleNullReferenceException #endif // ReSharper disable PossibleMultipleEnumeration // ReSharper disable UnusedMember.Local // ReSharper disable UnusedParameter.Local // ReSharper disable AssignNullToNotNullAttribute namespace Serilog.Tests { /// <summary> /// The goal of these tests is to test API conformance, /// against classes that implement the ILogger interface /// </summary> [Collection("Log.Logger")] public class MethodOverloadConventionTests { const string Write = "Write"; //this is used as both the variable name for message template parameter // and as the argument for the MessageTemplateFormatMethodAttr const string MessageTemplate = "messageTemplate"; #if FEATURE_DEFAULT_INTERFACE public static IEnumerable<object[]> DefaultInterfaceMethods => typeof(ILogger).GetMethods() .Where(mi => mi.GetMethodBody() != null) .Where(mi => mi.GetCustomAttribute(typeof(CustomDefaultMethodImplementationAttribute)) == null) .Where(mi => typeof(Logger).GetInterfaceMap(typeof(ILogger)).InterfaceMethods.Contains(mi)) .Select(mi => new object[] { mi }); [Theory] [MemberData(nameof(DefaultInterfaceMethods))] public void ILoggerDefaultMethodsShouldBeInSyncWithLogger(MethodInfo defaultInterfaceMethod) { var imap = typeof(Logger).GetInterfaceMap(typeof(ILogger)); var loggerMatchingMethod = imap.TargetMethods[Array.IndexOf(imap.InterfaceMethods, defaultInterfaceMethod)]; Assert.True(MethodBodyEqual(defaultInterfaceMethod, loggerMatchingMethod)); // checking binary IL equality of two method bodies, excluding Nops at the start // and up to the call/callvirt differences, that is // Serilog.Core.Logger.ForContext<T>(): call instance class Serilog.ILogger Serilog.Core.Logger::ForContext(class [netstandard]System.Type) // ILogger.ForContext<T>(): callvirt instance class Serilog.ILogger Serilog.ILogger::ForContext(class [netstandard]System.Type) // calls with the same type arguments, name and parameters are considered equal static bool MethodBodyEqual(MethodBase ifaceMethod, MethodBase classMethod) { // ReSharper disable once VariableHidesOuterVariable var imap = typeof(Logger).GetInterfaceMap(typeof(ILogger)); var opCodesMap = new[] { (OpCodes.Call, OpCodes.Call), (OpCodes.Callvirt, OpCodes.Call), (OpCodes.Callvirt, OpCodes.Callvirt), (OpCodes.Ldsfld, OpCodes.Ldsfld) }.ToLookup(x => x.Item1.Value, el => el.Item2.Value); var ifaceBytes = ifaceMethod.GetMethodBody()!.GetILAsByteArray().AsSpan(); var classBytes = classMethod.GetMethodBody()!.GetILAsByteArray().AsSpan(); while (ifaceBytes[0] == OpCodes.Nop.Value) { ifaceBytes = ifaceBytes.Slice(1); } while (classBytes[0] == OpCodes.Nop.Value) { classBytes = classBytes.Slice(1); } if (ifaceBytes.Length != classBytes.Length) { return false; } for (var i = 0; i < ifaceBytes.Length; ++i) { var l = ifaceBytes[i]; var r = classBytes[i]; var allowedOpCodes = opCodesMap[l]; if (!allowedOpCodes.Any()) { continue; } if (!allowedOpCodes.Contains(r)) { return false; } var ifaceMetaToken = BitConverter.ToInt32(ifaceBytes.Slice(i + 1, 4)); var classMetaToken = BitConverter.ToInt32(classBytes.Slice(i + 1, 4)); var ifaceMember = ifaceMethod.Module.ResolveMember(ifaceMetaToken, null, ifaceMethod.GetGenericArguments()); var classMember = classMethod.Module.ResolveMember(classMetaToken, null, classMethod.GetGenericArguments()); if (l == OpCodes.Call.Value || l == OpCodes.Callvirt.Value) { var ifaceMethodDef = ifaceMember is MethodInfo mi ? mi.IsGenericMethod ? mi.GetGenericMethodDefinition() : mi : null; var classMethodDef = classMember is MethodInfo mc ? mc.IsGenericMethod ? mc.GetGenericMethodDefinition() : mc : null; if (ifaceMethodDef == classMethodDef) { continue; } var mappedClassMethodDef = imap.TargetMethods[Array.IndexOf(imap.InterfaceMethods, ifaceMethodDef)]; if (mappedClassMethodDef != classMethodDef) { return false; } } // special handling for accessing static fields (e.g. NoPropertyValues) if (l == OpCodes.Ldsfld.Value) { var ifaceField = (ifaceMember as FieldInfo)?.GetValue(null); var classField = (classMember as FieldInfo)?.GetValue(null); if (ifaceField is object[] io && classField is object[] co) { if (!io.SequenceEqual(co)) { return false; } } else { if (!Equals(ifaceField, classField)) { return false; } } } i += 4; } return true; } } #endif [Theory] [InlineData(Write)] [InlineData(nameof(LogEventLevel.Verbose))] [InlineData(nameof(LogEventLevel.Debug))] [InlineData(nameof(LogEventLevel.Information))] [InlineData(nameof(LogEventLevel.Warning))] [InlineData(nameof(LogEventLevel.Error))] [InlineData(nameof(LogEventLevel.Fatal))] public void ILoggerValidateConventions(string setName) { ValidateConventionForMethodSet(setName, typeof(ILogger)); } [Theory] [InlineData(Write)] [InlineData(nameof(LogEventLevel.Verbose))] [InlineData(nameof(LogEventLevel.Debug))] [InlineData(nameof(LogEventLevel.Information))] [InlineData(nameof(LogEventLevel.Warning))] [InlineData(nameof(LogEventLevel.Error))] [InlineData(nameof(LogEventLevel.Fatal))] public void LoggerValidateConventions(string setName) { ValidateConventionForMethodSet(setName, typeof(Logger)); } [Theory] [InlineData(Write)] [InlineData(nameof(LogEventLevel.Verbose))] [InlineData(nameof(LogEventLevel.Debug))] [InlineData(nameof(LogEventLevel.Information))] [InlineData(nameof(LogEventLevel.Warning))] [InlineData(nameof(LogEventLevel.Error))] [InlineData(nameof(LogEventLevel.Fatal))] public void LogValidateConventions(string setName) { ValidateConventionForMethodSet(setName, typeof(Log)); } [Theory] [InlineData(Write)] [InlineData(nameof(LogEventLevel.Verbose))] [InlineData(nameof(LogEventLevel.Debug))] [InlineData(nameof(LogEventLevel.Information))] [InlineData(nameof(LogEventLevel.Warning))] [InlineData(nameof(LogEventLevel.Error))] [InlineData(nameof(LogEventLevel.Fatal))] public void SilentLoggerValidateConventions(string setName) { ValidateConventionForMethodSet(setName, typeof(SilentLogger), checkMesgTempAttr: false, testInvokeResults: false); } [Theory] [InlineData(typeof(SilentLogger))] [InlineData(typeof(Logger))] [InlineData(typeof(Log))] [InlineData(typeof(ILogger))] public void ValidateWriteEventLogMethods(Type loggerType) { var methods = loggerType.GetMethods() .Where(method => method.Name == Write && method.GetParameters() .Any(param => param.ParameterType == typeof(LogEvent))); Assert.Single(methods); var writeMethod = methods.Single(); Assert.True(writeMethod.IsPublic); Assert.Equal(typeof(void), writeMethod.ReturnType); var level = LogEventLevel.Information; var logger = GetLogger(loggerType, out var sink); InvokeMethod(writeMethod, logger, new object[] { Some.LogEvent(DateTimeOffset.Now, level) }); //handle silent logger special case i.e. no result validation if (loggerType == typeof(SilentLogger)) return; EvaluateSingleResult(level, sink); } [Theory] [InlineData(typeof(SilentLogger))] [InlineData(typeof(Logger))] [InlineData(typeof(Log))] [InlineData(typeof(ILogger))] public void ValidateForContextMethods(Type loggerType) { var methodSet = loggerType.GetMethods().Where(method => method.Name == "ForContext"); var testMethods = typeof(MethodOverloadConventionTests).GetRuntimeMethods() .Where(method => Regex.IsMatch(method.Name, "ForContextMethod\\d")); Assert.Equal(testMethods.Count(), methodSet.Count()); foreach (var method in methodSet) { Assert.Equal(typeof(ILogger), method.ReturnType); Assert.True(method.IsPublic); var signatureMatchAndInvokeSuccess = false; var report = new StringBuilder(); foreach (var testMethod in testMethods) { try { testMethod.Invoke(this, new object[] { method }); signatureMatchAndInvokeSuccess = true; break; } catch (TargetInvocationException e) when (e.GetBaseException() is XunitException) { var xunitException = (XunitException)e.GetBaseException(); if (xunitException.Data.Contains("IsSignatureAssertionFailure")) { report.AppendLine($"{testMethod.Name} Signature Mismatch on: {method} with: {xunitException.Message}"); } else { report.AppendLine($"{testMethod.Name} Invocation Failure on: {method} with: {xunitException.UserMessage}"); } } } Assert.True(signatureMatchAndInvokeSuccess, $"{method} did not match any known method or failed invoke\n" + report); } } [Theory] [InlineData(typeof(SilentLogger))] [InlineData(typeof(Logger))] [InlineData(typeof(Log))] [InlineData(typeof(ILogger))] public void ValidateBindMessageTemplateMethods(Type loggerType) { var method = loggerType.GetMethod("BindMessageTemplate"); Assert.NotNull(method); Assert.Equal(typeof(bool), method!.ReturnType); Assert.True(method.IsPublic); var messageTemplateAttr = method.GetCustomAttribute<MessageTemplateFormatMethodAttribute>(); Assert.NotNull(messageTemplateAttr); Assert.Equal(messageTemplateAttr!.MessageTemplateParameterName, MessageTemplate); var parameters = method.GetParameters(); var index = 0; Assert.Equal("messageTemplate", parameters[index].Name); Assert.Equal(typeof(string), parameters[index].ParameterType); index++; Assert.Equal("propertyValues", parameters[index].Name); Assert.Equal(typeof(object[]), parameters[index].ParameterType); index++; Assert.Equal("parsedTemplate", parameters[index].Name); Assert.Equal(parameters[index].ParameterType, typeof(MessageTemplate).MakeByRefType()); Assert.True(parameters[index].IsOut); index++; Assert.Equal("boundProperties", parameters[index].Name); Assert.Equal(parameters[index].ParameterType, typeof(IEnumerable<LogEventProperty>).MakeByRefType()); Assert.True(parameters[index].IsOut); var logger = GetLogger(loggerType); var args = new object?[] { "Processed {value0}, {value1}", new object[] { "value0", "value1" }, null, null }; var result = InvokeMethod(method, logger, args); Assert.IsType<bool>(result); //SilentLogger is always false if (loggerType == typeof(SilentLogger)) return; Assert.True(result as bool?); //test null arg path var falseResult = InvokeMethod(method, logger, new object?[] { null, null, null, null }); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); } [Theory] [InlineData(typeof(SilentLogger))] [InlineData(typeof(Logger))] [InlineData(typeof(Log))] [InlineData(typeof(ILogger))] public void ValidateBindPropertyMethods(Type loggerType) { var method = loggerType.GetMethod("BindProperty"); Assert.NotNull(method); Assert.Equal(typeof(bool), method!.ReturnType); Assert.True(method.IsPublic); var parameters = method.GetParameters(); var index = 0; Assert.Equal("propertyName", parameters[index].Name); Assert.Equal(typeof(string), parameters[index].ParameterType); index++; Assert.Equal("value", parameters[index].Name); Assert.Equal(typeof(object), parameters[index].ParameterType); index++; Assert.Equal("destructureObjects", parameters[index].Name); Assert.Equal(typeof(bool), parameters[index].ParameterType); index++; Assert.Equal("property", parameters[index].Name); Assert.Equal(parameters[index].ParameterType, typeof(LogEventProperty).MakeByRefType()); Assert.True(parameters[index].IsOut); var logger = GetLogger(loggerType); var args = new object?[] { "SomeString", "someString", false, null }; var result = InvokeMethod(method, logger, args); Assert.IsType<bool>(result); //SilentLogger will always be false if (loggerType == typeof(SilentLogger)) return; Assert.True(result as bool?); //test null arg path/ invalid property name var falseResult = InvokeMethod(method, logger, new object?[] { " ", null, false, null }); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); } [Theory] [InlineData(typeof(SilentLogger))] [InlineData(typeof(Logger))] [InlineData(typeof(Log))] [InlineData(typeof(ILogger))] public void ValidateIsEnabledMethods(Type loggerType) { var method = loggerType.GetMethod("IsEnabled"); Assert.NotNull(method); Assert.True(method!.IsPublic); Assert.Equal(typeof(bool), method.ReturnType); var parameters = method.GetParameters(); Assert.Single(parameters); var parameter = parameters.Single(); Assert.Equal("level", parameter.Name); Assert.Equal(typeof(LogEventLevel), parameter.ParameterType); var logger = GetLogger(loggerType, out _, LogEventLevel.Information); var falseResult = InvokeMethod(method, logger, new object[] { LogEventLevel.Verbose }); Assert.IsType<bool>(falseResult); Assert.False(falseResult as bool?); var trueResult = InvokeMethod(method, logger, new object[] { LogEventLevel.Warning }); Assert.IsType<bool>(trueResult); //return as SilentLogger will always be false if (loggerType == typeof(SilentLogger)) return; Assert.True(trueResult as bool?); } //public ILogger ForContext(ILogEventEnricher enricher) void ForContextMethod0(MethodInfo method) { try { var parameters = method.GetParameters(); Assert.Single(parameters); var parameter = parameters.Single(); Assert.Equal("enricher", parameter.Name); Assert.Equal(typeof(ILogEventEnricher), parameter.ParameterType); } catch (XunitException e) { e.Data.Add("IsSignatureAssertionFailure", true); throw; } var logger = GetLogger(method.DeclaringType!); var logEnricher = new TestDummies.DummyThreadIdEnricher(); var enrichedLogger = InvokeMethod(method, logger, new object[] { logEnricher }); TestForContextResult(method, logger, normalResult: enrichedLogger); } //public ILogger ForContext(ILogEventEnricher[] enricher) void ForContextMethod1(MethodInfo method) { try { var parameters = method.GetParameters(); Assert.Single(parameters); var parameter = parameters.Single(); Assert.Equal("enrichers", parameter.Name); Assert.True(parameter.ParameterType == typeof(IEnumerable<ILogEventEnricher>) || parameter.ParameterType == typeof(ILogEventEnricher[])); } catch (XunitException e) { e.Data.Add("IsSignatureAssertionFailure", true); throw; } var logger = GetLogger(method.DeclaringType!); var logEnricher = new TestDummies.DummyThreadIdEnricher(); var enrichedLogger = InvokeMethod(method, logger, new object[] { new ILogEventEnricher[] { logEnricher, logEnricher } }); TestForContextResult(method, logger, normalResult: enrichedLogger); } //public ILogger ForContext(string propertyName, object value, bool destructureObjects) void ForContextMethod2(MethodInfo method) { try { var parameters = method.GetParameters(); Assert.Equal(3, parameters.Length); var index = 0; Assert.Equal("propertyName", parameters[index].Name); Assert.Equal(typeof(string), parameters[index].ParameterType); index++; Assert.Equal("value", parameters[index].Name); Assert.Equal(typeof(object), parameters[index].ParameterType); index++; Assert.Equal("destructureObjects", parameters[index].Name); Assert.Equal(typeof(bool), parameters[index].ParameterType); Assert.True(parameters[index].IsOptional); } catch (XunitException e) { e.Data.Add("IsSignatureAssertionFailure", true); throw; } var logger = GetLogger(method.DeclaringType!); var propertyName = "SomeString"; var propertyValue = "someString"; var enrichedLogger = InvokeMethod(method, logger, new object[] { propertyName, propertyValue, false }); Assert.NotNull(enrichedLogger); Assert.True(enrichedLogger is ILogger); //SilentLogger will always return itself if (method.DeclaringType == typeof(SilentLogger)) return; Assert.NotSame(logger, enrichedLogger); //invalid args path var sameLogger = InvokeMethod(method, logger, new object?[] { null, null, false }); Assert.NotNull(sameLogger); Assert.True(sameLogger is ILogger); if (method.DeclaringType == typeof(Log)) Assert.Same(Log.Logger, sameLogger); else Assert.Same(logger, sameLogger); } //public ILogger ForContext<TSource>() void ForContextMethod3(MethodInfo method) { try { Assert.True(method.IsGenericMethod); var genericArgs = method.GetGenericArguments(); Assert.Single(genericArgs); var genericArg = genericArgs.Single(); Assert.Equal("TSource", genericArg.Name); } catch (XunitException e) { e.Data.Add("IsSignatureAssertionFailure", true); throw; } var logger = GetLogger(method.DeclaringType!); var enrichedLogger = InvokeMethod(method, logger, null, new[] { typeof(object) }); Assert.NotNull(enrichedLogger); Assert.True(enrichedLogger is ILogger); } //public ILogger ForContext(Type source) void ForContextMethod4(MethodInfo method) { try { var args = method.GetParameters(); Assert.Single(args); var arg = args.Single(); Assert.Equal("source", arg.Name); Assert.Equal(typeof(Type), arg.ParameterType); } catch (XunitException e) { e.Data.Add("IsSignatureAssertionFailure", true); throw; } var logger = GetLogger(method.DeclaringType!); var enrichedLogger = InvokeMethod(method, logger, new object[] { typeof(object) }); TestForContextResult(method, logger, normalResult: enrichedLogger); } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local static void TestForContextResult(MethodInfo method, ILogger? logger, object normalResult) { Assert.NotNull(normalResult); Assert.True(normalResult is ILogger); if (method.DeclaringType == typeof(SilentLogger)) return; Assert.NotSame(logger, normalResult); //if invoked with null args it should return the same instance var sameLogger = InvokeMethod(method, logger, new object?[] { null }); Assert.NotNull(sameLogger); if (method.DeclaringType == typeof(Log)) Assert.Same(Log.Logger, sameLogger); else Assert.Same(logger, sameLogger); } void ValidateConventionForMethodSet( string setName, Type loggerType, bool checkMesgTempAttr = true, bool testInvokeResults = true) { IEnumerable<MethodInfo> methodSet; if (setName == Write) methodSet = loggerType.GetMethods() .Where(method => method.Name == setName && method.GetParameters() .Any(param => param.ParameterType == typeof(string))); else methodSet = loggerType.GetMethods() .Where(method => method.Name == setName); var testMethods = typeof(MethodOverloadConventionTests).GetRuntimeMethods() .Where(method => Regex.IsMatch(method.Name, "ValidateMethod\\d")); Assert.Equal(testMethods.Count(), methodSet.Count()); foreach (var method in methodSet) { Assert.Equal(typeof(void), method.ReturnType); Assert.True(method.IsPublic); if (checkMesgTempAttr) { var messageTemplateAttr = method.GetCustomAttribute<MessageTemplateFormatMethodAttribute>(); Assert.NotNull(messageTemplateAttr); Assert.Equal(messageTemplateAttr!.MessageTemplateParameterName, MessageTemplate); } var signatureMatchAndInvokeSuccess = false; var report = new StringBuilder(); foreach (var testMethod in testMethods) { try { Action<MethodInfo, Type[], object[]> invokeTestMethod; if (testInvokeResults) invokeTestMethod = InvokeConventionMethodAndTest; else invokeTestMethod = InvokeConventionMethod; testMethod.Invoke(this, new object[] { method, invokeTestMethod }); signatureMatchAndInvokeSuccess = true; break; } catch (TargetInvocationException e) when (e.GetBaseException() is XunitException) { var xunitException = (XunitException)e.GetBaseException(); if (xunitException.Data.Contains("IsSignatureAssertionFailure")) { report.AppendLine($"{testMethod.Name} Signature Mismatch on: {method} with: {xunitException.Message}"); } else { report.AppendLine($"{testMethod.Name} Invocation Failure on: {method} with: {xunitException.UserMessage}"); } } } Assert.True(signatureMatchAndInvokeSuccess, $"{method} did not match any known convention or failed invoke\n" + report); } } // Method0 (string messageTemplate) : void void ValidateMethod0(MethodInfo method, Action<MethodInfo, Type[]?, object[]> invokeMethod) { VerifyMethodSignature(method); var parameters = new object[] { "message" }; invokeMethod(method, null, parameters); } // Method1<T> (string messageTemplate, T propertyValue) : void void ValidateMethod1(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, isGeneric: true, expectedArgCount: 2); var typeArgs = new[] { typeof(string) }; var parameters = new object[] { "message", "value0" }; invokeMethod(method, typeArgs, parameters); } // Method2<T0, T1> (string messageTemplate, T0 propertyValue0, T1 propertyValue1) : void void ValidateMethod2(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, isGeneric: true, expectedArgCount: 3); var typeArgs = new[] { typeof(string), typeof(string) }; var parameters = new object[] { "Processed {value0}, {value1}", "value0", "value1" }; invokeMethod(method, typeArgs, parameters); } // Method3<T0, T1, T2> (string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) : void void ValidateMethod3(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, isGeneric: true, expectedArgCount: 4); var typeArgs = new[] { typeof(string), typeof(string), typeof(string) }; var parameters = new object[] { "Processed {value0}, {value1}, {value2}", "value0", "value1", "value2" }; invokeMethod(method, typeArgs, parameters); } // Method4 (string messageTemplate, params object[] propertyValues) : void void ValidateMethod4(MethodInfo method, Action<MethodInfo, Type[]?, object[]> invokeMethod) { VerifyMethodSignature(method, expectedArgCount: 2); var parameters = new object[] { "Processed {value0}, {value1}, {value2}", new object[] { "value0", "value1", "value2" } }; invokeMethod(method, null, parameters); } // Method5 (Exception exception, string messageTemplate) : void void ValidateMethod5(MethodInfo method, Action<MethodInfo, Type[]?, object[]> invokeMethod) { VerifyMethodSignature(method, hasExceptionArg: true, expectedArgCount: 2); var parameters = new object[] { new Exception("test"), "message" }; invokeMethod(method, null, parameters); } // Method6<T> (Exception exception, string messageTemplate, T propertyValue) : void void ValidateMethod6(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, hasExceptionArg: true, isGeneric: true, expectedArgCount: 3); var typeArgs = new[] { typeof(string) }; var parameters = new object[] { new Exception("test"), "Processed {value0}", "value0" }; invokeMethod(method, typeArgs, parameters); } // Method7<T0, T1> (Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) : void void ValidateMethod7(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, hasExceptionArg: true, isGeneric: true, expectedArgCount: 4); var typeArgs = new[] { typeof(string), typeof(string) }; var parameters = new object[] { new Exception("test"), "Processed {value0}, {value1}", "value0", "value1" }; invokeMethod(method, typeArgs, parameters); } // Method8<T0, T1, T2> (Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) : void void ValidateMethod8(MethodInfo method, Action<MethodInfo, Type[], object[]> invokeMethod) { VerifyMethodSignature(method, hasExceptionArg: true, isGeneric: true, expectedArgCount: 5); var typeArgs = new[] { typeof(string), typeof(string), typeof(string) }; var parameters = new object[] { new Exception("test"), "Processed {value0}, {value1}, {value2}", "value0", "value1", "value2" }; invokeMethod(method, typeArgs, parameters); } // Method9 (Exception exception, string messageTemplate, params object[] propertyValues) : void void ValidateMethod9(MethodInfo method, Action<MethodInfo, Type[]?, object[]> invokeMethod) { VerifyMethodSignature(method, hasExceptionArg: true, expectedArgCount: 3); var parameters = new object[] { new Exception("test"), "Processed {value0}, {value1}, {value2}", new object[] { "value0", "value1", "value2" } }; invokeMethod(method, null, parameters); } //primarily meant for testing silent logger static void InvokeConventionMethod( MethodInfo method, Type[] typeArgs, object[] parameters, out LogEventLevel level, out CollectingSink? sink) { var logger = GetLogger(method.DeclaringType!, out sink); if (method.Name == Write) { level = LogEventLevel.Information; var paramList = new List<object> { level }; paramList.AddRange(parameters); parameters = paramList.ToArray(); } else { Assert.True(Enum.TryParse(method.Name, out level)); } InvokeMethod(method, logger, parameters, typeArgs); } static void InvokeConventionMethod(MethodInfo method, Type[] typeArgs, object[] parameters) { InvokeConventionMethod(method, typeArgs, parameters, out _, out _); } static void InvokeConventionMethodAndTest(MethodInfo method, Type[] typeArgs, object[] parameters) { InvokeConventionMethod(method, typeArgs, parameters, out var level, out var sink); EvaluateSingleResult(level, sink); } // parameters will always be ordered so single evaluation method will work static void VerifyMethodSignature(MethodInfo method, bool hasExceptionArg = false, bool isGeneric = false, int expectedArgCount = 1) { try { var parameters = method.GetParameters(); var index = 0; if (method.Name == Write) { //write convention methods always have one more parameter, LogEventLevel Arg expectedArgCount++; Assert.Equal(typeof(LogEventLevel), parameters[index].ParameterType); Assert.Equal("level", parameters[index].Name); index++; } Assert.Equal(parameters.Length, expectedArgCount); // exceptions always come before messageTemplate string if (hasExceptionArg) //verify exception argument type and name { Assert.Equal(typeof(Exception), parameters[index].ParameterType); Assert.Equal("exception", parameters[index].Name); index++; } //check for message template string argument Assert.Equal(typeof(string), parameters[index].ParameterType); Assert.Equal(parameters[index].Name, MessageTemplate); index++; if (isGeneric) //validate type arguments, generic parameters, and cross-reference { Assert.True(method.IsGenericMethod); var genericTypeArgs = method.GetGenericArguments(); //multiple generic argument convention T0...Tx : T0 propertyValue0... Tx propertyValueX if (genericTypeArgs.Length > 1) { for (var i = 0; i < genericTypeArgs.Length; i++, index++) { Assert.Equal(genericTypeArgs[i].Name, $"T{i}"); var genericConstraints = genericTypeArgs[i].GetTypeInfo().GetGenericParameterConstraints(); Assert.Empty(genericConstraints); Assert.Equal(parameters[index].Name, $"propertyValue{i}"); Assert.Equal(parameters[index].ParameterType, genericTypeArgs[i]); } } else //single generic argument convention T : T propertyValue { var genericTypeArg = genericTypeArgs[0]; Assert.Equal("T", genericTypeArg.Name); var genericConstraints = genericTypeArg.GetTypeInfo().GetGenericParameterConstraints(); Assert.Empty(genericConstraints); Assert.Equal("propertyValue", parameters[index].Name); Assert.Equal(genericTypeArg, parameters[index].ParameterType); index++; } } //check for params argument: params object[] propertyValues //params argument currently has to be the last argument, and generic methods don't have params argument if (!isGeneric && (parameters.Length - index) == 1) { var paramsArrayArg = parameters[index]; // params array attribute should never have derived/inherited classes var paramsAttr = parameters[index].GetCustomAttribute(typeof(ParamArrayAttribute), inherit: false); Assert.NotNull(paramsAttr); Assert.Equal(typeof(object[]), paramsArrayArg.ParameterType); Assert.Equal("propertyValues", paramsArrayArg.Name); } } catch (XunitException e) { // mark xunit assertion failures e.Data.Add("IsSignatureAssertionFailure", true); throw; } } static object InvokeMethod( MethodInfo method, ILogger? instance, object?[]? parameters, Type[]? typeArgs = null) { if (method.IsStatic) { if (method.IsGenericMethod) return method.MakeGenericMethod(typeArgs!).Invoke(null, parameters)!; return method.Invoke(null, parameters)!; } if (method.IsGenericMethod) return method.MakeGenericMethod(typeArgs!).Invoke(instance, parameters)!; return method.Invoke(instance, parameters)!; } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local static void EvaluateSingleResult(LogEventLevel level, CollectingSink? results) { if (results == null) throw new ArgumentNullException(nameof(results), $"Invalid test state. {nameof(results)} should have a value here."); //evaluate single log event Assert.Single(results.Events); var evt = results.Events.Single(); Assert.Equal(level, evt.Level); } static ILogger? GetLogger(Type loggerType) => GetLogger(loggerType, out _); static ILogger? GetLogger(Type loggerType, out CollectingSink? sink, LogEventLevel level = LogEventLevel.Verbose) { sink = null; if (loggerType == typeof(Logger) || loggerType == typeof(ILogger)) { sink = new CollectingSink(); return new LoggerConfiguration() .MinimumLevel.Is(level) .WriteTo.Sink(sink) .CreateLogger(); } if (loggerType == typeof(Log)) { sink = new CollectingSink(); Log.CloseAndFlush(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Is(level) .WriteTo.Sink(sink) .CreateLogger(); return null; } if (loggerType == typeof(SilentLogger)) return SilentLogger.Instance; throw new ArgumentException($"Logger Type of {loggerType} is not supported"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using Xunit; public static class ExpectedExceptionTests { [Fact] [OuterLoop] public static void NotExistentHost_Throws_EndpointNotFoundException() { string nonExistentHost = "http://nonexisthost/WcfService/WindowsCommunicationFoundation"; BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() => { using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(nonExistentHost))) { IWcfService serviceProxy = factory.CreateChannel(); string response = serviceProxy.Echo("Hello"); } }); // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(nonExistentHost), string.Format("Expected exception message to contain: '{0}'", nonExistentHost)); } [Fact] [OuterLoop] public static void ServiceRestart_Throws_CommunicationException() { StringBuilder errorBuilder = new StringBuilder(); string restartServiceAddress = ""; BasicHttpBinding binding = new BasicHttpBinding(); try { using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); restartServiceAddress = serviceProxy.GetRestartServiceEndpoint(); } } catch (Exception e) { string error = String.Format("Unexpected exception thrown while calling the 'GetRestartServiceEndpoint' operation. {0}", e.ToString()); if (e.InnerException != null) error += String.Format("\r\nInnerException:\r\n{0}", e.InnerException.ToString()); errorBuilder.AppendLine(error); } if (errorBuilder.Length == 0) { // Get the Service host name and replace localhost with it UriBuilder builder = new UriBuilder(Endpoints.HttpBaseAddress_Basic); string hostName = builder.Uri.Host; restartServiceAddress = restartServiceAddress.Replace("[HOST]", hostName); //On .NET Native retail, exception message is stripped to include only parameter string expectExceptionMsg = restartServiceAddress; try { using (ChannelFactory<IWcfRestartService> factory = new ChannelFactory<IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress))) { // Get the last portion of the restart service url which is a Guid and convert it back to a Guid // This is needed by the RestartService operation as a Dictionary key to get the ServiceHost string uniqueIdentifier = restartServiceAddress.Substring(restartServiceAddress.LastIndexOf("/") + 1); Guid guid = new Guid(uniqueIdentifier); IWcfRestartService serviceProxy = factory.CreateChannel(); serviceProxy.RestartService(guid); } errorBuilder.AppendLine("Expected CommunicationException exception, but no exception thrown."); } catch (Exception e) { if (e.GetType() == typeof(CommunicationException)) { if (e.Message.Contains(expectExceptionMsg)) { } else { errorBuilder.AppendLine(string.Format("Expected exception message contains: {0}, actual: {1}", expectExceptionMsg, e.Message)); } } else { errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}/n Exception was: {2}", "CommunicationException", e.GetType(), e.ToString())); } } } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceRestart_Throws_CommunicationException FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void NonExistentAction_Throws_ActionNotSupportedException() { string exceptionMsg = "The message with Action 'http://tempuri.org/IWcfService/NotExistOnServer' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)."; try { BasicHttpBinding binding = new BasicHttpBinding(); using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); serviceProxy.NotExistOnServer(); } } catch (Exception e) { if (e.GetType() != typeof(System.ServiceModel.ActionNotSupportedException)) { Assert.True(false, string.Format("Expected exception: {0}, actual: {1}", "ActionNotSupportedException", e.GetType())); } if (e.Message != exceptionMsg) { Assert.True(false, string.Format("Expected Fault Message: {0}, actual: {1}", exceptionMsg, e.Message)); } return; } Assert.True(false, "Expected ActionNotSupportedException exception, but no exception thrown."); } // SendTimeout is set to 5 seconds, the service waits 10 seconds to respond. // The client should throw a TimeoutException [Fact] [OuterLoop] public static void SendTimeout_For_Long_Running_Operation_Throws_TimeoutException() { BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(5000); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); Stopwatch watch = new Stopwatch(); try { var exception = Assert.Throws<TimeoutException>(() => { IWcfService proxy = factory.CreateChannel(); watch.Start(); proxy.EchoWithTimeout("Hello"); }); } finally { watch.Stop(); } // want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec // (usual case is around 5001-5005 ms) Assert.InRange<long>(watch.ElapsedMilliseconds, 5000, 10000); } // SendTimeout is set to 0, this should trigger a TimeoutException before even attempting to call the service. [Fact] [OuterLoop] public static void SendTimeout_Zero_Throws_TimeoutException_Immediately() { BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(0); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); Stopwatch watch = new Stopwatch(); try { var exception = Assert.Throws<TimeoutException>(() => { IWcfService proxy = factory.CreateChannel(); watch.Start(); proxy.EchoWithTimeout("Hello"); }); } finally { watch.Stop(); } // want to assert that this completed in < 2 s as an upper bound since the SendTimeout is 0 sec // (usual case is around 1 - 3 ms) Assert.InRange<long>(watch.ElapsedMilliseconds, 0, 2000); } [Fact] [OuterLoop] public static void FaultException_Throws_WithFaultDetail() { string faultMsg = "Test Fault Exception"; StringBuilder errorBuilder = new StringBuilder(); try { BasicHttpBinding binding = new BasicHttpBinding(); using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); serviceProxy.TestFault(faultMsg); } } catch (Exception e) { if (e.GetType() != typeof(FaultException<FaultDetail>)) { string error = string.Format("Expected exception: {0}, actual: {1}\r\n{2}", "FaultException<FaultDetail>", e.GetType(), e.ToString()); if (e.InnerException != null) error += String.Format("\r\nInnerException:\r\n{0}", e.InnerException.ToString()); errorBuilder.AppendLine(error); } else { FaultException<FaultDetail> faultException = (FaultException<FaultDetail>)(e); string actualFaultMsg = ((FaultDetail)(faultException.Detail)).Message; if (actualFaultMsg != faultMsg) { errorBuilder.AppendLine(string.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, actualFaultMsg)); } } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: FaultException_Throws_WithFaultDetail FAILED with the following errors: {0}", errorBuilder)); return; } Assert.True(false, "Expected FaultException<FaultDetail> exception, but no exception thrown."); } [Fact] [OuterLoop] public static void UnexpectedException_Throws_FaultException() { string faultMsg = "This is a test fault msg"; StringBuilder errorBuilder = new StringBuilder(); try { BasicHttpBinding binding = new BasicHttpBinding(); using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); serviceProxy.ThrowInvalidOperationException(faultMsg); } } catch (Exception e) { if (e.GetType() != typeof(FaultException<ExceptionDetail>)) { errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}", "FaultException<ExceptionDetail>", e.GetType())); } else { FaultException<ExceptionDetail> faultException = (FaultException<ExceptionDetail>)(e); string actualFaultMsg = ((ExceptionDetail)(faultException.Detail)).Message; if (actualFaultMsg != faultMsg) { errorBuilder.AppendLine(string.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, actualFaultMsg)); } } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: UnexpectedException_Throws_FaultException FAILED with the following errors: {0}", errorBuilder)); return; } Assert.True(false, "Expected FaultException<FaultDetail> exception, but no exception thrown."); } [Fact] [OuterLoop] public static void UnknownUrl_Throws_EndpointNotFoundException() { string notFoundUrl = Endpoints.HttpUrlNotFound_Address; BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() => { using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(notFoundUrl))) { IWcfService serviceProxy = factory.CreateChannel(); string response = serviceProxy.Echo("Hello"); } }); // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(notFoundUrl), string.Format("Expected exception message to contain: '{0}'", notFoundUrl)); } [Fact] [OuterLoop] public static void UnknownUrl_Throws_ProtocolException() { string protocolExceptionUri = Endpoints.HttpProtocolError_Address; BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(protocolExceptionUri))) { IWcfService serviceProxy = factory.CreateChannel(); ProtocolException exception = Assert.Throws<ProtocolException>(() => { string response = serviceProxy.Echo("Hello"); }); // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(protocolExceptionUri), string.Format("Expected exception message to contain '{0}'", protocolExceptionUri)); } } [Fact] [OuterLoop] public static void DuplexCallback_Throws_FaultException_DirectThrow() { DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback(true); InstanceContext context = new InstanceContext(callbackService); try { var exception = Assert.Throws<FaultException<FaultDetail>>(() => { factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address)); IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel(); Task<Guid> task = serviceProxy.FaultPing(guid); if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout)) { Guid returnedGuid = task.GetAwaiter().GetResult(); } else { throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout)); } // Not closing the factory as an exception will always be thrown prior to this point. }); Assert.Equal("ServicePingFaultCallback", exception.Code.Name); Assert.Equal("Reason: Testing FaultException returned from Duplex Callback", exception.Reason.GetMatchingTranslation().Text); } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } } [Fact] [OuterLoop] public static void DuplexCallback_Throws_FaultException_ReturnsFaultedTask() { DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null; Guid guid = Guid.NewGuid(); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback(); InstanceContext context = new InstanceContext(callbackService); try { var exception = Assert.Throws<FaultException<FaultDetail>>(() => { factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address)); IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel(); Task<Guid> task = serviceProxy.FaultPing(guid); if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout)) { Guid returnedGuid = task.GetAwaiter().GetResult(); } else { throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout)); } // Not closing the factory as an exception will always be thrown prior to this point. }); Assert.Equal("ServicePingFaultCallback", exception.Code.Name); Assert.Equal("Reason: Testing FaultException returned from Duplex Callback", exception.Reason.GetMatchingTranslation().Text); } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } } }
// // 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public static partial class ProductPolicyOperationsExtensions { /// <summary> /// Deletes specific product policy of the Api Management service /// instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string etag) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).DeleteAsync(resourceGroupName, serviceName, pid, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes specific product policy of the Api Management service /// instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string etag) { return operations.DeleteAsync(resourceGroupName, serviceName, pid, etag, CancellationToken.None); } /// <summary> /// Gets specific product policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public static PolicyGetResponse Get(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).GetAsync(resourceGroupName, serviceName, pid, format); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets specific product policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public static Task<PolicyGetResponse> GetAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format) { return operations.GetAsync(resourceGroupName, serviceName, pid, format, CancellationToken.None); } /// <summary> /// Sets policy for product. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Set(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format, Stream policyStream, string etag) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).SetAsync(resourceGroupName, serviceName, pid, format, policyStream, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Sets policy for product. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml, /// application/vnd.ms-azure-apim.policy.raw+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> SetAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format, Stream policyStream, string etag) { return operations.SetAsync(resourceGroupName, serviceName, pid, format, policyStream, etag, CancellationToken.None); } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { [TestCase(Name = "Create Overloads", Desc = "Create Overloads")] public partial class TCCreateOverloads : TCXMLReaderBaseGeneral { private string _sampleFileName = @"sample.xml"; private string _sampleXml = "<root><a/></root>"; private void CreateFile() { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); sw.WriteLine(_sampleXml); sw.Flush(); FilePathUtil.addStream(_sampleFileName, ms); } public override int Init(object o) { CreateFile(); return base.Init(o); } public Stream GetStream() { return FilePathUtil.getStream(_sampleFileName); } public String GetUrl() { return _sampleFileName; } public TextReader GetTextReader() { return new StringReader(_sampleXml); } public string GetBaseUri() { return _sampleFileName; } public XmlReaderSettings GetSettings() { return new XmlReaderSettings(); } public XmlReader GetXmlReader() { return ReaderHelper.Create(GetTextReader()); } public XmlParserContext GetParserContext() { NameTable nt = new NameTable(); XmlParserContext pc = new XmlParserContext(nt, new XmlNamespaceManager(nt), null, XmlSpace.Default); return pc; } public class ReaderDelegate { public static bool Create(String url) { XmlReader reader = null; try { reader = ReaderHelper.Create(url); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(Stream input) { XmlReader reader = null; try { reader = ReaderHelper.Create(input); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(TextReader input) { XmlReader reader = null; try { reader = ReaderHelper.Create(input); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(String url, XmlReaderSettings settings) { XmlReader reader = null; try { reader = ReaderHelper.Create(url, settings); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(XmlReader input, XmlReaderSettings settings) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(Stream input, XmlReaderSettings settings) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(TextReader input, XmlReaderSettings settings) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(Stream input, XmlReaderSettings settings, String baseUri) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings, baseUri); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(Stream input, XmlReaderSettings settings, XmlParserContext parserContext) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings, parserContext); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(TextReader input, XmlReaderSettings settings, String baseUri) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings, baseUri); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(TextReader input, XmlReaderSettings settings, XmlParserContext parserContext) { XmlReader reader = null; try { reader = ReaderHelper.Create(input, settings, parserContext); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } public static bool Create(String url, XmlReaderSettings settings, XmlParserContext context) { XmlReader reader = null; try { reader = ReaderHelper.Create(url, settings, context); while (reader.Read()) ; return true; } catch (ArgumentNullException ane) { CError.WriteLineIgnore(ane.ToString()); return false; } finally { if (reader != null) reader.Dispose(); } } } [Variation("Null Input")] public int v1() { CError.Equals(ReaderDelegate.Create((Stream)null), false, "Null Stream doesnt throw error1"); CError.Equals(ReaderDelegate.Create((Stream)null, GetSettings(), GetBaseUri()), false, "Null Stream doesnt throw error2"); CError.Equals(ReaderDelegate.Create((Stream)null, GetSettings()), false, "Null Stream doesnt throw error3"); CError.Equals(ReaderDelegate.Create((string)null), false, "Null URL doesnt throw error1"); CError.Equals(ReaderDelegate.Create((string)null, GetSettings()), false, "Null URL doesnt throw error2"); CError.Equals(ReaderDelegate.Create((string)null, GetSettings(), GetParserContext()), false, "Null URL doesnt throw error3"); CError.Equals(ReaderDelegate.Create((TextReader)null), false, "Null TextReader doesnt throw error1"); CError.Equals(ReaderDelegate.Create((TextReader)null, GetSettings(), GetBaseUri()), false, "Null TextReader doesnt throw error2"); CError.Equals(ReaderDelegate.Create((TextReader)null, GetSettings()), false, "Null TextReader doesnt throw error2"); return TEST_PASS; } [Variation("Valid Input")] public int v2() { XmlReader r = null; Stream s = GetStream(); r = ReaderHelper.Create(s); while (r.Read()) ; r.Dispose(); r = ReaderHelper.Create(GetUrl()); while (r.Read()) ; r.Dispose(); r = ReaderHelper.Create(GetTextReader()); while (r.Read()) ; r.Dispose(); return TEST_PASS; } [Variation("Null Settings")] public int v3() { CError.Equals(ReaderDelegate.Create(GetStream(), null, GetParserContext()), true, "StreamOverload2"); CError.Equals(ReaderDelegate.Create(GetStream(), null), true, "StreamOverload3"); CError.Equals(ReaderDelegate.Create(GetUrl(), null), true, "URL Overload 1"); CError.Equals(ReaderDelegate.Create(GetUrl(), null, GetParserContext()), true, "URL Overload 2"); CError.Equals(ReaderDelegate.Create(GetTextReader(), null, GetParserContext()), true, "TextReader Overload2"); CError.Equals(ReaderDelegate.Create(GetTextReader(), null), true, "TextReader Overload3"); CError.Equals(ReaderDelegate.Create(GetXmlReader(), null), true, "XmlReader Overload1"); return TEST_PASS; } [Variation("Null ParserContext")] public int v5() { CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (string)null), true, "StreamOverload3"); CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (XmlParserContext)null), true, "StreamOverload4"); CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), (string)null), true, "TextOverload3"); CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), GetParserContext()), true, "TextOverload4"); return TEST_PASS; } [Variation("Valid Settings")] public int v6() { CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (string)null), true, "StreamOverload2"); CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (XmlParserContext)null), true, "StreamOverload2"); CError.Equals(ReaderDelegate.Create(GetUrl(), GetSettings()), true, "URL Overload 1"); CError.Equals(ReaderDelegate.Create(GetUrl(), GetSettings(), GetParserContext()), true, "URL Overload 2"); CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), (string)null), true, "TextReader Overload2"); CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), (XmlParserContext)null), true, "TextReader Overload2"); CError.Equals(ReaderDelegate.Create(GetXmlReader(), GetSettings()), true, "XmlReader Overload1"); return TEST_PASS; } [Variation("Valid ParserContext")] public int v7() { CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), GetParserContext()), true, "StreamOverload3"); CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), GetParserContext()), true, "TextOverload3"); return TEST_PASS; } } }
// 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.Diagnostics; using System.Text.RegularExpressions; namespace BasicEventSourceTests { /// <summary> /// Tests the user experience for common user errors. /// </summary> public partial class TestsUserErrors { /// <summary> /// Try to pass a user defined class (even with EventData) /// to a manifest based eventSource /// </summary> [Fact] public void Test_BadTypes_Manifest_UserClass() { var badEventSource = new BadEventSource_Bad_Type_UserClass(); Test_BadTypes_Manifest(badEventSource); } private void Test_BadTypes_Manifest(EventSource source) { try { using (var listener = new EventListenerListener()) { var events = new List<Event>(); Debug.WriteLine("Adding delegate to onevent"); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(source.Name, EventCommand.Enable); listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " Assert.Matches("Unsupported type", message); } } finally { source.Dispose(); } } /// <summary> /// Test the /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754 public void Test_BadEventSource_MismatchedIds() { TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new List<Func<Listener>>(); listenerGenerators.Add(() => new EventListenerListener()); var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func<Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// A helper that can run the test under a variety of conditions /// * Whether the eventSource is enabled at startup /// * Whether the listener is ETW or an EventListern /// * Whether the ETW output is self describing or not. /// </summary> private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings) { var eventSourceName = typeof(BadEventSource_MismatchedIds).Name; Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")"); // Activate the source before the source exists (if told to). if (onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; using (var source = new BadEventSource_MismatchedIds(settings)) { Assert.Equal(eventSourceName, source.Name); // activate the source after the source exists (if told to). if (!onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); source.Event1(1); // Try to send something. } listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); Debug.WriteLine(string.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. " if (!PlatformDetection.IsFullFramework) // Full framework has typo Assert.Matches("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message); } [Fact] public void Test_Bad_WriteRelatedID_ParameterName() { #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null; EventListenerListener listener = null; try { Guid oldGuid; Guid newGuid = Guid.NewGuid(); Guid newGuid2 = Guid.NewGuid(); EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter(); using (var listener = new EventListenerListener()) { var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(bes.Name, EventCommand.Enable); bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.")); } } finally { if (bes != null) { bes.Dispose(); } if (listener != null) { listener.Dispose(); } } #endif } } /// <summary> /// This EventSource has a common user error, and we want to make sure EventSource /// gives a reasonable experience in that case. /// </summary> internal class BadEventSource_MismatchedIds : EventSource { public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { } public void Event1(int arg) { WriteEvent(1, arg); } // Error Used the same event ID for this event. public void Event2(int arg) { WriteEvent(1, arg); } } /// <summary> /// A manifest based provider with a bad type byte[] /// </summary> internal class BadEventSource_Bad_Type_ByteArray : EventSource { public void Event1(byte[] myArray) { WriteEvent(1, myArray); } } public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource { public void E2() { this.Write("sampleevent", new { a = "a string" }); } [Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)] public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId) { WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId); } public class Keywords { public const EventKeywords Debug = (EventKeywords)0x0002; } } [EventData] public class UserClass { public int i; }; /// <summary> /// A manifest based provider with a bad type (only supported in self describing) /// </summary> internal class BadEventSource_Bad_Type_UserClass : EventSource { public void Event1(UserClass myClass) { WriteEvent(1, myClass); } } }
// 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.Generic; using System.Globalization; using System.Resources; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.BlogClient; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Diagnostics; using OpenLiveWriter.CoreServices.Marketization; using OpenLiveWriter.CoreServices.Settings; using OpenLiveWriter.HtmlEditor; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Localization; using OpenLiveWriter.Mshtml; using OpenLiveWriter.PostEditor.ContentSources.Common; using OpenLiveWriter.PostEditor.ImageInsertion.WebImages; using OpenLiveWriter.PostEditor.LiveClipboard; using OpenLiveWriter.PostEditor.PostHtmlEditing; using OpenLiveWriter.PostEditor.Tagging; using OpenLiveWriter.PostEditor.Video; using OpenLiveWriter.InternalWriterPlugin; using mshtml; namespace OpenLiveWriter.PostEditor.ContentSources { internal interface IContentSourceSite : IPublishingContext { IWin32Window DialogOwner { get; } IExtensionData CreateExtensionData(string id); bool InsertCommandsEnabled { get; } string SelectedHtml { get; } void Focus(); void InsertContent(string content, bool select); void InsertContent(string contentSourceId, string content, IExtensionData extensionData); void InsertContent(string contentSourceId, string content, IExtensionData extensionData, HtmlInsertionOptions insertionOptions); /// <summary> /// Given a list of contentIds the IContentSourceSite will find the Ids still in use and /// tell the SmartContentSource to update those smart content elements in the post. /// </summary> /// <param name="extensionDataList">List of contentIds that will be updated, this list can contain nulls</param> /// <returns>It returns a list of extensiondata that was no updated because it wasnt found in the editor</returns> IExtensionData[] UpdateContent(IExtensionData[] extensionDataList); } public class SmartContentItem { public SmartContentItem(string contentSourceId, IExtensionData extensionData) : this(contentSourceId, extensionData.Id, new SmartContent(extensionData)) { } public SmartContentItem(string contentSourceId, string contentBlockId, SmartContent smartContent) { _contentSourceId = contentSourceId; _contentBlockId = contentBlockId; _smartContent = smartContent; } public string ContainingElementId { get { return ContentSourceManager.MakeContainingElementId(ContentSourceId, ContentBlockId); } } public string ContentSourceId { get { return _contentSourceId; } } public string ContentBlockId { get { return _contentBlockId; } } public SmartContent SmartContent { get { return _smartContent; } } private string _contentSourceId; private string _contentBlockId; private SmartContent _smartContent; } public class ContentSourceInfo { private ResourceManager _resMan; public ContentSourceInfo(Type pluginType, bool showErrors) { // save a refernce to the type _pluginType = pluginType; _resMan = new ResourceManager(_pluginType); // initialize list of live clipboard attributes ArrayList liveClipboardFormats = new ArrayList(); // initialize our metadata from the Type's attributes object[] attributes = pluginType.GetCustomAttributes(true); foreach (object attribute in attributes) { if (attribute is WriterPluginAttribute) { _writerPlugin = attribute as WriterPluginAttribute; VerifyPluginBitmap(showErrors); } else if (attribute is InsertableContentSourceAttribute) { _insertableContentSource = attribute as InsertableContentSourceAttribute; } else if (attribute is UrlContentSourceAttribute) { _urlContentSource = attribute as UrlContentSourceAttribute; } else if (attribute is LiveClipboardContentSourceAttribute) { LiveClipboardContentSourceAttribute liveClipboardContentSourceAttribute = attribute as LiveClipboardContentSourceAttribute; liveClipboardFormats.Add(new LiveClipboardFormatHandler(liveClipboardContentSourceAttribute, this)); } else if (attribute is CustomLocalizedPluginAttribute) { _customLocalizedPlugin = attribute as CustomLocalizedPluginAttribute; } } // copy array of lc attributes _liveClipboardFormatHandlers = liveClipboardFormats.ToArray(typeof(LiveClipboardFormatHandler)) as LiveClipboardFormatHandler[]; if (_writerPlugin == null) throw new WriterContentPluginAttributeMissingException(pluginType); if (!CanCreateNew && !CanCreateFromUrl && (LiveClipboardFormatHandlers.Length == 0) && !(typeof(PublishNotificationHook).IsAssignableFrom(pluginType) || typeof(HeaderFooterSource).IsAssignableFrom(pluginType))) throw new WriterContentPluginAttributeMissingException(pluginType); // initialize settings _settings = _parentSettings.GetSubSettings(Id); } ~ContentSourceInfo() { // Explicit dispose of managed objects not necessary from finalizer // try { _settings.Dispose(); }catch{} } // plugin type public Type Type { get { return _pluginType; } } // convenience accessors for most frequently requested properties public string Id { get { return _writerPlugin.Id; } } public string Name { get { string name = GetLocalizedString("WriterPlugin.Name", _writerPlugin.Name); int nameLength = name.Length; if (name != null) name = name.Substring(0, Math.Min(name.Length, MAX_NAME_LENGTH)).Trim(); return name; } } private const int MAX_NAME_LENGTH = 256; public Bitmap Image { get { Bitmap bitmap; Debug.Assert(_pluginType.Assembly.ManifestModule.Name != "OpenLiveWriter.WriterPlugin.dll" && _pluginType.Assembly.ManifestModule.Name != "OpenLiveWriter.PostEditor.dll", "1st Party plugins should not have their image loaded. It should come from the ribbon"); if (_writerPlugin.ImagePath != null) bitmap = ResourceHelper.LoadAssemblyResourceBitmap(_pluginType.Assembly, _pluginType.Namespace, _writerPlugin.ImagePath, false); else bitmap = ResourceHelper.LoadAssemblyResourceBitmap("ContentSources.Images.DefaultPluginImage.png"); if (bitmap.Width != IMAGE_WIDTH || bitmap.Height != IMAGE_HEIGHT) { if (HasTransparentBorder(bitmap)) bitmap = ImageHelper2.CropBitmap(bitmap, GetCenterRectangle(bitmap)); else bitmap = ImageHelper2.CreateResizedBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, bitmap.RawFormat); } return bitmap; } } private Rectangle GetCenterRectangle(Bitmap bitmap) { return new Rectangle( (bitmap.Width - IMAGE_WIDTH) / 2, (bitmap.Height - IMAGE_HEIGHT) / 2, IMAGE_WIDTH, IMAGE_HEIGHT ); } private bool HasTransparentBorder(Bitmap bitmap) { if (bitmap.Width < IMAGE_WIDTH || bitmap.Height < IMAGE_HEIGHT) return false; Rectangle rect = GetCenterRectangle(bitmap); for (int x = 0; x < bitmap.Width; x++) for (int y = 0; y < bitmap.Height; y++) if (!rect.Contains(x, y) && bitmap.GetPixel(x, y).A > 0) return false; return true; } private string GetLocalizedString(string name, string defaultValue) { if (_customLocalizedPlugin != null) { string fullName = "Plugin." + _customLocalizedPlugin.Name + "." + name; fullName = fullName.Replace('.', '_'); string customValue = Res.Get(fullName); return (customValue != null) ? customValue : defaultValue; } if (_resMan == null) return defaultValue; try { string result = _resMan.GetString(name); if (result == null) return defaultValue; return result; } catch (MissingManifestResourceException) { _resMan = null; return defaultValue; } } private CustomLocalizedPluginAttribute _customLocalizedPlugin; // core plugin attributes private WriterPluginAttribute _writerPlugin; public bool WriterPluginHasEditableOptions { get { return _writerPlugin.HasEditableOptions; } } public string WriterPluginPublisherUrl { get { return _writerPlugin.PublisherUrl; } } public string WriterPluginDescription { get { return GetLocalizedString("WriterPlugin.Description", _writerPlugin.Description); } } // insertable content source private InsertableContentSourceAttribute _insertableContentSource; public bool CanCreateNew { get { return _insertableContentSource != null; } } public string InsertableContentSourceMenuText { get { string menuText = GetLocalizedString("InsertableContentSource.MenuText", _insertableContentSource.MenuText); if (menuText != null) menuText = menuText.Substring(0, Math.Min(menuText.Length, MAX_MENU_TEXT_LENGTH)).Trim(); return menuText; } } private const int MAX_MENU_TEXT_LENGTH = 50; public string InsertableContentSourceSidebarText { get { string sidebarText = GetLocalizedString("InsertableContentSource.SidebarText", _insertableContentSource.SidebarText); if (sidebarText != null) sidebarText = sidebarText.Substring(0, Math.Min(sidebarText.Length, MAX_SIDEBAR_TEXT_LENGTH)).Trim(); return sidebarText; } } private const int MAX_SIDEBAR_TEXT_LENGTH = 20; // url content source private UrlContentSourceAttribute _urlContentSource; public bool CanCreateFromUrl { get { return _urlContentSource != null; } } public string UrlContentSourceUrlPattern { get { return _urlContentSource.UrlPattern; } } public bool UrlContentSourceRequiresProgress { get { return _urlContentSource != null && _urlContentSource.RequiresProgress; } } public string UrlContentSourceProgressCaption { get { return GetLocalizedString("UrlContentSource.ProgressCaption", _urlContentSource.ProgressCaption); } } public string UrlContentSourceProgressMessage { get { return GetLocalizedString("UrlContentSource.ProgressMessage", _urlContentSource.ProgressMessage); } } // live clipboard content source metadata internal LiveClipboardFormatHandler[] LiveClipboardFormatHandlers { get { return _liveClipboardFormatHandlers; } } private LiveClipboardFormatHandler[] _liveClipboardFormatHandlers; public bool Enabled { get { return _settings.GetBoolean(ENABLED, true); } set { _settings.SetBoolean(ENABLED, value); } } private const string ENABLED = "Enabled"; public DateTime LastUse { get { return _settings.GetDateTime(LAST_USE, DateTime.Now); } set { _settings.SetDateTime(LAST_USE, value); } } private const string LAST_USE = "LastUse"; public WriterPlugin Instance { get { lock (this) { if (_plugin == null) { _plugin = (WriterPlugin)Activator.CreateInstance(_pluginType); _plugin.Initialize(new PluginSettingsAdaptor(_settings)); } return _plugin; } } } public override bool Equals(object obj) { return (obj as ContentSourceInfo).Id == this.Id; } public override int GetHashCode() { return this.Id.GetHashCode(); } internal class LastUseComparer : IComparer { public int Compare(object x, object y) { return -(x as ContentSourceInfo).LastUse.CompareTo((y as ContentSourceInfo).LastUse); } } internal class NameComparer : IComparer { public int Compare(object x, object y) { return (x as ContentSourceInfo).Name.CompareTo((y as ContentSourceInfo).Name); } } internal const int IMAGE_WIDTH = 16; internal const int IMAGE_HEIGHT = 16; private string VerifyAttributeValue(Type pluginType, object attribute, string attributeField, string attributeValue) { if (attributeValue != null && attributeValue != String.Empty) return attributeValue; else throw new PluginAttributeFieldMissingException(pluginType, attribute.GetType(), attributeField); } private void VerifyPluginBitmap(bool showErrors) { if (_writerPlugin.ImagePath != null) { try { // try to load bitmap using (Bitmap bitmap = new Bitmap(_pluginType, _writerPlugin.ImagePath)) { // verify bitmap size if ((bitmap.Width != IMAGE_WIDTH || bitmap.Height != IMAGE_HEIGHT) && (bitmap.Width != 20 || bitmap.Height != 18)) { string errorText = String.Format(CultureInfo.CurrentCulture, "Warning: The bitmap for plugin {0} is not the correct size (it should be 16x16 or 20x18).", _pluginType.Name); Trace.Fail(errorText); } } } catch (Exception e) { Trace.Fail("Failed to load plugin bitmap: " + e.ToString()); if (showErrors) DisplayMessage.Show(MessageId.PluginBitmapLoadError, _pluginType.Name, _writerPlugin.ImagePath); // set image path to null so that the "empty" image is used _writerPlugin.ImagePath = null; } } } private Regex VerifyRegex(Type pluginType, string regex) { try { return new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); } catch { throw new PluginAttributeInvalidRegexException(pluginType, regex); } } private Type _pluginType; private WriterPlugin _plugin; private SettingsPersisterHelper _settings; private static SettingsPersisterHelper _parentSettings = PostEditorSettings.SettingsKey.GetSubSettings("ContentSources"); } internal sealed class ContentSourceManager { /// <summary> /// Method that can force early initialization of the content-source manager /// so that plugin load errors occur prior to the load of the PostEditorForm /// </summary> public static void Initialize() { Initialize(null); } private static bool _loaded; public static void Initialize(bool? enablePlugins) { if (_loaded) { Debug.Fail("ContentSourceManager should not be initialized more then once per process."); return; } _loaded = true; _pluginsEnabledOverride = enablePlugins; try { if (PluginsEnabled) { PostEditorPluginManager.Init(); } // initialize content sources RefreshContentSourceLists(true); if (PluginsEnabled) { // subscribe to changed event for plugin list PostEditorPluginManager.Instance.PluginListChanged += new EventHandler(Instance_PluginListChanged); } } catch (Exception ex) { Trace.Fail("Unexptected exception initializing content-sources: " + ex.ToString()); } ContentSourceInfo[] contentSources = PluginContentSources; } internal static event EventHandler GlobalContentSourceListChanged; private static void OnGlobalContentSourceListChanged() { if (GlobalContentSourceListChanged != null) GlobalContentSourceListChanged(null, EventArgs.Empty); } private static void RefreshContentSourceLists(bool showErrors) { lock (_contentSourceListLock) { // list of built-in content sources ArrayList builtInContentSources = new ArrayList(); if (MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.VideoProviders)) AddContentSource(builtInContentSources, typeof(VideoContentSource), showErrors); if (MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.Maps)) AddContentSource(builtInContentSources, typeof(MapContentSource), showErrors); if (MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.TagProviders)) AddContentSource(builtInContentSources, typeof(TagContentSource), showErrors); AddContentSource(builtInContentSources, typeof(WebImageContentSource), showErrors); builtInContentSources.Sort(new ContentSourceInfo.NameComparer()); _builtInContentSources = builtInContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; // list of plugin content sources ArrayList pluginContentSources = new ArrayList(); if (PluginsEnabled) { Type[] pluginTypes = PostEditorPluginManager.Instance.GetPlugins(typeof(WriterPlugin)); foreach (Type type in pluginTypes) AddContentSource(pluginContentSources, type, showErrors); pluginContentSources.Sort(new ContentSourceInfo.NameComparer()); } _pluginContentSources = pluginContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; // list of all installed content sources ArrayList installedContentSources = new ArrayList(); installedContentSources.AddRange(_builtInContentSources); installedContentSources.AddRange(_pluginContentSources); _installedContentSources = installedContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; // list of active content-sources ArrayList activeContentSources = new ArrayList(); foreach (ContentSourceInfo contentSourceInfo in _installedContentSources) if (contentSourceInfo.Enabled) activeContentSources.Add(contentSourceInfo); _activeContentSources = activeContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; // list of built-in insertable content-sources ArrayList builtInInsertableContentSources = new ArrayList(); foreach (ContentSourceInfo contentSourceInfo in _builtInContentSources) if (contentSourceInfo.Enabled && contentSourceInfo.CanCreateNew) builtInInsertableContentSources.Add(contentSourceInfo); _builtInInsertableContentSources = builtInInsertableContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; // list of plugin insertable content-sources ArrayList pluginInsertableContentSources = new ArrayList(); foreach (ContentSourceInfo contentSourceInfo in _pluginContentSources) if (contentSourceInfo.Enabled && contentSourceInfo.CanCreateNew) pluginInsertableContentSources.Add(contentSourceInfo); _pluginInsertableContentSources = pluginInsertableContentSources.ToArray(typeof(ContentSourceInfo)) as ContentSourceInfo[]; } // notify listeners OnGlobalContentSourceListChanged(); } private readonly static object _contentSourceListLock = new object(); private static void Instance_PluginListChanged(object sender, EventArgs e) { RefreshContentSourceLists(false); } public static IDynamicCommandMenuContext CreateDynamicCommandMenuContext(DynamicCommandMenuOptions options, CommandManager commandManager, IContentSourceSite sourceSite) { return new ContentSourceCommandMenuContext(options, commandManager, sourceSite); } public static ContentSourceInfo[] BuiltInContentSources { get { lock (_contentSourceListLock) return _builtInContentSources; } } public static ContentSourceInfo[] PluginContentSources { get { lock (_contentSourceListLock) return _pluginContentSources; } } public static ContentSourceInfo[] InstalledContentSources { get { lock (_contentSourceListLock) return _installedContentSources; } } public static ContentSourceInfo[] ActiveContentSources { get { lock (_contentSourceListLock) return _activeContentSources; } } public static ContentSourceInfo[] BuiltInInsertableContentSources { get { lock (_contentSourceListLock) return _builtInInsertableContentSources; } } public static ContentSourceInfo[] PluginInsertableContentSources { get { lock (_contentSourceListLock) return _pluginInsertableContentSources; } } public static IEnumerable<ContentSourceInfo> EnabledPublishNotificationPlugins { get { return GetEnabledPlugins(typeof(PublishNotificationHook)); } } /// <summary> /// Gets the publish notification plugins that are enabled FOR THIS BLOG and /// also enabled globally. /// If there are any plugins that are not currently explicitly enabled/disabled, /// and owner is not null, the user will be prompted whether or not to enable a /// plugin. If not explicitly set but owner is null, the plugin will be considered /// disabled. /// </summary> public static IEnumerable<ContentSourceInfo> GetActivePublishNotificationPlugins(IWin32Window owner, string blogId) { using (BlogSettings blogSettings = BlogSettings.ForBlogId(blogId)) return GetActivePlugins(owner, EnabledPublishNotificationPlugins, blogSettings, DEFAULT_ENABLED); } public static IEnumerable<ContentSourceInfo> EnabledHeaderFooterPlugins { get { return GetEnabledPlugins(typeof(HeaderFooterSource)); } } public static IEnumerable<ContentSourceInfo> GetActiveHeaderFooterPlugins(IWin32Window owner, string blogId) { using (BlogSettings blogSettings = BlogSettings.ForBlogId(blogId)) return GetActivePlugins(owner, EnabledHeaderFooterPlugins, blogSettings, DEFAULT_ENABLED); } private const bool DEFAULT_ENABLED = false; public static Comparison<ContentSourceInfo> CreateComparison(BlogPublishingPluginSettings settings) { return delegate (ContentSourceInfo a, ContentSourceInfo b) { int orderA = settings.GetOrder(a.Id) ?? 100000; int orderB = settings.GetOrder(b.Id) ?? 100000; if (orderA != orderB) return orderA - orderB; else return a.LastUse.CompareTo(b.LastUse); }; } private static IEnumerable<ContentSourceInfo> GetEnabledPlugins(Type type) { ContentSourceInfo[] csis = ActiveContentSources; foreach (ContentSourceInfo csi in csis) { if (type.IsAssignableFrom(csi.Type)) { yield return csi; } } } private static IEnumerable<ContentSourceInfo> GetActivePlugins(IWin32Window owner, IEnumerable<ContentSourceInfo> plugins, BlogSettings blogSettings, bool defaultEnabled) { BlogPublishingPluginSettings settings = blogSettings.PublishingPluginSettings; List<ContentSourceInfo> pluginList = new List<ContentSourceInfo>(plugins); // Sort the plugins according to their determined order, and for those // without an order, sort by last use pluginList.Sort(CreateComparison(settings)); // Filter out plugins that aren't enabled for this blog. // Do this after sorting, so that if we need to prompt, we // will persist the correct order pluginList = pluginList.FindAll(delegate (ContentSourceInfo csi) { return PluginIsEnabled(owner, settings, csi, defaultEnabled); }); return pluginList; } // TODO: Instead of prompting for each one, show one consolidated dialog private static bool PluginIsEnabled(IWin32Window owner, BlogPublishingPluginSettings settings, ContentSourceInfo plugin, bool defaultEnabled) { bool? alreadyEnabled = settings.IsEnabled(plugin.Id); if (alreadyEnabled != null) return alreadyEnabled.Value; // Got here? then we haven't seen this plugin before if (owner == null) return defaultEnabled; bool enabled = DisplayMessage.Show(MessageId.ShouldUsePlugin, owner, plugin.Name) == DialogResult.Yes; settings.Set(plugin.Id, enabled, settings.KnownPluginIds.Length); return enabled; } public static ContentSourceInfo FindContentSource(Type type) { lock (_contentSourceListLock) { foreach (ContentSourceInfo contentSourceInfo in ActiveContentSources) if (contentSourceInfo.Type == type) return contentSourceInfo; // none found return null; } } public static ContentSourceInfo FindContentSource(string contentSourceId) { lock (_contentSourceListLock) { foreach (ContentSourceInfo contentSourceInfo in ActiveContentSources) if (contentSourceInfo.Id == contentSourceId) return contentSourceInfo; // none found return null; } } public static ContentSourceInfo FindContentSourceForUrl(string url) { lock (_contentSourceListLock) { foreach (ContentSourceInfo contentSourceInfo in ActiveContentSources) { if (contentSourceInfo.CanCreateFromUrl) { if (CanHandleUrl(contentSourceInfo, url)) return contentSourceInfo; } } // didn't find one return null; } } public static bool ContentSourceIsPlugin(string contentSourceId) { lock (_contentSourceListLock) { // search for a plugin with this id foreach (ContentSourceInfo contentSourceInfo in PluginContentSources) if (contentSourceInfo.Id == contentSourceId) return true; // no love return false; } } public static string MakeContainingElementId(string sourceId, string contentBlockId) { return String.Format(CultureInfo.InvariantCulture, "{0}:{1}:{2}", SMART_CONTENT_ID_PREFIX, sourceId, contentBlockId); } public static void ParseContainingElementId(string containingElementId, out string sourceId, out string contentBlockId) { if (string.IsNullOrEmpty(containingElementId)) { throw new ArgumentException("Invalid containing element id."); } string[] contentIds = containingElementId.Split(':'); if (contentIds.Length == 3 && contentIds[0] == SMART_CONTENT_ID_PREFIX) { sourceId = contentIds[1]; contentBlockId = contentIds[2]; } else if (contentIds.Length == 2) { // for legacy versions of Writer sourceId = contentIds[0]; contentBlockId = contentIds[1]; } else { throw new ArgumentException("Invalid containing element id: " + containingElementId); } } public static void PerformInsertion(IContentSourceSite sourceSite, ContentSourceInfo contentSource) { // record use of content-source (used to list source in MRU order on the sidebar) RecordContentSourceUsage(contentSource.Id); try { if (contentSource.Instance is SmartContentSource) { SmartContentSource scSource = (SmartContentSource)contentSource.Instance; IExtensionData extensionData = sourceSite.CreateExtensionData(Guid.NewGuid().ToString()); // SmartContentSource implementations *must* be stateless (see WinLive 126969), so we wrap up the // internal smart content context and pass it in as a parameter to the CreateContent call. ISmartContent sContent; if (scSource is IInternalSmartContentSource) { sContent = new InternalSmartContent(extensionData, sourceSite as IInternalSmartContentContextSource, contentSource.Id); } else { sContent = new SmartContent(extensionData); } if (scSource.CreateContent(sourceSite.DialogOwner, sContent) == DialogResult.OK) { string content = scSource.GenerateEditorHtml(sContent, sourceSite); if (content != null) { sourceSite.InsertContent(contentSource.Id, content, extensionData); sourceSite.Focus(); if (ApplicationPerformance.ContainsEvent(MediaInsertForm.EventName)) ApplicationPerformance.EndEvent(MediaInsertForm.EventName); } } } else if (contentSource.Instance is ContentSource) { ContentSource sSource = (ContentSource)contentSource.Instance; string newContent = String.Empty; // default try { if (sourceSite.SelectedHtml != null) newContent = sourceSite.SelectedHtml; } catch { } // safely try to provide selected html if (sSource.CreateContent(sourceSite.DialogOwner, ref newContent) == DialogResult.OK) { sourceSite.InsertContent(newContent, contentSource.Id == WebImageContentSource.ID); sourceSite.Focus(); } } } catch (Exception ex) { DisplayContentRetreivalError(sourceSite.DialogOwner, ex, contentSource); } } /// <summary> /// Returns true if the element className is a structured block. /// </summary> /// <param name="elementClassName"></param> /// <returns></returns> public static bool IsSmartContentClass(string elementClassName) { if (elementClassName == SMART_CONTENT || elementClassName == EDITABLE_SMART_CONTENT) { return true; } return false; } /// <summary> /// Returns true if the element exists in a structured block. /// </summary> /// <param name="element"></param> /// <returns></returns> public static bool IsSmartContent(IHTMLElement element) { while (element != null) { if (IsSmartContentClass(element.className)) { return true; } element = element.parentElement; } return false; } public static IHTMLElement GetContainingSmartContent(IHTMLElement element) { while (element != null) { if (IsSmartContentClass(element.className)) return element; element = element.parentElement; } return null; } /// <summary> /// Returns true if the element is a structured block. /// </summary> public static bool IsSmartContentContainer(IHTMLElement element) { if (element == null) return false; return IsSmartContentClass(element.className); } public static IHTMLElement GetContainingSmartContentElement(MarkupRange range) { IHTMLElement containingSmartContent = range.ParentElement(IsSmartContentContainer); if (containingSmartContent != null) { return containingSmartContent; } else { IHTMLElement[] elements = range.GetTopLevelElements(MarkupRange.FilterNone); if (elements.Length == 1 && IsSmartContent(elements[0])) { return elements[0]; } } return null; } public static string[] GetSmartContentIds(MarkupRange range) { ArrayList ids = new ArrayList(); foreach (IHTMLElement el in range.GetElements(new IHTMLElementFilter(IsSmartContentContainer), false)) { if (el.id != null) ids.Add(el.id); } return (string[])ids.ToArray(typeof(string)); } public static bool ContainsSmartContentFromSource(string contentSourceId, MarkupRange range) { string[] contentIds = GetSmartContentIds(range); foreach (string contentId in contentIds) { string sourceId; string contentBlockId; ParseContainingElementId(contentId, out sourceId, out contentBlockId); if (sourceId == contentSourceId) return true; } // if we got this far then there are no tags return false; } public class SmartContentPredicate : IElementPredicate { public bool IsMatch(Element e) { BeginTag bt = e as BeginTag; if (bt == null) return false; return IsSmartContentClass(bt.GetAttributeValue("class")); } } public static void DisplayContentRetreivalError(IWin32Window dialogOwner, Exception ex, ContentSourceInfo info) { if (ex is ContentCreationException) { ContentCreationException ccEx = ex as ContentCreationException; DisplayableExceptionDisplayForm.Show(dialogOwner, new DisplayableException(ccEx.Title, ccEx.Description)); } else if (ex is NotImplementedException) { DisplayableExceptionDisplayForm.Show(dialogOwner, new DisplayableException( Res.Get(StringId.MethodNotImplemented), String.Format(CultureInfo.InvariantCulture, Res.Get(StringId.MethodNotImplementedDetail), info.Name, info.WriterPluginPublisherUrl, ex.Message))); } else { DisplayableExceptionDisplayForm.Show(dialogOwner, ex); } } //note that these strings are also used within the BlogPostRegionLocatorStrategy class. Changes // here should be made there as well (used for detecting smart content when updating weblog style) public const string SMART_CONTENT = "wlWriterSmartContent"; public const string EDITABLE_SMART_CONTENT = "wlWriterEditableSmartContent"; public const string HEADERS_FOOTERS = "wlWriterHeaderFooter"; public const string SMART_CONTENT_ID_PREFIX = "scid"; public const string SMART_CONTENT_CONTAINER = "wlwScContainer"; public class SmartContentElementFilter { public bool Filter(IHTMLElement e) { return (e is IHTMLDivElement) && ((e.className == ContentSourceManager.SMART_CONTENT) || (e.className == ContentSourceManager.EDITABLE_SMART_CONTENT)); } } public static IHTMLElementFilter CreateSmartContentElementFilter() { return new IHTMLElementFilter(new SmartContentElementFilter().Filter); } public static void RemoveSmartContentAttributes(BeginTag beginTag) { if (beginTag == null) throw new ArgumentNullException("beginTag"); Attr classAttr = beginTag.GetAttribute("class"); // Remove the SmartContent classes. if (classAttr != null) { classAttr.Value = classAttr.Value.Replace(EDITABLE_SMART_CONTENT, string.Empty); classAttr.Value = classAttr.Value.Replace(SMART_CONTENT, string.Empty); } // Remove contentEditable=true so that the user can edit it manually. beginTag.RemoveAttribute("contentEditable"); } private static void AddContentSource(ArrayList contentSourceList, Type contentSourceType, bool showErrors) { try { contentSourceList.Add(new ContentSourceInfo(contentSourceType, showErrors)); } catch (WriterContentPluginAttributeMissingException) { // this exception is OK (allows for ContentSource base-class which doesn't implement an actual plugin) } catch (ArgumentException ex) { if (showErrors) DisplayMessage.Show(MessageId.PluginInvalidAttribute, contentSourceType.Name, ex.ParamName, ex.Message); } catch (Exception ex) { if (showErrors) DisplayMessage.Show(MessageId.PluginUnexpectedLoadError, contentSourceType.Name, ex.Message); } } private static bool CanHandleUrl(ContentSourceInfo contentSource, string url) { try { if (typeof(IHandlesMultipleUrls).IsAssignableFrom(contentSource.Type)) { IHandlesMultipleUrls plugin = (IHandlesMultipleUrls)Activator.CreateInstance(contentSource.Type); return plugin.HasUrlMatch(url); } Regex regex = new Regex(contentSource.UrlContentSourceUrlPattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); return regex.IsMatch(url); } catch { return false; } } private static bool? _pluginsEnabledOverride; private static bool PluginsEnabled { get { if (_pluginsEnabledOverride != null) return _pluginsEnabledOverride.Value; string commandLine = Environment.CommandLine; if (commandLine != null) return commandLine.ToLower(CultureInfo.InvariantCulture).IndexOf("/noplugins") == -1; return true; } } private static void RecordContentSourceUsage(string sourceId) { foreach (ContentSourceInfo contentSourceId in ActiveContentSources) { if (contentSourceId.Id == sourceId) { contentSourceId.LastUse = DateTime.Now; return; } } } private static ContentSourceInfo[] _builtInContentSources; private static ContentSourceInfo[] _pluginContentSources; private static ContentSourceInfo[] _installedContentSources; private static ContentSourceInfo[] _activeContentSources; private static ContentSourceInfo[] _builtInInsertableContentSources; private static ContentSourceInfo[] _pluginInsertableContentSources; internal static ContentSourceInfo GetContentSourceInfoById(string Id) { foreach (ContentSourceInfo contentSourceInfo in _installedContentSources) { if (contentSourceInfo.Id == Id) { return contentSourceInfo; } } return null; } } internal class ContentSourceCommand : Command, IMenuCommandObject { public ContentSourceCommand(IContentSourceSite sourceSite, ContentSourceInfo contentSourceInfo, bool isBuiltInPlugin) { // copy references _insertionSite = sourceSite; _contentSourceInfo = contentSourceInfo; // tie this command to the content-source for execution // (we don't initialize other properties b/c this Command // is only use for decoupled lookup & execution not for // UI display. If we actually want to display this command // on a command bar, etc. we should fill in the other properties. this.Identifier = contentSourceInfo.Id; // For built in plugins, we will get these values from the ribbon if (contentSourceInfo.CanCreateNew && !isBuiltInPlugin) { this.MenuText = ((IMenuCommandObject)this).Caption; this.CommandBarButtonBitmapEnabled = contentSourceInfo.Image; } } Bitmap IMenuCommandObject.Image { get { return _contentSourceInfo.Image; } } string IMenuCommandObject.Caption { get { return String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.WithEllipses), _contentSourceInfo.InsertableContentSourceMenuText); } } string IMenuCommandObject.CaptionNoMnemonic { get { return String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.WithEllipses), _contentSourceInfo.InsertableContentSourceSidebarText); } } bool IMenuCommandObject.Enabled { get { return _insertionSite.InsertCommandsEnabled; } } bool IMenuCommandObject.Latched { get { return false; } } protected override void OnExecute(EventArgs e) { base.OnExecute(e); if (_insertionSite.InsertCommandsEnabled) { ContentSourceManager.PerformInsertion(_insertionSite, _contentSourceInfo); } else { DisplayMessage.Show(MessageId.CannotInsert, _insertionSite.DialogOwner, _contentSourceInfo.InsertableContentSourceSidebarText); } } private IContentSourceSite _insertionSite; private ContentSourceInfo _contentSourceInfo; } internal class ContentSourceCommandMenuContext : IDynamicCommandMenuContext { public ContentSourceCommandMenuContext(DynamicCommandMenuOptions options, CommandManager commandManager, IContentSourceSite sourceSite) { _options = options; _commandManager = commandManager; _insertionSite = sourceSite; } public DynamicCommandMenuOptions Options { get { return _options; } } private DynamicCommandMenuOptions _options; public CommandManager CommandManager { get { return _commandManager; } } private CommandManager _commandManager; public IMenuCommandObject[] GetMenuCommandObjects() { ArrayList menuCommandObjects = new ArrayList(); // list built-in sources first foreach (ContentSourceInfo _contentSourceInfo in ContentSourceManager.BuiltInInsertableContentSources) { if (_contentSourceInfo.Id == WebImageContentSource.ID) continue; Command command = CommandManager.Get(_contentSourceInfo.Id); if (command != null) menuCommandObjects.Add(command); } // then plugin sources foreach (ContentSourceInfo _contentSourceInfo in ContentSourceManager.PluginInsertableContentSources) { Command command = CommandManager.Get(_contentSourceInfo.Id); if (command != null) menuCommandObjects.Add(command); } return menuCommandObjects.ToArray(typeof(IMenuCommandObject)) as IMenuCommandObject[]; } public void CommandExecuted(IMenuCommandObject menuCommandObject) { (menuCommandObject as ContentSourceCommand).PerformExecute(); } private IContentSourceSite _insertionSite; } internal class PluginAttributeException : ApplicationException { } internal class PluginAttributeFieldMissingException : PluginAttributeException { public PluginAttributeFieldMissingException(Type pluginType, Type attributeType, string attributeFieldName) { _pluginType = pluginType; _attributeType = attributeType; _attributeFieldName = attributeFieldName; } public override string Message { get { return String.Format(CultureInfo.CurrentCulture, "Plugin {0} is missing the \"{1}\" field of the {2}.", _pluginType.Name, _attributeFieldName, _attributeType.Name); } } private Type _pluginType; private Type _attributeType; private string _attributeFieldName; } internal abstract class PluginAttributeImageResourceException : PluginAttributeException { public PluginAttributeImageResourceException(Type pluginType, string imageResourcePath) { _pluginType = pluginType; _imageResourcePath = imageResourcePath; } protected Type _pluginType; protected string _imageResourcePath; } internal class PluginAttributeImageResourceMissingException : PluginAttributeImageResourceException { public PluginAttributeImageResourceMissingException(Type pluginType, string imageResourcePath) : base(pluginType, imageResourcePath) { } public override string Message { get { return String.Format(CultureInfo.CurrentCulture, "Unable to load image resource {0} for Plugin {1}.", _imageResourcePath, _pluginType.Name); } } } internal class PluginAttributeImageResourceWrongSizeException : PluginAttributeImageResourceException { public PluginAttributeImageResourceWrongSizeException(Type pluginType, string imageResourcePath) : base(pluginType, imageResourcePath) { } public override string Message { get { return String.Format(CultureInfo.CurrentCulture, "Image resource {0} for Plugin {1} is the wrong size (Plugin images must be {2}x{3}).", _imageResourcePath, _pluginType.Name, ContentSourceInfo.IMAGE_WIDTH, ContentSourceInfo.IMAGE_HEIGHT); } } } internal class PluginAttributeInvalidRegexException : PluginAttributeException { public PluginAttributeInvalidRegexException(Type pluginType, string regex) { _pluginType = pluginType; _regex = regex; } public override string Message { get { return String.Format(CultureInfo.CurrentCulture, "Invalid regular expression for Plugin {0} ({1}).", _pluginType.Name, _regex); } } private Type _pluginType; private string _regex; } internal class WriterContentPluginAttributeMissingException : PluginAttributeException { public WriterContentPluginAttributeMissingException(Type pluginType) { _pluginType = pluginType; } public override string Message { get { return String.Format(CultureInfo.CurrentCulture, "The Plugin {0} does not have the required attributes. Content source plugins must include the WriterPlugin attribute as well as one or more of the InsertableContentSource, UrlContentSource, or LiveClipbaordContentSource attributes.", _pluginType.Name); } } private Type _pluginType; } }
using System; using System.Reflection; /* * Regression tests for the mono JIT. * * Each test needs to be of the form: * * static int test_<result>_<name> (); * * where <result> is an integer (the value that needs to be returned by * the method to make it pass. * <name> is a user-displayed name used to identify the test. * * The tests can be driven in two ways: * *) running the program directly: Main() uses reflection to find and invoke * the test methods (this is useful mostly to check that the tests are correct) * *) with the --regression switch of the jit (this is the preferred way since * all the tests will be run with optimizations on and off) * * The reflection logic could be moved to a .dll since we need at least another * regression test file written in IL code to have better control on how * the IL code looks. */ class Tests { static int Main (string[] args) { return TestDriver.RunTests (typeof (Tests), args); } static public int test_0_many_nested_loops () { // we do the loop a few times otherwise it's too fast for (int i = 0; i < 5; ++i) { int n = 16; int x = 0; int a = n; while (a-- != 0) { int b = n; while (b-- != 0) { int c = n; while (c-- != 0) { int d = n; while (d-- != 0) { int e = n; while (e-- != 0) { int f = n; while (f-- != 0) { x++; } } } } } } if (x != 16777216) return 1; } return 0; } public static int test_0_logic_run () { // GPL: Copyright (C) 2001 Southern Storm Software, Pty Ltd. int iter, i = 0; while (i++ < 10) { // Initialize. bool flag1 = true; bool flag2 = true; bool flag3 = true; bool flag4 = true; bool flag5 = true; bool flag6 = true; bool flag7 = true; bool flag8 = true; bool flag9 = true; bool flag10 = true; bool flag11 = true; bool flag12 = true; bool flag13 = true; // First set of tests. for(iter = 0; iter < 2000000; ++iter) { if((flag1 || flag2) && (flag3 || flag4) && (flag5 || flag6 || flag7)) { flag8 = !flag8; flag9 = !flag9; flag10 = !flag10; flag11 = !flag11; flag12 = !flag12; flag13 = !flag13; flag1 = !flag1; flag2 = !flag2; flag3 = !flag3; flag4 = !flag4; flag5 = !flag5; flag6 = !flag6; flag1 = !flag1; flag2 = !flag2; flag3 = !flag3; flag4 = !flag4; flag5 = !flag5; flag6 = !flag6; } } } return 0; } static public int test_1028_sieve () { //int NUM = ((argc == 2) ? atoi(argv[1]) : 1); int NUM = 2000; byte[] flags = new byte[8192 + 1]; int i, k; int count = 0; while (NUM-- != 0) { count = 0; for (i=2; i <= 8192; i++) { flags[i] = 1; } for (i=2; i <= 8192; i++) { if (flags[i] != 0) { // remove all multiples of prime: i for (k=i+i; k <= 8192; k+=i) { flags[k] = 0; } count++; } } } //printf("Count: %d\n", count); return(count); } public static int fib (int n) { if (n < 2) return 1; return fib(n-2)+fib(n-1); } public static int test_3524578_fib () { for (int i = 0; i < 10; i++) fib (32); return fib (32); } private static ulong numMoves; static void movetower (int disc, int from, int to, int use) { if (disc > 0) { numMoves++; movetower (disc-1, from, use, to); movetower (disc-1, use, to, from); } } public static int test_0_hanoi () { int iterations = 5000; int numdiscs = 12; numMoves = 0; while (iterations > 0) { iterations--; movetower (numdiscs, 1, 3, 2); } if (numMoves != 20475000) return 1; return 0; } public static int test_0_castclass () { object a = "a"; for (int i = 0; i < 100000000; i++) { string b = (string)a; if ((object)a != (object)b) return 1; } return 0; } public static int test_23005000_float () { double a, b, c, d; bool val; int loops = 0; a = 0.0; b = 0.0001; c = 2300.5; d = 1000.0; while (a < c) { if (a == d) b *= 2; a += b; val = b >= c; if (val) break; loops++; } return loops; } /* /// Gaussian blur of a generated grayscale picture private int test_0_blur(int size) { const int num = 5; // Number of time to blur byte[,] arr1 = new byte[size, size]; byte[,] arr2 = new byte[size, size]; int iterations = 1; while(iterations-- > 0) { // Draw fake picture for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { arr1[i, j] = (byte) (i%255); } } for(int n = 0; n < num; n++) { // num rounds of blurring for(int i = 3; i < size-3; i++) // vertical blur arr1 -> arr2 for(int j = 0; j < size; j++) arr2[i, j] = (byte)((arr1[i-3, j] + arr1[i+3, j] + 6*(arr1[i-2, j]+arr1[i+2, j]) + 15*(arr1[i-1, j]+arr1[i+1, j]) + 20*arr1[i, j] + 32)>>6); for(int j = 3; j < size-3; j++) // horizontal blur arr1 -> arr2 for(int i = 0; i < size; i++) arr1[i, j] = (byte)((arr2[i, j-3] + arr2[i, j+3] + 6*(arr2[i, j-2]+arr2[i, j+2]) + 15*(arr2[i, j-1]+arr2[i, j+1]) + 20*arr2[i, j] + 32)>>6); } } return 0; } */ }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Threading; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Logging; using QuantConnect.Packets; using System.Threading.Tasks; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Data.Custom; using QuantConnect.Data.Market; using System.Collections.Generic; using QuantConnect.Configuration; using QuantConnect.Data.Custom.Tiingo; using QuantConnect.Lean.Engine.Results; using QuantConnect.Data.UniverseSelection; using QuantConnect.Lean.Engine.DataFeeds.Enumerators; using QuantConnect.Lean.Engine.DataFeeds.Enumerators.Factories; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides an implementation of <see cref="IDataFeed"/> that is designed to deal with /// live, remote data sources /// </summary> public class LiveTradingDataFeed : IDataFeed { private LiveNodePacket _job; // used to get current time private ITimeProvider _timeProvider; private ITimeProvider _frontierTimeProvider; private IDataProvider _dataProvider; private IMapFileProvider _mapFileProvider; private IDataQueueHandler _dataQueueHandler; private BaseDataExchange _customExchange; private SubscriptionCollection _subscriptions; private IFactorFileProvider _factorFileProvider; private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private IDataChannelProvider _channelProvider; /// <summary> /// Public flag indicator that the thread is still busy. /// </summary> public bool IsActive { get; private set; } /// <summary> /// Initializes the data feed for the specified job and algorithm /// </summary> public void Initialize(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider, IDataProvider dataProvider, IDataFeedSubscriptionManager subscriptionManager, IDataFeedTimeProvider dataFeedTimeProvider, IDataChannelProvider dataChannelProvider) { if (!(job is LiveNodePacket)) { throw new ArgumentException("The LiveTradingDataFeed requires a LiveNodePacket."); } _cancellationTokenSource = new CancellationTokenSource(); _job = (LiveNodePacket)job; _timeProvider = dataFeedTimeProvider.TimeProvider; _dataProvider = dataProvider; _mapFileProvider = mapFileProvider; _factorFileProvider = factorFileProvider; _channelProvider = dataChannelProvider; _frontierTimeProvider = dataFeedTimeProvider.FrontierTimeProvider; _customExchange = new BaseDataExchange("CustomDataExchange") { SleepInterval = 10 }; _subscriptions = subscriptionManager.DataFeedSubscriptions; _dataQueueHandler = GetDataQueueHandler(); _dataQueueHandler?.SetJob(_job); // run the custom data exchange var manualEvent = new ManualResetEventSlim(false); Task.Factory.StartNew(() => { manualEvent.Set(); _customExchange.Start(_cancellationTokenSource.Token); }, TaskCreationOptions.LongRunning); manualEvent.Wait(); manualEvent.DisposeSafely(); IsActive = true; } /// <summary> /// Creates a new subscription to provide data for the specified security. /// </summary> /// <param name="request">Defines the subscription to be added, including start/end times the universe and security</param> /// <returns>The created <see cref="Subscription"/> if successful, null otherwise</returns> public Subscription CreateSubscription(SubscriptionRequest request) { // create and add the subscription to our collection var subscription = request.IsUniverseSubscription ? CreateUniverseSubscription(request) : CreateDataSubscription(request); return subscription; } /// <summary> /// Removes the subscription from the data feed, if it exists /// </summary> /// <param name="subscription">The subscription to remove</param> public void RemoveSubscription(Subscription subscription) { var symbol = subscription.Configuration.Symbol; // remove the subscriptions if (!_channelProvider.ShouldStreamSubscription(subscription.Configuration)) { _customExchange.RemoveEnumerator(symbol); _customExchange.RemoveDataHandler(symbol); } else { _dataQueueHandler.UnsubscribeWithMapping(subscription.Configuration); if (subscription.Configuration.SecurityType == SecurityType.Equity && !subscription.Configuration.IsInternalFeed) { _dataQueueHandler.UnsubscribeWithMapping(new SubscriptionDataConfig(subscription.Configuration, typeof(Dividend))); _dataQueueHandler.UnsubscribeWithMapping(new SubscriptionDataConfig(subscription.Configuration, typeof(Split))); } } } /// <summary> /// External controller calls to signal a terminate of the thread. /// </summary> public virtual void Exit() { if (IsActive) { IsActive = false; Log.Trace("LiveTradingDataFeed.Exit(): Start. Setting cancellation token..."); _cancellationTokenSource.Cancel(); _customExchange?.Stop(); Log.Trace("LiveTradingDataFeed.Exit(): Exit Finished."); } } /// <summary> /// Gets the <see cref="IDataQueueHandler"/> to use by default <see cref="DataQueueHandlerManager"/> /// </summary> /// <remarks>Useful for testing</remarks> /// <returns>The loaded <see cref="IDataQueueHandler"/></returns> protected virtual IDataQueueHandler GetDataQueueHandler() { return new DataQueueHandlerManager(); } /// <summary> /// Creates a new subscription for the specified security /// </summary> /// <param name="request">The subscription request</param> /// <returns>A new subscription instance of the specified security</returns> protected Subscription CreateDataSubscription(SubscriptionRequest request) { Subscription subscription = null; try { var localEndTime = request.EndTimeUtc.ConvertFromUtc(request.Security.Exchange.TimeZone); var timeZoneOffsetProvider = new TimeZoneOffsetProvider(request.Configuration.ExchangeTimeZone, request.StartTimeUtc, request.EndTimeUtc); IEnumerator<BaseData> enumerator; if (!_channelProvider.ShouldStreamSubscription(request.Configuration)) { if (!Tiingo.IsAuthCodeSet) { // we're not using the SubscriptionDataReader, so be sure to set the auth token here Tiingo.SetAuthCode(Config.Get("tiingo-auth-token")); } var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider); var enumeratorStack = factory.CreateEnumerator(request, _dataProvider); _customExchange.AddEnumerator(request.Configuration.Symbol, enumeratorStack); var enqueable = new EnqueueableEnumerator<BaseData>(); _customExchange.SetDataHandler(request.Configuration.Symbol, data => { enqueable.Enqueue(data); subscription.OnNewDataAvailable(); }); enumerator = enqueable; } else { var auxEnumerators = new List<IEnumerator<BaseData>>(); if (LiveAuxiliaryDataEnumerator.TryCreate(request.Configuration, _timeProvider, _dataQueueHandler, request.Security.Cache, _mapFileProvider, _factorFileProvider, request.StartTimeLocal, out var auxDataEnumator)) { auxEnumerators.Add(auxDataEnumator); } EventHandler handler = (_, _) => subscription?.OnNewDataAvailable(); enumerator = Subscribe(request.Configuration, handler); if (request.Configuration.EmitSplitsAndDividends()) { auxEnumerators.Add(Subscribe(new SubscriptionDataConfig(request.Configuration, typeof(Dividend)), handler)); auxEnumerators.Add(Subscribe(new SubscriptionDataConfig(request.Configuration, typeof(Split)), handler)); } if (auxEnumerators.Count > 0) { enumerator = new LiveAuxiliaryDataSynchronizingEnumerator(_timeProvider, request.Configuration.ExchangeTimeZone, enumerator, auxEnumerators); } } // scale prices before 'SubscriptionFilterEnumerator' since it updates securities realtime price // and before fill forwarding so we don't happen to apply twice the factor if (request.Configuration.PricesShouldBeScaled(liveMode:true)) { enumerator = new PriceScaleFactorEnumerator( enumerator, request.Configuration, _factorFileProvider, liveMode:true); } if (request.Configuration.FillDataForward) { var fillForwardResolution = _subscriptions.UpdateAndGetFillForwardResolution(request.Configuration); enumerator = new LiveFillForwardEnumerator(_frontierTimeProvider, enumerator, request.Security.Exchange, fillForwardResolution, request.Configuration.ExtendedMarketHours, localEndTime, request.Configuration.Increment, request.Configuration.DataTimeZone); } // define market hours and user filters to incoming data if (request.Configuration.IsFilteredSubscription) { enumerator = new SubscriptionFilterEnumerator(enumerator, request.Security, localEndTime, request.Configuration.ExtendedMarketHours, true, request.ExchangeHours); } // finally, make our subscriptions aware of the frontier of the data feed, prevents future data from spewing into the feed enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, timeZoneOffsetProvider); var subscriptionDataEnumerator = new SubscriptionDataEnumerator(request.Configuration, request.Security.Exchange.Hours, timeZoneOffsetProvider, enumerator, request.IsUniverseSubscription); subscription = new Subscription(request, subscriptionDataEnumerator, timeZoneOffsetProvider); } catch (Exception err) { Log.Error(err); } return subscription; } private IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { return new LiveSubscriptionEnumerator(dataConfig, _dataQueueHandler, newDataAvailableHandler); } /// <summary> /// Creates a new subscription for universe selection /// </summary> /// <param name="request">The subscription request</param> private Subscription CreateUniverseSubscription(SubscriptionRequest request) { Subscription subscription = null; // TODO : Consider moving the creating of universe subscriptions to a separate, testable class // grab the relevant exchange hours var config = request.Universe.Configuration; var localEndTime = request.EndTimeUtc.ConvertFromUtc(request.Security.Exchange.TimeZone); var tzOffsetProvider = new TimeZoneOffsetProvider(request.Configuration.ExchangeTimeZone, request.StartTimeUtc, request.EndTimeUtc); IEnumerator<BaseData> enumerator = null; var timeTriggered = request.Universe as ITimeTriggeredUniverse; if (timeTriggered != null) { Log.Trace($"LiveTradingDataFeed.CreateUniverseSubscription(): Creating user defined universe: {config.Symbol.ID}"); // spoof a tick on the requested interval to trigger the universe selection function var enumeratorFactory = new TimeTriggeredUniverseSubscriptionEnumeratorFactory(timeTriggered, MarketHoursDatabase.FromDataFolder(), _frontierTimeProvider); enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider); enumerator = new FrontierAwareEnumerator(enumerator, _timeProvider, tzOffsetProvider); var enqueueable = new EnqueueableEnumerator<BaseData>(); _customExchange.AddEnumerator(new EnumeratorHandler(config.Symbol, enumerator, enqueueable)); enumerator = enqueueable; } else if (config.Type == typeof(CoarseFundamental) || config.Type == typeof(ETFConstituentData)) { Log.Trace($"LiveTradingDataFeed.CreateUniverseSubscription(): Creating {config.Type.Name} universe: {config.Symbol.ID}"); // Will try to pull data from the data folder every 10min, file with yesterdays date. // If lean is started today it will trigger initial coarse universe selection var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider, // we adjust time to the previous tradable date time => Time.GetStartTimeForTradeBars(request.Security.Exchange.Hours, time, Time.OneDay, 1, false, config.DataTimeZone), TimeSpan.FromMinutes(10) ); var enumeratorStack = factory.CreateEnumerator(request, _dataProvider); // aggregates each coarse data point into a single BaseDataCollection var aggregator = new BaseDataCollectionAggregatorEnumerator(enumeratorStack, config.Symbol, true); _customExchange.AddEnumerator(config.Symbol, aggregator); var enqueable = new EnqueueableEnumerator<BaseData>(); _customExchange.SetDataHandler(config.Symbol, data => { enqueable.Enqueue(data); subscription.OnNewDataAvailable(); }); enumerator = GetConfiguredFrontierAwareEnumerator(enqueable, tzOffsetProvider, // advance time if before 23pm or after 5am and not on Saturdays time => time.Hour < 23 && time.Hour > 5 && time.DayOfWeek != DayOfWeek.Saturday); } else if (request.Universe is OptionChainUniverse) { Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating option chain universe: " + config.Symbol.ID); Func<SubscriptionRequest, IEnumerator<BaseData>> configure = (subRequest) => { var fillForwardResolution = _subscriptions.UpdateAndGetFillForwardResolution(subRequest.Configuration); var input = Subscribe(subRequest.Configuration, (sender, args) => subscription.OnNewDataAvailable()); return new LiveFillForwardEnumerator(_frontierTimeProvider, input, subRequest.Security.Exchange, fillForwardResolution, subRequest.Configuration.ExtendedMarketHours, localEndTime, subRequest.Configuration.Increment, subRequest.Configuration.DataTimeZone); }; var symbolUniverse = GetUniverseProvider(SecurityType.Option); var enumeratorFactory = new OptionChainUniverseSubscriptionEnumeratorFactory(configure, symbolUniverse, _timeProvider); enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider); enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, tzOffsetProvider); } else if (request.Universe is FuturesChainUniverse) { Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating futures chain universe: " + config.Symbol.ID); var symbolUniverse = GetUniverseProvider(SecurityType.Option); var enumeratorFactory = new FuturesChainUniverseSubscriptionEnumeratorFactory(symbolUniverse, _timeProvider); enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider); enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, tzOffsetProvider); } else { Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating custom universe: " + config.Symbol.ID); var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider); var enumeratorStack = factory.CreateEnumerator(request, _dataProvider); enumerator = new BaseDataCollectionAggregatorEnumerator(enumeratorStack, config.Symbol, liveMode: true); var enqueueable = new EnqueueableEnumerator<BaseData>(); _customExchange.AddEnumerator(new EnumeratorHandler(config.Symbol, enumerator, enqueueable)); enumerator = enqueueable; } // create the subscription var subscriptionDataEnumerator = new SubscriptionDataEnumerator(request.Configuration, request.Security.Exchange.Hours, tzOffsetProvider, enumerator, request.IsUniverseSubscription); subscription = new Subscription(request, subscriptionDataEnumerator, tzOffsetProvider); // send the subscription for the new symbol through to the data queuehandler if (_channelProvider.ShouldStreamSubscription(subscription.Configuration)) { Subscribe(request.Configuration, (sender, args) => subscription.OnNewDataAvailable()); } return subscription; } /// <summary> /// Will wrap the provided enumerator with a <see cref="FrontierAwareEnumerator"/> /// using a <see cref="PredicateTimeProvider"/> that will advance time based on the provided /// function /// </summary> /// <remarks>Won't advance time if now.Hour is bigger or equal than 23pm, less or equal than 5am or Saturday. /// This is done to prevent universe selection occurring in those hours so that the subscription changes /// are handled correctly.</remarks> private IEnumerator<BaseData> GetConfiguredFrontierAwareEnumerator( IEnumerator<BaseData> enumerator, TimeZoneOffsetProvider tzOffsetProvider, Func<DateTime, bool> customStepEvaluator) { var stepTimeProvider = new PredicateTimeProvider(_frontierTimeProvider, customStepEvaluator); return new FrontierAwareEnumerator(enumerator, stepTimeProvider, tzOffsetProvider); } private IDataQueueUniverseProvider GetUniverseProvider(SecurityType securityType) { if (_dataQueueHandler is not IDataQueueUniverseProvider or DataQueueHandlerManager { HasUniverseProvider: false }) { throw new NotSupportedException($"The DataQueueHandler does not support {securityType}."); } return (IDataQueueUniverseProvider)_dataQueueHandler; } /// <summary> /// Overrides methods of the base data exchange implementation /// </summary> private class EnumeratorHandler : BaseDataExchange.EnumeratorHandler { private readonly EnqueueableEnumerator<BaseData> _enqueueable; public EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, EnqueueableEnumerator<BaseData> enqueueable) : base(symbol, enumerator, true) { _enqueueable = enqueueable; } /// <summary> /// Returns true if this enumerator should move next /// </summary> public override bool ShouldMoveNext() { return true; } /// <summary> /// Calls stop on the internal enqueueable enumerator /// </summary> public override void OnEnumeratorFinished() { _enqueueable.Stop(); } /// <summary> /// Enqueues the data /// </summary> /// <param name="data">The data to be handled</param> public override void HandleData(BaseData data) { _enqueueable.Enqueue(data); } } } }
using System; using System.Runtime.InteropServices; using CorDebugInterop; using System.Diagnostics; using System.Collections; using nanoFramework.Tools.Debugger; namespace nanoFramework.Tools.VisualStudio.Debugger.MetaData { public class MetaDataImport : IMetaDataImport2, IMetaDataAssemblyImport { private readonly CorDebugAssembly m_assembly; private readonly Engine m_engine; private readonly Guid m_guidModule; private IntPtr m_fakeSig; private readonly int m_cbFakeSig; private ArrayList m_alEnums; private int m_handleEnumNext = 1; private bool m_fAlert = false; public MetaDataImport (CorDebugAssembly assembly) { m_assembly = assembly; m_engine = m_assembly.Process.Engine; m_guidModule = Guid.NewGuid (); m_alEnums = new ArrayList(); byte[] fakeSig = new byte[] { (byte)CorCallingConvention.IMAGE_CEE_CS_CALLCONV_DEFAULT, 0x0 /*count of params*/, (byte)CorElementType.ELEMENT_TYPE_VOID}; m_cbFakeSig = fakeSig.Length; m_fakeSig = Marshal.AllocCoTaskMem (m_cbFakeSig); Marshal.Copy (fakeSig, 0, m_fakeSig, m_cbFakeSig); } ~MetaDataImport () { Marshal.FreeCoTaskMem (m_fakeSig); } [Conditional("DEBUG")] private void NotImpl() { Debug.Assert(!m_fAlert, "IMDI NotImpl"); } private class HCorEnum { public int m_handle; public int[] m_tokens; public int m_iToken; public HCorEnum(int handle, int[] tokens) { m_handle = handle; m_tokens = tokens; m_iToken = 0; } public int Reset(uint uPos) { m_iToken = (int)uPos; return COM_HResults.S_OK; } public int Count { get { return m_tokens.Length; } } public int Enum(IntPtr dest, uint cMax, IntPtr pct) { int cItems = Math.Min((int)cMax, this.Count - m_iToken); Marshal.WriteInt32(pct, cItems); Marshal.Copy(m_tokens, m_iToken, pct, cItems); m_iToken += cItems; return COM_HResults.S_OK; } } private HCorEnum CreateEnum(int[] tokens) { HCorEnum hce = new HCorEnum(m_handleEnumNext, tokens); m_alEnums.Add(hce); m_handleEnumNext++; return hce; } private HCorEnum HCorEnumFromHandle(int handle) { foreach (HCorEnum hce in m_alEnums) { if (hce.m_handle == handle) return hce; } return null; } private int EnumNoTokens( IntPtr phEnum, IntPtr pcTokens ) { int[] tokens = new int[0]; HCorEnum hce = CreateEnum( tokens ); if( phEnum != IntPtr.Zero ) Marshal.WriteInt32( phEnum, hce.m_handle ); if( pcTokens != IntPtr.Zero ) Marshal.WriteInt32( pcTokens, 0 ); return COM_HResults.S_OK; } #region IMetaDataImport2 Members public int EnumGenericParams (IntPtr phEnum, uint tk, IntPtr rGenericParams, uint cMax, IntPtr pcGenericParams) { return EnumNoTokens( phEnum, pcGenericParams ); } public int GetGenericParamProps (uint gp, IntPtr pulParamSeq, IntPtr pdwParamFlags, IntPtr ptOwner, IntPtr ptkKind, IntPtr wzName, uint cchName, IntPtr pchName) { // MetaDataImport.GetGenericParamProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMethodSpecProps (uint mi, IntPtr tkParent, IntPtr ppvSigBlob, IntPtr pcbSigBlob) { // MetaDataImport.GetMethodSpecProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumGenericParamConstraints (IntPtr phEnum, uint tk, IntPtr rGenericParamConstraints, uint cMax, IntPtr pcGenericParamConstraints) { return EnumNoTokens( phEnum, pcGenericParamConstraints ); } public int GetGenericParamConstraintProps (uint gpc, IntPtr ptGenericParam, IntPtr ptkConstraintType) { // MetaDataImport.GetGenericParamConstraintProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPEKind (IntPtr pdwPEKind, IntPtr pdwMAchine) { // MetaDataImport.GetPEKind is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetVersionString (IntPtr pwzBuf, int ccBufSize, IntPtr pccBufSize) { // MetaDataImport.GetVersionString is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMethodSpecs(IntPtr phEnum, uint tk, IntPtr rMethodSpecs, uint cMax, IntPtr pcMethodSpecs) { return EnumNoTokens( phEnum, pcMethodSpecs ); } #endregion #region IMetaDataImport/IMetaDataAssemblyImport Members public void CloseEnum (IntPtr hEnum) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); if (hce != null) m_alEnums.Remove(hce); } #endregion #region IMetaDataImport Members public int CountEnum (IntPtr hEnum, IntPtr pulCount) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); Marshal.WriteInt32(pulCount, hce.Count); return COM_HResults.S_OK; } public int ResetEnum (IntPtr hEnum, uint ulPos) { HCorEnum hce = HCorEnumFromHandle(hEnum.ToInt32()); return hce.Reset(ulPos); } public int EnumTypeDefs (IntPtr phEnum, IntPtr rTypeDefs, uint cMax, IntPtr pcTypeDefs) { return EnumNoTokens( phEnum, pcTypeDefs ); } public int EnumInterfaceImpls (IntPtr phEnum, uint td, IntPtr rImpls, uint cMax, IntPtr pcImpls) { return EnumNoTokens( phEnum, pcImpls ); } public int EnumTypeRefs (IntPtr phEnum, IntPtr rTypeRefs, uint cMax, IntPtr pcTypeRefs) { return EnumNoTokens( phEnum, pcTypeRefs ); } public int FindTypeDefByName (string szTypeDef, uint tkEnclosingClass, IntPtr mdTypeDef) { // MetaDataImport.FindTypeDefByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetScopeProps (IntPtr szName, uint cchName, IntPtr pchName, IntPtr pmvid) { // MetaDataImport.GetScopeProps is not implemented m_assembly.ICorDebugAssembly.GetName (cchName, pchName, szName); if (pmvid != IntPtr.Zero) { byte [] guidModule = m_guidModule.ToByteArray(); Marshal.Copy (guidModule, 0, pmvid, guidModule.Length); } return COM_HResults.S_OK; } public int GetModuleFromScope (IntPtr pmd) { // MetaDataImport.GetModuleFromScope is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, IntPtr pchTypeDef, IntPtr pdwTypeDefFlags, IntPtr ptkExtends) { uint tk = nanoCLR_TypeSystem.SymbollessSupport.nanoCLRTokenFromTypeDefToken(td); uint index = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken (td, m_assembly); var getTypeName = m_engine.GetTypeNameAsync(index); getTypeName.Wait(); string name = getTypeName.Result; Utility.MarshalString (name, cchTypeDef, pchTypeDef, szTypeDef); Utility.MarshalInt (pchTypeDef, 0); Utility.MarshalInt (pdwTypeDefFlags, 0); Utility.MarshalInt (ptkExtends, 0); return COM_HResults.S_OK; } public int GetInterfaceImplProps (uint iiImpl, IntPtr pClass, IntPtr ptkIface) { // MetaDataImport.GetInterfaceImplProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetTypeRefProps (uint tr, IntPtr ptkResolutionScope, IntPtr szName, uint cchName, IntPtr pchName) { // MetaDataImport.GetTypeRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int ResolveTypeRef (uint tr, IntPtr riid, ref object ppIScope, IntPtr ptd) { // MetaDataImport.ResolveTypeRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMembers (IntPtr phEnum, uint cl, IntPtr rMembers, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMembersWithName (IntPtr phEnum, uint cl, string szName, IntPtr rMembers, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethods (IntPtr phEnum, uint cl, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethodsWithName (IntPtr phEnum, uint cl, string szName, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFields (IntPtr phEnum, uint cl, IntPtr rFields, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFieldsWithName (IntPtr phEnum, uint cl, string szName, IntPtr rFields, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumParams (IntPtr phEnum, uint mb, IntPtr rParams, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMemberRefs (IntPtr phEnum, uint tkParent, IntPtr rMemberRefs, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumMethodImpls (IntPtr phEnum, uint td, IntPtr rMethodBody, IntPtr rMethodDecl, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumPermissionSets (IntPtr phEnum, uint tk, int dwActions, IntPtr rPermission, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int FindMember (uint td, string szName, IntPtr pvSigBlob, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindMember is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindMethod (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindMethod is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindField (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmb) { // MetaDataImport.FindField is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindMemberRef (uint td, string szName, IntPtr pvSigBlog, uint cbSigBlob, IntPtr pmr) { // MetaDataImport.FindMemberRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMethodProps (uint mb, IntPtr pClass, IntPtr szMethod, uint cchMethod, IntPtr pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA, IntPtr pdwImplFlags) { uint tk = nanoCLR_TypeSystem.SymbollessSupport.nanoCLRTokenFromMethodDefToken (mb); uint md = nanoCLR_TypeSystem.ClassMemberIndexFromnanoCLRToken (tk, m_assembly); var resolveMethod = m_engine.ResolveMethodAsync(md); resolveMethod.Wait(); Debugger.WireProtocol.Commands.Debugging_Resolve_Method.Result resolvedMethod = resolveMethod.Result; string name = null; uint tkClass = 0; if (resolvedMethod != null) { name = resolvedMethod.m_name; uint tkType = nanoCLR_TypeSystem.nanoCLRTokenFromTypeIndex (resolvedMethod.m_td); tkClass = nanoCLR_TypeSystem.SymbollessSupport.TypeDefTokenFromnanoCLRToken (tkType); } Utility.MarshalString (name, cchMethod, pchMethod, szMethod); Utility.MarshalInt (pClass, (int)tkClass); Utility.MarshalInt(pdwAttr, (int)CorMethodAttr.mdStatic); Utility.MarshalInt(pulCodeRVA, 0); Utility.MarshalInt(pdwImplFlags, 0); Utility.MarshalInt(pcbSigBlob, m_cbFakeSig); Utility.MarshalInt(ppvSigBlob, m_fakeSig.ToInt32 ()); return COM_HResults.S_OK; } public int GetMemberRefProps (uint mr, IntPtr ptk, IntPtr szMember, uint cchMember, IntPtr pchMember, IntPtr ppvSigBlob, IntPtr pcbSigBlob) { // MetaDataImport.GetMemberRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumProperties (IntPtr phEnum, uint td, IntPtr rProperties, uint cMax, IntPtr pcProperties) { return EnumNoTokens( phEnum, pcProperties ); } public int EnumEvents (IntPtr phEnum, uint td, IntPtr rEvents, uint cMax, IntPtr pcEvents) { return EnumNoTokens( phEnum, pcEvents ); } public int GetEventProps (uint ev, IntPtr pClass, IntPtr szEvent, uint cchEvent, IntPtr pchEvent, IntPtr pdwEventFlags, IntPtr ptkEventType, IntPtr pmdAddOn, IntPtr pmdRemoveOn, IntPtr pmdFire, IntPtr rmdOtherMethod, uint cMax, IntPtr pcOtherMethod) { // MetaDataImport.GetEventProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumMethodSemantics (IntPtr phEnum, uint mb, IntPtr rEventProp, uint cMax, IntPtr pcEventProp) { return EnumNoTokens( phEnum, pcEventProp ); } public int GetMethodSemantics (uint mb, uint tkEventProp, IntPtr pdwSemanticFlags) { // MetaDataImport.GetMethodSemantics is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetClassLayout (uint td, IntPtr pdwPackSize, IntPtr rFieldOffset, uint cMax, IntPtr pcFieldOffset, IntPtr pulClassSize) { // MetaDataImport.GetClassLayour is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFieldMarshal (uint tk, IntPtr ppvNativeType, IntPtr pcbNativeType) { // MetaDataImport.GetFieldMarshal is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetRVA (uint tk, IntPtr pulCodeRVA, IntPtr pdwImplFlags) { // MetaDataImport.GetRVA is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPermissionSetProps (uint pm, IntPtr pdwAction, IntPtr ppvPermission, IntPtr pcbPermission) { // MetaDataImport.GetPermissionSetProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetSigFromToken (uint mdSig, IntPtr ppvSig, IntPtr pcbSig) { // MetaDataImport.GetSigFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetModuleRefProps (uint mur, IntPtr szName, uint cchName, IntPtr pchName) { // MetaDataImport.GetModuleRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumModuleRefs (IntPtr phEnum, IntPtr rModuleRefs, uint cmax, IntPtr pcModuleRefs) { return EnumNoTokens( phEnum, pcModuleRefs ); } public int GetTypeSpecFromToken (uint typespec, IntPtr ppvSig, IntPtr pcbSig) { // MetaDataImport.GetTypeSpecFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNameFromToken (uint tk, IntPtr pszUtf8NamePtr) { // MetaDataImport.GetNameFromToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumUnresolvedMethods (IntPtr phEnum, IntPtr rMethods, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int GetUserString (uint stk, IntPtr szString, uint cchString, IntPtr pchString) { // MetaDataImport.GetUserString is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPinvokeMap (uint tk, IntPtr pdwMappingFlags, IntPtr szImportName, uint cchImportName, IntPtr pchImportName, IntPtr pmrImportDLL) { // MetaDataImport.GetPinvokeMap is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumSignatures (IntPtr phEnum, IntPtr rSignatures, uint cmax, IntPtr pcSignatures) { return EnumNoTokens( phEnum, pcSignatures ); } public int EnumTypeSpecs (IntPtr phEnum, IntPtr rTypeSpecs, uint cmax, IntPtr pcTypeSpecs) { return EnumNoTokens( phEnum, pcTypeSpecs ); } public int EnumUserStrings (IntPtr phEnum, IntPtr rStrings, uint cmax, IntPtr pcStrings) { return EnumNoTokens( phEnum, pcStrings ); } public int GetParamForMethodIndex (uint md, uint ulParamSeq, IntPtr ppd) { // MetaDataImport.GetParamForMethodIndex is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumUserStrings (IntPtr phEnum, uint tk, uint tkType, IntPtr rCustomAttributes, uint cMax, IntPtr pcCustomAttributes) { return EnumNoTokens( phEnum, pcCustomAttributes ); } public int GetCustomAttributeProps (uint cv, IntPtr ptkObj, IntPtr ptkType, IntPtr ppBlob, IntPtr pcbSize) { return COM_HResults.S_FALSE; } public int FindTypeRef (uint tkResolutionScope, string szName, IntPtr ptr) { // MetaDataImport.FindTypeRef is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetMemberProps (uint mb, IntPtr pClass, IntPtr szMember, uint cchMember, IntPtr pchMember, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA, IntPtr pdwImplFlags, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetMemberProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFieldProps (uint mb, IntPtr pClass, IntPtr szField, uint cchField, IntPtr pchField, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetFieldProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetPropertyProps (uint prop, IntPtr pClass, IntPtr szProperty, uint cchProperty, IntPtr pchProperty, IntPtr pdwPropFlags, IntPtr ppvSig, IntPtr pbSig, IntPtr pdwCPlusTypeFlag, IntPtr ppDefaultValue, IntPtr pcchDefaultValue, IntPtr pmdSetter, IntPtr pmdGetter, IntPtr rmdOtherMethod, uint cMax, IntPtr pcOtherMethod) { // MetaDataImport.GetPropertyProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetParamProps (uint tk, IntPtr pmd, IntPtr pulSequence, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pdwAttr, IntPtr pdwCPlusTypeFlag, IntPtr ppValue, IntPtr pcchValue) { // MetaDataImport.GetParamProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetCustomAttributeByName (uint tkObj, string szName, IntPtr ppData, IntPtr pcbData) { // MetaDataImport.GetCustomAttributeByName is not implemented return COM_HResults.E_NOTIMPL; } public int IsValidToken (uint tk) { // MetaDataImport.IsValidToken is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNestedClassProps (uint tdNestedClass, IntPtr ptdEnclosingClass) { // MetaDataImport.GetNestedClassProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig, IntPtr pCallConv) { // MetaDataImport.GetNativeCallConvFromSig is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int IsGlobal (uint pd, IntPtr pbGlobal) { // MetaDataImport.IsGlobal is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } #endregion #region IMetaDataAssemblyImport Members public int GetAssemblyProps (uint mda, IntPtr ppbPublicKey, IntPtr pcbPublicKey, IntPtr pulHashAlgId, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pMetaData, IntPtr pdwAssemblyFlags) { m_assembly.ICorDebugAssembly.GetName(cchName, pchName, szName); return COM_HResults.S_OK; } public int GetAssemblyRefProps (uint mdar, IntPtr ppbPublicKeyOrToken, IntPtr pcbPublicKeyOrToken, IntPtr szName, uint cchName, IntPtr pchName, IntPtr pMetaData, IntPtr ppbHashValue, IntPtr pcbHashValue, IntPtr pdwAssemblyRefFlags) { // MetaDataImport.GetAssemblyRefProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetFileProps (uint mdf, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ppbHashValue, IntPtr pcbHashValue, IntPtr pdwFileFlags) { // MetaDataImport.GetFileProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetExportedTypeProps (uint mdct, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ptkImplementation, IntPtr ptkTypeDef, IntPtr pdwExportedTypeFlags) { // MetaDataImport.GetExportedTypeProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetManifestResourceProps (uint mdmr, IntPtr szName, uint cchName, IntPtr pchName, IntPtr ptkImplementation, IntPtr pdwOffset, IntPtr pdwResourceFlags) { // MetaDataImport.GetManifestResourceProps is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int EnumAssemblyRefs (IntPtr phEnum, IntPtr rAssemblyRefs, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumFiles (IntPtr phEnum, IntPtr rFiles, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumExportedTypes (IntPtr phEnum, IntPtr rExportedTypes, uint cMax, IntPtr pcTokens) { return EnumNoTokens( phEnum, pcTokens ); } public int EnumManifestResources (IntPtr phEnum, IntPtr rManifestResources, uint cMax, IntPtr pcTokens) { // MetaDataImport.EnumManifestResources is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int GetAssemblyFromScope (IntPtr ptkAssembly) { //Only one assembly per MetaDataImport, doesn't matter what token we give them back return COM_HResults.E_NOTIMPL; } public int FindExportedTypeByName (string szName, uint mdtExportedType, IntPtr ptkExportedType) { // MetaDataImport.FindExportedTypeByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindManifestResourceByName (string szName, IntPtr ptkManifestResource) { // MetaDataImport.FindManifestResourceByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } public int FindAssembliesByName (string szAppBase, string szPrivateBin, string szAssemblyName, IntPtr ppIUnk, uint cMax, IntPtr pcAssemblies) { // MetaDataImport.FindAssembliesByName is not implemented NotImpl(); return COM_HResults.E_NOTIMPL; } #endregion } }
using System; using Audit.Core; using System.Threading.Tasks; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using System.Collections.Generic; using System.Collections.Concurrent; namespace Audit.DynamoDB.Providers { /// <summary> /// Amazon DynamoDB data provider for Audit.NET. Store the audit events into DynamoDB tables. /// </summary> public class DynamoDataProvider : AuditDataProvider { private static readonly ConcurrentDictionary<string, Table> TableCache = new ConcurrentDictionary<string, Table>(); /// <summary> /// Top-level attributes to be added to the event and document before saving /// </summary> public Dictionary<string, Func<AuditEvent, object>> CustomAttributes { get; set; } = new Dictionary<string, Func<AuditEvent, object>>(); /// <summary> /// Factory that creates the client /// </summary> public Lazy<IAmazonDynamoDB> Client { get; set; } /// <summary> /// The DynamoDB table name to use when saving an audit event. /// </summary> public Func<AuditEvent, string> TableNameBuilder { get; set; } /// <summary> /// Creates a new DynamoDB data provider using the given client. /// </summary> /// <param name="client">The amazon DynamoDB client instance</param> public DynamoDataProvider(IAmazonDynamoDB client) { Client = new Lazy<IAmazonDynamoDB>(() => client); } /// <summary> /// Creates a new DynamoDB data provider using the given client. /// </summary> /// <param name="client">The amazon DynamoDB client instance</param> public DynamoDataProvider(AmazonDynamoDBClient client) { Client = new Lazy<IAmazonDynamoDB>(() => client); } /// <summary> /// Creates a new DynamoDB data provider. /// </summary> public DynamoDataProvider() { } /// <summary> /// Creates a new DynamoDB data provider with the given configuration options. /// </summary> public DynamoDataProvider(Action<Configuration.IDynamoProviderConfigurator> config) { var dynaDbConfig = new Configuration.DynamoProviderConfigurator(); if (config != null) { config.Invoke(dynaDbConfig); Client = dynaDbConfig._clientFactory; TableNameBuilder = dynaDbConfig._tableConfigurator?._tableNameBuilder; CustomAttributes = dynaDbConfig._tableConfigurator?._attrConfigurator?._attributes; } } /// <summary> /// Inserts an event into DynamoDB /// </summary> public override object InsertEvent(AuditEvent auditEvent) { var table = GetTable(auditEvent); var document = CreateDocument(auditEvent, true); table.PutItemAsync(document).GetAwaiter().GetResult(); return GetKeyValues(document, table); } /// <summary> /// Asynchronously inserts an event into DynamoDB /// </summary> public override async Task<object> InsertEventAsync(AuditEvent auditEvent) { var table = GetTable(auditEvent); var document = CreateDocument(auditEvent, true); await table.PutItemAsync(document); return GetKeyValues(document, table); } /// <summary> /// Replaces an event into DynamoDB /// </summary> public override void ReplaceEvent(object eventId, AuditEvent auditEvent) { var table = GetTable(auditEvent); var document = CreateDocument(auditEvent, false); table.PutItemAsync(document).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously replaces an event into DynamoDB /// </summary> public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent) { var table = GetTable(auditEvent); var document = CreateDocument(auditEvent, false); await table.PutItemAsync(document); } /// <summary> /// Gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="hashKey">The primary key Hash portion</param> /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param> public T GetEvent<T>(Primitive hashKey, Primitive rangeKey) where T : AuditEvent { var table = GetTable(null); Document doc; if (rangeKey == null) { doc = table.GetItemAsync(hashKey).GetAwaiter().GetResult(); } else { doc = table.GetItemAsync(hashKey, rangeKey).GetAwaiter().GetResult(); } return AuditEvent.FromJson<T>(doc.ToJson()); } /// <summary> /// Gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="hashKey">The primary key Hash portion</param> /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param> public async Task<T> GetEventAsync<T>(Primitive hashKey, Primitive rangeKey) where T : AuditEvent { var table = GetTable(null); Document doc; if (rangeKey == null) { doc = await table.GetItemAsync(hashKey); } else { doc = await table.GetItemAsync(hashKey, rangeKey); } return AuditEvent.FromJson<T>(doc.ToJson()); } /// <summary> /// Gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="hashKey">The primary key Hash portion</param> /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param> public T GetEvent<T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey) where T : AuditEvent { return GetEvent<T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive()); } /// <summary> /// Asynchronously gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="hashKey">The primary key Hash portion</param> /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param> public async Task<T> GetEventAsync<T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey) where T : AuditEvent { return await GetEventAsync<T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive()); } /// <summary> /// Gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="eventId">The event ID to retrieve. /// Must be a Primitive, a DynamoDBEntry or an array of any of these two types. The first (or only) element must be the Hash key, and the second element is the range key. /// </param> public override T GetEvent<T>(object eventId) { if (eventId == null) { return null; } if (eventId is Primitive[] keys) { return GetEvent<T>(keys[0], keys.Length > 1 ? keys[1] : null); } if (eventId is Primitive key) { return GetEvent<T>(key, null); } if (eventId is DynamoDBEntry[] ekeys) { return GetEvent<T>(ekeys[0], ekeys.Length > 1 ? ekeys[1] : null); } if (eventId is DynamoDBEntry ekey) { return GetEvent<T>(ekey, null); } throw new ArgumentException("Parameter must be convertible to Primitive, Primitive[], DynamoDBEntry or DynamoDBEntry[]", "eventId"); } /// <summary> /// Asynchronously gets an audit event from its primary key /// </summary> /// <typeparam name="T">The audit event type</typeparam> /// <param name="eventId">The event ID to retrieve. /// Must be a Primitive, a DynamoDBEntry or an array of any of these two types. The first (or only) element must be the Hash key, and the second element is the range key. /// </param> public override async Task<T> GetEventAsync<T>(object eventId) { if (eventId == null) { return null; } if (eventId is Primitive[] keys) { return await GetEventAsync<T>(keys[0], keys.Length > 1 ? keys[1] : null); } if (eventId is Primitive key) { return await GetEventAsync<T>(key, null); } if (eventId is DynamoDBEntry[] ekeys) { return await GetEventAsync<T>(ekeys[0], ekeys.Length > 1 ? ekeys[1] : null); } if (eventId is DynamoDBEntry ekey) { return await GetEventAsync<T>(ekey, null); } throw new ArgumentException("Parameter must be convertible to Primitive, Primitive[], DynamoDBEntry or DynamoDBEntry[]", "eventId"); } private Table GetTable(AuditEvent auditEvent) { var tableName = TableNameBuilder?.Invoke(auditEvent) ?? auditEvent?.GetType().Name ?? "AuditEvent"; if (TableCache.TryGetValue(tableName, out Table table)) { return table; } table = Table.LoadTable(Client.Value, tableName); TableCache[tableName] = table; return table; } private Primitive[] GetKeyValues(Document document, Table table) { var keyValues = new List<Primitive>() { document[table.HashKeys[0]].AsPrimitive() }; if (table.RangeKeys.Count > 0) { keyValues.Add(document[table.RangeKeys[0]].AsPrimitive()); } return keyValues.ToArray(); } private Document CreateDocument(AuditEvent auditEvent, bool addCustomFields) { if (addCustomFields && CustomAttributes != null) { foreach (var attrib in CustomAttributes) { auditEvent.CustomFields[attrib.Key] = attrib.Value.Invoke(auditEvent); } } return Document.FromJson(auditEvent.ToJson()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Microsoft.Azure.KeyVault { using System.Threading; using System.Threading.Tasks; using Models; using System.Net.Http; using Rest.Azure; using System.Collections.Generic; using Rest; using System; using System.Net; using Rest.Serialization; using Newtonsoft.Json; using System.Linq; using Microsoft.Azure.KeyVault.Customized.Authentication; /// <summary> /// Client class to perform cryptographic key operations and vault /// operations against the Key Vault service. /// </summary> public partial class KeyVaultClient { /// <summary> /// The authentication callback delegate which is to be implemented by the client code /// </summary> /// <param name="authority"> Identifier of the authority, a URL. </param> /// <param name="resource"> Identifier of the target resource that is the recipient of the requested token, a URL. </param> /// <param name="scope"> The scope of the authentication request. </param> /// <returns> access token </returns> public delegate Task<string> AuthenticationCallback(string authority, string resource, string scope); /// <summary> /// Constructor /// </summary> /// <param name="authenticationCallback">The authentication callback</param> /// <param name='handlers'>Optional. The delegating handlers to add to the http client pipeline.</param> public KeyVaultClient(AuthenticationCallback authenticationCallback, params DelegatingHandler[] handlers) : this(new KeyVaultCredential(authenticationCallback), handlers) { } /// <summary> /// Constructor /// </summary> /// <param name="authenticationCallback">The authentication callback</param> /// <param name="httpClient">Customized HTTP client </param> public KeyVaultClient(AuthenticationCallback authenticationCallback, HttpClient httpClient) : this(new KeyVaultCredential(authenticationCallback), httpClient) { } /// <summary> /// Constructor /// </summary> /// <param name="credential">Credential for key vault operations</param> /// <param name="httpClient">Customized HTTP client </param> public KeyVaultClient(KeyVaultCredential credential, HttpClient httpClient) // clone the KeyVaultCredential to ensure the instance is only used by this client since it // will use this client's HttpClient for unauthenticated calls to retrieve the auth challange : this(credential.Clone()) { base.HttpClient = httpClient; } /// <summary> /// Gets the pending certificate signing request response. /// </summary> /// <param name='vaultBaseUrl'> /// The vault name, e.g. https://myvault.vault.azure.net /// </param> /// <param name='certificateName'> /// The name of the certificate /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<string>> GetPendingCertificateSigningRequestWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultBaseUrl == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultBaseUrl"); } if (certificateName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "certificateName"); } if (this.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("vaultBaseUrl", vaultBaseUrl); tracingParameters.Add("certificateName", certificateName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPendingCertificateSigningRequest", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "certificates/{certificate-name}/pending"; _url = _url.Replace("{vaultBaseUrl}", vaultBaseUrl); _url = _url.Replace("{certificate-name}", Uri.EscapeDataString(certificateName)); List<string> _queryParameters = new List<string>(); if (this.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); _httpRequest.Headers.Add("Accept", "application/pkcs10"); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new KeyVaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); KeyVaultError _errorBody = SafeJsonConvert.DeserializeObject<KeyVaultError>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<string>(); _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) { _result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Overrides the base <see cref="CreateHttpHandlerPipeline"/> to add a <see cref="ChallengeCacheHandler"/> as the outermost <see cref="DelegatingHandler"/>. /// </summary> /// <param name="httpClientHandler">The base handler for the client</param> /// <param name="handlers">The handler pipeline for the client</param> /// <returns></returns> protected override DelegatingHandler CreateHttpHandlerPipeline(HttpClientHandler httpClientHandler, params DelegatingHandler[] handlers) { var challengeCacheHandler = new ChallengeCacheHandler(); challengeCacheHandler.InnerHandler = base.CreateHttpHandlerPipeline(httpClientHandler, handlers); return challengeCacheHandler; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Sockets; using System.Text; namespace System.Net { /// <summary> /// <para> /// Implements basic sending and receiving of network commands. /// Handles generic parsing of server responses and provides /// a pipeline sequencing mechanism for sending the commands to the server. /// </para> /// </summary> internal class CommandStream : NetworkStreamWrapper { private static readonly AsyncCallback s_writeCallbackDelegate = new AsyncCallback(WriteCallback); private static readonly AsyncCallback s_readCallbackDelegate = new AsyncCallback(ReadCallback); private bool _recoverableFailure; // // Active variables used for the command state machine // protected WebRequest _request; protected bool _isAsync; private bool _aborted; protected PipelineEntry[] _commands; protected int _index; private bool _doRead; private bool _doSend; private ResponseDescription _currentResponseDescription; protected string _abortReason; private const int WaitingForPipeline = 1; private const int CompletedPipeline = 2; internal CommandStream(TcpClient client) : base(client) { _decoder = _encoding.GetDecoder(); } internal virtual void Abort(Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "closing control Stream"); lock (this) { if (_aborted) return; _aborted = true; } try { base.Close(0); } finally { if (e != null) { InvokeRequestCallback(e); } else { InvokeRequestCallback(null); } } } protected override void Dispose(bool disposing) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); InvokeRequestCallback(null); // Do not call base.Dispose(bool), which would close the web request. // This stream effectively should be a wrapper around a web // request that does not own the web request. } protected void InvokeRequestCallback(object obj) { WebRequest webRequest = _request; if (webRequest != null) { FtpWebRequest ftpWebRequest = (FtpWebRequest)webRequest; ftpWebRequest.RequestCallback(obj); } } internal bool RecoverableFailure { get { return _recoverableFailure; } } protected void MarkAsRecoverableFailure() { if (_index <= 1) { _recoverableFailure = true; } } internal Stream SubmitRequest(WebRequest request, bool isAsync, bool readInitalResponseOnConnect) { ClearState(); PipelineEntry[] commands = BuildCommandsList(request); InitCommandPipeline(request, commands, isAsync); if (readInitalResponseOnConnect) { _doSend = false; _index = -1; } return ContinueCommandPipeline(); } protected virtual void ClearState() { InitCommandPipeline(null, null, false); } protected virtual PipelineEntry[] BuildCommandsList(WebRequest request) { return null; } protected Exception GenerateException(string message, WebExceptionStatus status, Exception innerException) { return new WebException( message, innerException, status, null /* no response */ ); } protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException) { return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)), innerException, WebExceptionStatus.ProtocolError, null); } protected void InitCommandPipeline(WebRequest request, PipelineEntry[] commands, bool isAsync) { _commands = commands; _index = 0; _request = request; _aborted = false; _doRead = true; _doSend = true; _currentResponseDescription = null; _isAsync = isAsync; _recoverableFailure = false; _abortReason = string.Empty; } internal void CheckContinuePipeline() { if (_isAsync) return; try { ContinueCommandPipeline(); } catch (Exception e) { Abort(e); } } /// Pipelined command resolution. /// How this works: /// A list of commands that need to be sent to the FTP server are spliced together into an array, /// each command such STOR, PORT, etc, is sent to the server, then the response is parsed into a string, /// with the response, the delegate is called, which returns an instruction (either continue, stop, or read additional /// responses from server). protected Stream ContinueCommandPipeline() { // In async case, The BeginWrite can actually result in a // series of synchronous completions that eventually close // the connection. So we need to save the members that // we need to access, since they may not be valid after // BeginWrite returns bool isAsync = _isAsync; while (_index < _commands.Length) { if (_doSend) { if (_index < 0) throw new InternalException(); byte[] sendBuffer = Encoding.GetBytes(_commands[_index].Command); if (NetEventSource.Log.IsEnabled()) { string sendCommand = _commands[_index].Command.Substring(0, _commands[_index].Command.Length - 2); if (_commands[_index].HasFlag(PipelineEntryFlags.DontLogParameter)) { int index = sendCommand.IndexOf(' '); if (index != -1) sendCommand = string.Concat(sendCommand.AsSpan(0, index), " ********"); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Sending command {sendCommand}"); } try { if (isAsync) { BeginWrite(sendBuffer, 0, sendBuffer.Length, s_writeCallbackDelegate, this); } else { Write(sendBuffer, 0, sendBuffer.Length); } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } if (isAsync) { return null; } } Stream stream = null; bool isReturn = PostSendCommandProcessing(ref stream); if (isReturn) { return stream; } } lock (this) { Close(); } return null; } private bool PostSendCommandProcessing(ref Stream stream) { if (_doRead) { // In async case, the next call can actually result in a // series of synchronous completions that eventually close // the connection. So we need to save the members that // we need to access, since they may not be valid after the // next call returns bool isAsync = _isAsync; int index = _index; PipelineEntry[] commands = _commands; try { ResponseDescription response = ReceiveCommandResponse(); if (isAsync) { return true; } _currentResponseDescription = response; } catch { // If we get an exception on the QUIT command (which is // always the last command), ignore the final exception // and continue with the pipeline regardlss of sync/async if (index < 0 || index >= commands.Length || commands[index].Command != "QUIT\r\n") throw; } } return PostReadCommandProcessing(ref stream); } private bool PostReadCommandProcessing(ref Stream stream) { if (_index >= _commands.Length) return false; // Set up front to prevent a race condition on result == PipelineInstruction.Pause _doSend = false; _doRead = false; PipelineInstruction result; PipelineEntry entry; if (_index == -1) entry = null; else entry = _commands[_index]; // Final QUIT command may get exceptions since the connection // may be already closed by the server. So there is no response // to process, just advance the pipeline to continue. if (_currentResponseDescription == null && entry.Command == "QUIT\r\n") result = PipelineInstruction.Advance; else result = PipelineCallback(entry, _currentResponseDescription, false, ref stream); if (result == PipelineInstruction.Abort) { Exception exception; if (_abortReason != string.Empty) exception = new WebException(_abortReason); else exception = GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); Abort(exception); throw exception; } else if (result == PipelineInstruction.Advance) { _currentResponseDescription = null; _doSend = true; _doRead = true; _index++; } else if (result == PipelineInstruction.Pause) { // PipelineCallback did an async operation and will have to re-enter again. // Hold on for now. return true; } else if (result == PipelineInstruction.GiveStream) { // We will have another response coming, don't send _currentResponseDescription = null; _doRead = true; if (_isAsync) { // If they block in the requestcallback we should still continue the pipeline ContinueCommandPipeline(); InvokeRequestCallback(stream); } return true; } else if (result == PipelineInstruction.Reread) { // Another response is expected after this one _currentResponseDescription = null; _doRead = true; } return false; } internal enum PipelineInstruction { Abort, // aborts the pipeline Advance, // advances to the next pipelined command Pause, // Let async callback to continue the pipeline Reread, // rereads from the command socket GiveStream, // returns with open data stream, let stream close to continue } [Flags] internal enum PipelineEntryFlags { UserCommand = 0x1, GiveDataStream = 0x2, CreateDataConnection = 0x4, DontLogParameter = 0x8 } internal class PipelineEntry { internal PipelineEntry(string command) { Command = command; } internal PipelineEntry(string command, PipelineEntryFlags flags) { Command = command; Flags = flags; } internal bool HasFlag(PipelineEntryFlags flags) { return (Flags & flags) != 0; } internal string Command; internal PipelineEntryFlags Flags; } protected virtual PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { return PipelineInstruction.Abort; } // // I/O callback methods // private static void ReadCallback(IAsyncResult asyncResult) { ReceiveState state = (ReceiveState)asyncResult.AsyncState; try { Stream stream = (Stream)state.Connection; int bytesRead = 0; try { bytesRead = stream.EndRead(asyncResult); if (bytesRead == 0) state.Connection.CloseSocket(); } catch (IOException) { state.Connection.MarkAsRecoverableFailure(); throw; } catch { throw; } state.Connection.ReceiveCommandResponseCallback(state, bytesRead); } catch (Exception e) { state.Connection.Abort(e); } } private static void WriteCallback(IAsyncResult asyncResult) { CommandStream connection = (CommandStream)asyncResult.AsyncState; try { try { connection.EndWrite(asyncResult); } catch (IOException) { connection.MarkAsRecoverableFailure(); throw; } catch { throw; } Stream stream = null; if (connection.PostSendCommandProcessing(ref stream)) return; connection.ContinueCommandPipeline(); } catch (Exception e) { connection.Abort(e); } } // // Read parsing methods and privates // private string _buffer = string.Empty; private Encoding _encoding = Encoding.UTF8; private Decoder _decoder; protected Encoding Encoding { get { return _encoding; } set { _encoding = value; _decoder = _encoding.GetDecoder(); } } /// <summary> /// This function is implemented in a derived class to determine whether a response is valid, and when it is complete. /// </summary> protected virtual bool CheckValid(ResponseDescription response, ref int validThrough, ref int completeLength) { return false; } /// <summary> /// Kicks off an asynchronous or sync request to receive a response from the server. /// Uses the Encoding <code>encoding</code> to transform the bytes received into a string to be /// returned in the GeneralResponseDescription's StatusDescription field. /// </summary> private ResponseDescription ReceiveCommandResponse() { // These are the things that will be needed to maintain state. ReceiveState state = new ReceiveState(this); try { // If a string of nonzero length was decoded from the buffered bytes after the last complete response, then we // will use this string as our first string to append to the response StatusBuffer, and we will // forego a Connection.Receive here. if (_buffer.Length > 0) { ReceiveCommandResponseCallback(state, -1); } else { int bytesRead; try { if (_isAsync) { BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state); return null; } else { bytesRead = Read(state.Buffer, 0, state.Buffer.Length); if (bytesRead == 0) CloseSocket(); ReceiveCommandResponseCallback(state, bytesRead); } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } } } catch (Exception e) { if (e is WebException) throw; throw GenerateException(SR.net_ftp_receivefailure, WebExceptionStatus.ReceiveFailure, e); } return state.Resp; } /// <summary> /// ReceiveCommandResponseCallback is the main "while loop" of the ReceiveCommandResponse function family. /// In general, what is does is perform an EndReceive() to complete the previous retrieval of bytes from the /// server (unless it is using a buffered response) It then processes what is received by using the /// implementing class's CheckValid() function, as described above. If the response is complete, it returns the single complete /// response in the GeneralResponseDescription created in BeginReceiveComamndResponse, and buffers the rest as described above. /// /// If the response is not complete, it issues another Connection.BeginReceive, with callback ReceiveCommandResponse2, /// so the action will continue at the next invocation of ReceiveCommandResponse2. /// </summary> private void ReceiveCommandResponseCallback(ReceiveState state, int bytesRead) { // completeLength will be set to a nonnegative number by CheckValid if the response is complete: // it will set completeLength to the length of a complete response. int completeLength = -1; while (true) { int validThrough = state.ValidThrough; // passed to checkvalid // If we have a Buffered response (ie data was received with the last response that was past the end of that response) // deal with it as if we had just received it now instead of actually doing another receive if (_buffer.Length > 0) { // Append the string we got from the buffer, and flush it out. state.Resp.StatusBuffer.Append(_buffer); _buffer = string.Empty; // invoke checkvalid. if (!CheckValid(state.Resp, ref validThrough, ref completeLength)) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } } else // we did a Connection.BeginReceive. Note that in this case, all bytes received are in the receive buffer (because bytes from // the buffer were transferred there if necessary { // this indicates the connection was closed. if (bytesRead <= 0) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } // decode the bytes in the receive buffer into a string, append it to the statusbuffer, and invoke checkvalid. // Decoder automatically takes care of caching partial codepoints at the end of a buffer. char[] chars = new char[_decoder.GetCharCount(state.Buffer, 0, bytesRead)]; int numChars = _decoder.GetChars(state.Buffer, 0, bytesRead, chars, 0, false); string szResponse = new string(chars, 0, numChars); state.Resp.StatusBuffer.Append(szResponse); if (!CheckValid(state.Resp, ref validThrough, ref completeLength)) { throw GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } // If the response is complete, then determine how many characters are left over...these bytes need to be set into Buffer. if (completeLength >= 0) { int unusedChars = state.Resp.StatusBuffer.Length - completeLength; if (unusedChars > 0) { _buffer = szResponse.Substring(szResponse.Length - unusedChars, unusedChars); } } } // Now, in general, if the response is not complete, update the "valid through" length for the efficiency of checkValid, // and perform the next receive. // Note that there may NOT be bytes in the beginning of the receive buffer (even if there were partial characters left over after the // last encoding), because they get tracked in the Decoder. if (completeLength < 0) { state.ValidThrough = validThrough; try { if (_isAsync) { BeginRead(state.Buffer, 0, state.Buffer.Length, s_readCallbackDelegate, state); return; } else { bytesRead = Read(state.Buffer, 0, state.Buffer.Length); if (bytesRead == 0) CloseSocket(); continue; } } catch (IOException) { MarkAsRecoverableFailure(); throw; } catch { throw; } } // The response is completed break; } // Otherwise, we have a complete response. string responseString = state.Resp.StatusBuffer.ToString(); state.Resp.StatusDescription = responseString.Substring(0, completeLength); // Set the StatusDescription to the complete part of the response. Note that the Buffer has already been taken care of above. if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Received response: {responseString.Substring(0, completeLength - 2)}"); if (_isAsync) { // Tell who is listening what was received. if (state.Resp != null) { _currentResponseDescription = state.Resp; } Stream stream = null; if (PostReadCommandProcessing(ref stream)) return; ContinueCommandPipeline(); } } } // class CommandStream /// <summary> /// Contains the parsed status line from the server /// </summary> internal class ResponseDescription { internal const int NoStatus = -1; internal bool Multiline = false; internal int Status = NoStatus; internal string StatusDescription; internal StringBuilder StatusBuffer = new StringBuilder(); internal string StatusCodeString; internal bool PositiveIntermediate { get { return (Status >= 100 && Status <= 199); } } internal bool PositiveCompletion { get { return (Status >= 200 && Status <= 299); } } internal bool TransientFailure { get { return (Status >= 400 && Status <= 499); } } internal bool PermanentFailure { get { return (Status >= 500 && Status <= 599); } } internal bool InvalidStatusCode { get { return (Status < 100 || Status > 599); } } } /// <summary> /// State information that is used during ReceiveCommandResponse()'s async operations /// </summary> internal class ReceiveState { private const int bufferSize = 1024; internal ResponseDescription Resp; internal int ValidThrough; internal byte[] Buffer; internal CommandStream Connection; internal ReceiveState(CommandStream connection) { Connection = connection; Resp = new ResponseDescription(); Buffer = new byte[bufferSize]; //1024 ValidThrough = 0; } } } // namespace System.Net
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; namespace SchoolBusAPI.Models { /// <summary> /// /// </summary> public partial class Notification : IEquatable<Notification> { /// <summary> /// Default constructor, required by entity framework /// </summary> public Notification() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="Notification" /> class. /// </summary> /// <param name="Id">Primary Key (required).</param> /// <param name="Event">Event.</param> /// <param name="Event2">Event2.</param> /// <param name="HasBeenViewed">HasBeenViewed.</param> /// <param name="IsWatchNotification">IsWatchNotification.</param> /// <param name="IsExpired">IsExpired.</param> /// <param name="IsAllDay">IsAllDay.</param> /// <param name="PriorityCode">PriorityCode.</param> /// <param name="User">User.</param> public Notification(int Id, NotificationEvent Event = null, NotificationEvent Event2 = null, bool? HasBeenViewed = null, bool? IsWatchNotification = null, bool? IsExpired = null, bool? IsAllDay = null, string PriorityCode = null, User User = null) { this.Id = Id; this.Event = Event; this.Event2 = Event2; this.HasBeenViewed = HasBeenViewed; this.IsWatchNotification = IsWatchNotification; this.IsExpired = IsExpired; this.IsAllDay = IsAllDay; this.PriorityCode = PriorityCode; this.User = User; } /// <summary> /// Primary Key /// </summary> /// <value>Primary Key</value> [MetaDataExtension (Description = "Primary Key")] public int Id { get; set; } /// <summary> /// Gets or Sets Event /// </summary> public NotificationEvent Event { get; set; } [ForeignKey("Event")] public int? EventRefId { get; set; } /// <summary> /// Gets or Sets Event2 /// </summary> public NotificationEvent Event2 { get; set; } [ForeignKey("Event2")] public int? Event2RefId { get; set; } /// <summary> /// Gets or Sets HasBeenViewed /// </summary> public bool? HasBeenViewed { get; set; } /// <summary> /// Gets or Sets IsWatchNotification /// </summary> public bool? IsWatchNotification { get; set; } /// <summary> /// Gets or Sets IsExpired /// </summary> public bool? IsExpired { get; set; } /// <summary> /// Gets or Sets IsAllDay /// </summary> public bool? IsAllDay { get; set; } /// <summary> /// Gets or Sets PriorityCode /// </summary> public string PriorityCode { get; set; } /// <summary> /// Gets or Sets User /// </summary> public User User { get; set; } [ForeignKey("User")] public int? UserRefId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Notification {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Event: ").Append(Event).Append("\n"); sb.Append(" Event2: ").Append(Event2).Append("\n"); sb.Append(" HasBeenViewed: ").Append(HasBeenViewed).Append("\n"); sb.Append(" IsWatchNotification: ").Append(IsWatchNotification).Append("\n"); sb.Append(" IsExpired: ").Append(IsExpired).Append("\n"); sb.Append(" IsAllDay: ").Append(IsAllDay).Append("\n"); sb.Append(" PriorityCode: ").Append(PriorityCode).Append("\n"); sb.Append(" User: ").Append(User).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((Notification)obj); } /// <summary> /// Returns true if Notification instances are equal /// </summary> /// <param name="other">Instance of Notification to be compared</param> /// <returns>Boolean</returns> public bool Equals(Notification other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Event == other.Event || this.Event != null && this.Event.Equals(other.Event) ) && ( this.Event2 == other.Event2 || this.Event2 != null && this.Event2.Equals(other.Event2) ) && ( this.HasBeenViewed == other.HasBeenViewed || this.HasBeenViewed != null && this.HasBeenViewed.Equals(other.HasBeenViewed) ) && ( this.IsWatchNotification == other.IsWatchNotification || this.IsWatchNotification != null && this.IsWatchNotification.Equals(other.IsWatchNotification) ) && ( this.IsExpired == other.IsExpired || this.IsExpired != null && this.IsExpired.Equals(other.IsExpired) ) && ( this.IsAllDay == other.IsAllDay || this.IsAllDay != null && this.IsAllDay.Equals(other.IsAllDay) ) && ( this.PriorityCode == other.PriorityCode || this.PriorityCode != null && this.PriorityCode.Equals(other.PriorityCode) ) && ( this.User == other.User || this.User != null && this.User.Equals(other.User) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks if (this.Id != null) { hash = hash * 59 + this.Id.GetHashCode(); } if (this.Event != null) { hash = hash * 59 + this.Event.GetHashCode(); } if (this.Event2 != null) { hash = hash * 59 + this.Event2.GetHashCode(); } if (this.HasBeenViewed != null) { hash = hash * 59 + this.HasBeenViewed.GetHashCode(); } if (this.IsWatchNotification != null) { hash = hash * 59 + this.IsWatchNotification.GetHashCode(); } if (this.IsExpired != null) { hash = hash * 59 + this.IsExpired.GetHashCode(); } if (this.IsAllDay != null) { hash = hash * 59 + this.IsAllDay.GetHashCode(); } if (this.PriorityCode != null) { hash = hash * 59 + this.PriorityCode.GetHashCode(); } if (this.User != null) { hash = hash * 59 + this.User.GetHashCode(); } return hash; } } #region Operators public static bool operator ==(Notification left, Notification right) { return Equals(left, right); } public static bool operator !=(Notification left, Notification right) { return !Equals(left, right); } #endregion Operators } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Orders; using QuantConnect.Securities; using QuantConnect.Util; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Provides a regression baseline focused on updating orders /// </summary> /// <meta name="tag" content="regression test" /> public class UpdateOrderRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private int LastMonth = -1; private Security Security; private int Quantity = 100; private const int DeltaQuantity = 10; private const decimal StopPercentage = 0.025m; private const decimal StopPercentageDelta = 0.005m; private const decimal LimitPercentage = 0.025m; private const decimal LimitPercentageDelta = 0.005m; private const string symbol = "SPY"; private const SecurityType SecType = SecurityType.Equity; private readonly CircularQueue<OrderType> _orderTypesQueue = new CircularQueue<OrderType>(Enum.GetValues(typeof(OrderType)) .OfType<OrderType>() .Where (x => x != OrderType.OptionExercise)); private readonly List<OrderTicket> _tickets = new List<OrderTicket>(); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 01, 01); //Set Start Date SetEndDate(2015, 01, 01); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddSecurity(SecType, symbol, Resolution.Daily); Security = Securities[symbol]; _orderTypesQueue.CircleCompleted += (sender, args) => { // flip our signs when we've gone through all the order types Quantity *= -1; }; } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!data.Bars.ContainsKey(symbol)) return; // each month make an action if (Time.Month != LastMonth) { // we'll submit the next type of order from the queue var orderType = _orderTypesQueue.Dequeue(); //Log(""); Log("\r\n--------------MONTH: " + Time.ToString("MMMM") + ":: " + orderType + "\r\n"); //Log(""); LastMonth = Time.Month; Log("ORDER TYPE:: " + orderType); var isLong = Quantity > 0; var stopPrice = isLong ? (1 + StopPercentage)*data.Bars[symbol].High : (1 - StopPercentage)*data.Bars[symbol].Low; var limitPrice = isLong ? (1 - LimitPercentage)*stopPrice : (1 + LimitPercentage)*stopPrice; if (orderType == OrderType.Limit) { limitPrice = !isLong ? (1 + LimitPercentage) * data.Bars[symbol].High : (1 - LimitPercentage) * data.Bars[symbol].Low; } var request = new SubmitOrderRequest(orderType, SecType, symbol, Quantity, stopPrice, limitPrice, UtcTime, orderType.ToString()); var ticket = Transactions.AddOrder(request); _tickets.Add(ticket); } else if (_tickets.Count > 0) { var ticket = _tickets.Last(); if (Time.Day > 8 && Time.Day < 14) { if (ticket.UpdateRequests.Count == 0 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { Quantity = ticket.Quantity + Math.Sign(Quantity)*DeltaQuantity, Tag = "Change quantity: " + Time }); Log("UPDATE1:: " + ticket.UpdateRequests.Last()); } } else if (Time.Day > 13 && Time.Day < 20) { if (ticket.UpdateRequests.Count == 1 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Update(new UpdateOrderFields { LimitPrice = Security.Price*(1 - Math.Sign(ticket.Quantity)*LimitPercentageDelta), StopPrice = Security.Price*(1 + Math.Sign(ticket.Quantity)*StopPercentageDelta), Tag = "Change prices: " + Time }); Log("UPDATE2:: " + ticket.UpdateRequests.Last()); } } else { if (ticket.UpdateRequests.Count == 2 && ticket.Status.IsOpen()) { Log("TICKET:: " + ticket); ticket.Cancel(Time + " and is still open!"); Log("CANCELLED:: " + ticket.CancelRequest); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { // if the order time isn't equal to the algo time, then the modified time on the order should be updated var order = Transactions.GetOrderById(orderEvent.OrderId); var ticket = Transactions.GetOrderTicket(orderEvent.OrderId); if (order.Status == OrderStatus.Canceled && order.CanceledTime != orderEvent.UtcTime) { throw new Exception("Expected canceled order CanceledTime to equal canceled order event time."); } // fills update LastFillTime if ((order.Status == OrderStatus.Filled || order.Status == OrderStatus.PartiallyFilled) && order.LastFillTime != orderEvent.UtcTime) { throw new Exception("Expected filled order LastFillTime to equal fill order event time."); } // check the ticket to see if the update was successfully processed if (ticket.UpdateRequests.Any(ur => ur.Response?.IsSuccess == true) && order.CreatedTime != UtcTime && order.LastUpdateTime == null) { throw new Exception("Expected updated order LastUpdateTime to equal submitted update order event time"); } if (orderEvent.Status == OrderStatus.Filled) { Log("FILLED:: " + Transactions.GetOrderById(orderEvent.OrderId) + " FILL PRICE:: " + orderEvent.FillPrice.SmartRounding()); } else { Log(orderEvent.ToString()); Log("TICKET:: " + _tickets.Last()); } } private new void Log(string msg) { if (LiveMode) Debug(msg); else base.Log(msg); } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "21"}, {"Average Win", "0%"}, {"Average Loss", "-1.60%"}, {"Compounding Annual Return", "-7.774%"}, {"Drawdown", "15.700%"}, {"Expectancy", "-1"}, {"Net Profit", "-14.944%"}, {"Sharpe Ratio", "-1.359"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.074"}, {"Beta", "-0.27"}, {"Annual Standard Deviation", "0.058"}, {"Annual Variance", "0.003"}, {"Information Ratio", "-1.701"}, {"Tracking Error", "0.058"}, {"Treynor Ratio", "0.293"}, {"Total Fees", "$21.00"} }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Collections.Generic { public static partial class CollectionExtensions { public static TValue GetValueOrDefault<TKey, TValue>(this System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { throw null; } public static TValue GetValueOrDefault<TKey, TValue>(this System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { throw null; } public static bool Remove<TKey, TValue>(this System.Collections.Generic.IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { throw null; } public static bool TryAdd<TKey, TValue>(this System.Collections.Generic.IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { throw null; } } public abstract partial class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer { protected Comparer() { } public static System.Collections.Generic.Comparer<T> Default { get { throw null; } } public abstract int Compare(T x, T y); public static System.Collections.Generic.Comparer<T> Create(System.Comparison<T> comparison) { throw null; } int System.Collections.IComparer.Compare(object x, object y) { throw null; } } public partial class Dictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public Dictionary() { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection) { } public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(int capacity) { } public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public int EnsureCapacity(int capacity) { throw null; } public System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public bool Remove(TKey key) { throw null; } public bool Remove(TKey key, out TValue value) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public void TrimExcess() { } public void TrimExcess(int capacity) { } public bool TryAdd(TKey key, TValue value) { throw null; } public bool TryGetValue(TKey key, out TValue value) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } } object System.Collections.IDictionaryEnumerator.Key { get { throw null; } } object System.Collections.IDictionaryEnumerator.Value { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TKey Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TValue Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } } public abstract partial class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer { protected EqualityComparer() { } public static System.Collections.Generic.EqualityComparer<T> Default { get { throw null; } } public abstract bool Equals(T x, T y); public abstract int GetHashCode(T obj); bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; } int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; } } public partial class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public HashSet() { } public HashSet(System.Collections.Generic.IEnumerable<T> collection) { } public HashSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer) { } public HashSet(System.Collections.Generic.IEqualityComparer<T> comparer) { } public HashSet(int capacity) { } public HashSet(int capacity, System.Collections.Generic.IEqualityComparer<T> comparer) { } protected HashSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IEqualityComparer<T> Comparer { get { throw null; } } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } public bool Add(T item) { throw null; } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(T[] array, int arrayIndex, int count) { } public static System.Collections.Generic.IEqualityComparer<System.Collections.Generic.HashSet<T>> CreateSetComparer() { throw null; } public int EnsureCapacity(int capacity) { throw null; } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public virtual void OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool Remove(T item) { throw null; } public int RemoveWhere(System.Predicate<T> match) { throw null; } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public void TrimExcess() { } public bool TryGetValue(T equalValue, out T actualValue) { throw null; } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial interface IAsyncEnumerable<out T> { System.Collections.Generic.IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public partial interface IAsyncEnumerator<out T> : System.IAsyncDisposable { T Current { get; } System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); } public partial interface ICollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable { int Count { get; } bool IsReadOnly { get; } void Add(T item); void Clear(); bool Contains(T item); void CopyTo(T[] array, int arrayIndex); bool Remove(T item); } public partial interface IComparer<in T> { int Compare(T x, T y); } public partial interface IDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IEnumerable { TValue this[TKey key] { get; set; } System.Collections.Generic.ICollection<TKey> Keys { get; } System.Collections.Generic.ICollection<TValue> Values { get; } void Add(TKey key, TValue value); bool ContainsKey(TKey key); bool Remove(TKey key); bool TryGetValue(TKey key, out TValue value); } public partial interface IEnumerable<out T> : System.Collections.IEnumerable { new System.Collections.Generic.IEnumerator<T> GetEnumerator(); } public partial interface IEnumerator<out T> : System.Collections.IEnumerator, System.IDisposable { new T Current { get; } } public partial interface IEqualityComparer<in T> { bool Equals(T x, T y); int GetHashCode(T obj); } public partial interface IList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable { T this[int index] { get; set; } int IndexOf(T item); void Insert(int index, T item); void RemoveAt(int index); } public partial interface IReadOnlyCollection<out T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable { int Count { get; } } public partial interface IReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IEnumerable { TValue this[TKey key] { get; } System.Collections.Generic.IEnumerable<TKey> Keys { get; } System.Collections.Generic.IEnumerable<TValue> Values { get; } bool ContainsKey(TKey key); bool TryGetValue(TKey key, out TValue value); } public partial interface IReadOnlyList<out T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.IEnumerable { T this[int index] { get; } } public partial interface ISet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable { new bool Add(T item); void ExceptWith(System.Collections.Generic.IEnumerable<T> other); void IntersectWith(System.Collections.Generic.IEnumerable<T> other); bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other); bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other); bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other); bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other); bool Overlaps(System.Collections.Generic.IEnumerable<T> other); bool SetEquals(System.Collections.Generic.IEnumerable<T> other); void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other); void UnionWith(System.Collections.Generic.IEnumerable<T> other); } public partial class KeyNotFoundException : System.SystemException { public KeyNotFoundException() { } protected KeyNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public KeyNotFoundException(string message) { } public KeyNotFoundException(string message, System.Exception innerException) { } } public static partial class KeyValuePair { public static System.Collections.Generic.KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value) { throw null; } } public readonly partial struct KeyValuePair<TKey, TValue> { private readonly TKey key; private readonly TValue value; private readonly int _dummyPrimitive; public KeyValuePair(TKey key, TValue value) { throw null; } public TKey Key { get { throw null; } } public TValue Value { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Deconstruct(out TKey key, out TValue value) { throw null; } public override string ToString() { throw null; } } public partial class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public LinkedList() { } public LinkedList(System.Collections.Generic.IEnumerable<T> collection) { } protected LinkedList(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Count { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> First { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Last { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void AddAfter(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddAfter(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; } public void AddBefore(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddBefore(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; } public void AddFirst(System.Collections.Generic.LinkedListNode<T> node) { } public System.Collections.Generic.LinkedListNode<T> AddFirst(T value) { throw null; } public void AddLast(System.Collections.Generic.LinkedListNode<T> node) { } public System.Collections.Generic.LinkedListNode<T> AddLast(T value) { throw null; } public void Clear() { } public bool Contains(T value) { throw null; } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.LinkedListNode<T> Find(T value) { throw null; } public System.Collections.Generic.LinkedListNode<T> FindLast(T value) { throw null; } public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public void Remove(System.Collections.Generic.LinkedListNode<T> node) { } public bool Remove(T value) { throw null; } public void RemoveFirst() { } public void RemoveLast() { } void System.Collections.Generic.ICollection<T>.Add(T value) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.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 sealed partial class LinkedListNode<T> { public LinkedListNode(T value) { } public System.Collections.Generic.LinkedList<T> List { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Next { get { throw null; } } public System.Collections.Generic.LinkedListNode<T> Previous { get { throw null; } } public T Value { get { throw null; } set { } } } public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public List() { } public List(System.Collections.Generic.IEnumerable<T> collection) { } public List(int capacity) { } public int Capacity { get { throw null; } set { } } public int Count { get { throw null; } } public T this[int index] { get { throw null; } set { } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void Add(T item) { } public void AddRange(System.Collections.Generic.IEnumerable<T> collection) { } public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { throw null; } public int BinarySearch(int index, int count, T item, System.Collections.Generic.IComparer<T> comparer) { throw null; } public int BinarySearch(T item) { throw null; } public int BinarySearch(T item, System.Collections.Generic.IComparer<T> comparer) { throw null; } public void Clear() { } public bool Contains(T item) { throw null; } public System.Collections.Generic.List<TOutput> ConvertAll<TOutput>(System.Converter<T, TOutput> converter) { throw null; } public void CopyTo(int index, T[] array, int arrayIndex, int count) { } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public bool Exists(System.Predicate<T> match) { throw null; } public T Find(System.Predicate<T> match) { throw null; } public System.Collections.Generic.List<T> FindAll(System.Predicate<T> match) { throw null; } public int FindIndex(int startIndex, int count, System.Predicate<T> match) { throw null; } public int FindIndex(int startIndex, System.Predicate<T> match) { throw null; } public int FindIndex(System.Predicate<T> match) { throw null; } public T FindLast(System.Predicate<T> match) { throw null; } public int FindLastIndex(int startIndex, int count, System.Predicate<T> match) { throw null; } public int FindLastIndex(int startIndex, System.Predicate<T> match) { throw null; } public int FindLastIndex(System.Predicate<T> match) { throw null; } public void ForEach(System.Action<T> action) { } public System.Collections.Generic.List<T>.Enumerator GetEnumerator() { throw null; } public System.Collections.Generic.List<T> GetRange(int index, int count) { throw null; } public int IndexOf(T item) { throw null; } public int IndexOf(T item, int index) { throw null; } public int IndexOf(T item, int index, int count) { throw null; } public void Insert(int index, T item) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable<T> collection) { } public int LastIndexOf(T item) { throw null; } public int LastIndexOf(T item, int index) { throw null; } public int LastIndexOf(T item, int index, int count) { throw null; } public bool Remove(T item) { throw null; } public int RemoveAll(System.Predicate<T> match) { throw null; } public void RemoveAt(int index) { } public void RemoveRange(int index, int count) { } public void Reverse() { } public void Reverse(int index, int count) { } public void Sort() { } public void Sort(System.Collections.Generic.IComparer<T> comparer) { } public void Sort(System.Comparison<T> comparison) { } public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object item) { throw null; } bool System.Collections.IList.Contains(object item) { throw null; } int System.Collections.IList.IndexOf(object item) { throw null; } void System.Collections.IList.Insert(int index, object item) { } void System.Collections.IList.Remove(object item) { } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TrueForAll(System.Predicate<T> match) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Queue() { } public Queue(System.Collections.Generic.IEnumerable<T> collection) { } public Queue(int capacity) { } public int Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array, int arrayIndex) { } public T Dequeue() { throw null; } public void Enqueue(T item) { } public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator() { throw null; } public T Peek() { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TryDequeue(out T result) { throw null; } public bool TryPeek(out T result) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public partial class SortedDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedDictionary() { } public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public void CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; } public bool Remove(TKey key) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(TKey key, out TValue value) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } } object System.Collections.IDictionaryEnumerator.Key { get { throw null; } } object System.Collections.IDictionaryEnumerator.Value { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TKey Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { throw null; } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public TValue Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } } public partial class SortedList<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedList() { } public SortedList(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(int capacity) { } public SortedList(int capacity, System.Collections.Generic.IComparer<TKey> comparer) { } public int Capacity { get { throw null; } set { } } public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } } public int Count { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.IList<TKey> Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.IList<TValue> Values { get { throw null; } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public bool ContainsValue(TValue value) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; } public int IndexOfKey(TKey key) { throw null; } public int IndexOfValue(TValue value) { throw null; } public bool Remove(TKey key) { throw null; } public void RemoveAt(int index) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public void TrimExcess() { } public bool TryGetValue(TKey key, out TValue value) { throw null; } } public partial class SortedSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public SortedSet() { } public SortedSet(System.Collections.Generic.IComparer<T> comparer) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T> comparer) { } protected SortedSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IComparer<T> Comparer { get { throw null; } } public int Count { get { throw null; } } public T Max { get { throw null; } } public T Min { get { throw null; } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public bool Add(T item) { throw null; } public virtual void Clear() { } public virtual bool Contains(T item) { throw null; } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int index) { } public void CopyTo(T[] array, int index, int count) { } public static System.Collections.Generic.IEqualityComparer<System.Collections.Generic.SortedSet<T>> CreateSetComparer() { throw null; } public static System.Collections.Generic.IEqualityComparer<System.Collections.Generic.SortedSet<T>> CreateSetComparer(System.Collections.Generic.IEqualityComparer<T> memberEqualityComparer) { throw null; } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { throw null; } public virtual void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; } protected virtual void OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; } public bool Remove(T item) { throw null; } public int RemoveWhere(System.Predicate<T> match) { throw null; } public System.Collections.Generic.IEnumerable<T> Reverse() { throw null; } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } 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 bool TryGetValue(T equalValue, out T actualValue) { throw null; } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.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 partial class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Stack() { } public Stack(System.Collections.Generic.IEnumerable<T> collection) { } public Stack(int capacity) { } public int Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array, int arrayIndex) { } public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator() { throw null; } public T Peek() { throw null; } public T Pop() { throw null; } public void Push(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public void TrimExcess() { } public bool TryPeek(out T result) { throw null; } public bool TryPop(out T result) { throw null; } public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } void System.Collections.IEnumerator.Reset() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Tests { public partial class EnumTests { [Theory] [MemberData(nameof(Parse_TestData))] public static void Parse_NetCoreApp11<T>(string value, bool ignoreCase, T expected) where T : struct { object result; if (!ignoreCase) { Assert.True(Enum.TryParse(expected.GetType(), value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, Enum.Parse<T>(value)); } Assert.True(Enum.TryParse(expected.GetType(), value, ignoreCase, out result)); Assert.Equal(expected, result); Assert.Equal(expected, Enum.Parse<T>(value, ignoreCase)); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid_NetCoreApp11(Type enumType, string value, bool ignoreCase, Type exceptionType) { Type typeArgument = enumType == null || !enumType.GetTypeInfo().IsEnum ? typeof(SimpleEnum) : enumType; MethodInfo parseMethod = typeof(EnumTests).GetTypeInfo().GetMethod(nameof(Parse_Generic_Invalid_NetCoreApp11)).MakeGenericMethod(typeArgument); parseMethod.Invoke(null, new object[] { enumType, value, ignoreCase, exceptionType }); } public static void Parse_Generic_Invalid_NetCoreApp11<T>(Type enumType, string value, bool ignoreCase, Type exceptionType) where T : struct { object result = null; if (!ignoreCase) { if (enumType != null && enumType.IsEnum) { Assert.False(Enum.TryParse(enumType, value, out result)); Assert.Equal(default(object), result); Assert.Throws(exceptionType, () => Enum.Parse<T>(value)); } else { Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, out result)); Assert.Equal(default(object), result); } } if (enumType != null && enumType.IsEnum) { Assert.False(Enum.TryParse(enumType, value, ignoreCase, out result)); Assert.Equal(default(object), result); Assert.Throws(exceptionType, () => Enum.Parse<T>(value, ignoreCase)); } else { Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, ignoreCase, out result)); Assert.Equal(default(object), result); } } public static IEnumerable<object[]> UnsupportedEnumType_TestData() { #if netcoreapp yield return new object[] { s_floatEnumType, 1.0f }; yield return new object[] { s_doubleEnumType, 1.0 }; yield return new object[] { s_intPtrEnumType, (IntPtr)1 }; yield return new object[] { s_uintPtrEnumType, (UIntPtr)1 }; #else return Array.Empty<object[]>(); #endif //netcoreapp } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void GetName_Unsupported_ThrowsArgumentException(Type enumType, object value) { AssertExtensions.Throws<ArgumentException>("value", () => Enum.GetName(enumType, value)); } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void IsDefined_UnsupportedEnumType_ThrowsInvalidOperationException(Type enumType, object value) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception ex = Assert.ThrowsAny<Exception>(() => Enum.IsDefined(enumType, value)); string exName = ex.GetType().Name; Assert.True(exName == nameof(InvalidOperationException) || exName == "ContractException"); } #if netcoreapp [Fact] public static void ToString_InvalidUnicodeChars() { // TODO: move into ToString_Format_TestData when dotnet/buildtools#1091 is fixed ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "D", char.MaxValue.ToString()); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "X", "FFFF"); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "F", char.MaxValue.ToString()); ToString_Format((Enum)Enum.ToObject(s_charEnumType, char.MaxValue), "G", char.MaxValue.ToString()); } #endif //netcoreapp public static IEnumerable<object[]> UnsupportedEnum_TestData() { #if netcoreapp yield return new object[] { Enum.ToObject(s_floatEnumType, 1) }; yield return new object[] { Enum.ToObject(s_doubleEnumType, 2) }; yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1) }; yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 2) }; #else return Array.Empty<object[]>(); #endif //netcoreapp } [Theory] [MemberData(nameof(UnsupportedEnum_TestData))] public static void ToString_UnsupportedEnumType_ThrowsArgumentException(Enum e) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception formatXException = Assert.ThrowsAny<Exception>(() => e.ToString("X")); string formatXExceptionName = formatXException.GetType().Name; Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException"); } [Theory] [MemberData(nameof(UnsupportedEnumType_TestData))] public static void Format_UnsupportedEnumType_ThrowsArgumentException(Type enumType, object value) { // A Contract.Assert(false, "...") is hit for certain unsupported primitives Exception formatGException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "G")); string formatGExceptionName = formatGException.GetType().Name; Assert.True(formatGExceptionName == nameof(InvalidOperationException) || formatGExceptionName == "ContractException"); Exception formatXException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "X")); string formatXExceptionName = formatXException.GetType().Name; Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException"); Exception formatFException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "F")); string formatFExceptionName = formatFException.GetType().Name; Assert.True(formatFExceptionName == nameof(InvalidOperationException) || formatFExceptionName == "ContractException"); } #if netcoreapp // .NetNative does not support RefEmit nor any other way to create Enum types with unusual backing types. private static EnumBuilder GetNonRuntimeEnumTypeBuilder(Type underlyingType) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); return module.DefineEnum("TestName_" + underlyingType.Name, TypeAttributes.Public, underlyingType); } private static Type s_boolEnumType = GetBoolEnumType(); private static Type GetBoolEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(bool)); enumBuilder.DefineLiteral("Value1", true); enumBuilder.DefineLiteral("Value2", false); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_charEnumType = GetCharEnumType(); private static Type GetCharEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(char)); enumBuilder.DefineLiteral("Value1", (char)1); enumBuilder.DefineLiteral("Value2", (char)2); enumBuilder.DefineLiteral("Value0x3f06", (char)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (char)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (char)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (char)0x1000); enumBuilder.DefineLiteral("Value0x0000", (char)0x0000); enumBuilder.DefineLiteral("Value0x0010", (char)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (char)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_floatEnumType = GetFloatEnumType(); private static Type GetFloatEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(float)); enumBuilder.DefineLiteral("Value1", 1.0f); enumBuilder.DefineLiteral("Value2", 2.0f); enumBuilder.DefineLiteral("Value0x3f06", (float)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (float)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (float)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (float)0x1000); enumBuilder.DefineLiteral("Value0x0000", (float)0x0000); enumBuilder.DefineLiteral("Value0x0010", (float)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (float)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_doubleEnumType = GetDoubleEnumType(); private static Type GetDoubleEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(double)); enumBuilder.DefineLiteral("Value1", 1.0); enumBuilder.DefineLiteral("Value2", 2.0); enumBuilder.DefineLiteral("Value0x3f06", (double)0x3f06); enumBuilder.DefineLiteral("Value0x3000", (double)0x3000); enumBuilder.DefineLiteral("Value0x0f06", (double)0x0f06); enumBuilder.DefineLiteral("Value0x1000", (double)0x1000); enumBuilder.DefineLiteral("Value0x0000", (double)0x0000); enumBuilder.DefineLiteral("Value0x0010", (double)0x0010); enumBuilder.DefineLiteral("Value0x3f16", (double)0x3f16); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_intPtrEnumType = GetIntPtrEnumType(); private static Type GetIntPtrEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(IntPtr)); return enumBuilder.CreateTypeInfo().AsType(); } private static Type s_uintPtrEnumType = GetUIntPtrEnumType(); private static Type GetUIntPtrEnumType() { EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(UIntPtr)); return enumBuilder.CreateTypeInfo().AsType(); } #endif //netcoreapp } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.Tools.Test.Utilities; using FluentAssertions; using Xunit; namespace Microsoft.DotNet.ProjectModel.Tests { public class LibraryExporterPackageTests { private const string PackagePath = "PackagePath"; private PackageDescription CreateDescription(LockFileTargetLibrary target = null, LockFilePackageLibrary package = null) { return new PackageDescription(PackagePath, package ?? new LockFilePackageLibrary(), target ?? new LockFileTargetLibrary(), new List<LibraryRange>(), compatible: true, resolved: true); } [Fact] public void ExportsPackageNativeLibraries() { var description = CreateDescription( new LockFileTargetLibrary() { NativeLibraries = new List<LockFileItem>() { { new LockFileItem() { Path = "lib/Native.so" } } } }); var result = ExportSingle(description); result.NativeLibraryGroups.Should().HaveCount(1); var libraryAsset = result.NativeLibraryGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("lib/Native.so"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Native.so")); } [Fact] public void ExportsPackageCompilationAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { CompileTimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.CompilationAssemblies.Should().HaveCount(1); var libraryAsset = result.CompilationAssemblies.First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(1); var libraryAsset = result.RuntimeAssemblyGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeTargets() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeTargets = new List<LockFileRuntimeTarget>() { new LockFileRuntimeTarget("native/native.dylib", "osx", "native"), new LockFileRuntimeTarget("lib/Something.OSX.dll", "osx", "runtime") } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(2); result.RuntimeAssemblyGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.RuntimeAssemblyGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); result.NativeLibraryGroups.Should().HaveCount(2); result.NativeLibraryGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.NativeLibraryGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); var nativeAsset = result.NativeLibraryGroups.GetRuntimeAssets("osx").First(); nativeAsset.Name.Should().Be("native"); nativeAsset.Transform.Should().BeNull(); nativeAsset.RelativePath.Should().Be("native/native.dylib"); nativeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "native/native.dylib")); var runtimeAsset = result.RuntimeAssemblyGroups.GetRuntimeAssets("osx").First(); runtimeAsset.Name.Should().Be("Something.OSX"); runtimeAsset.Transform.Should().BeNull(); runtimeAsset.RelativePath.Should().Be("lib/Something.OSX.dll"); runtimeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Something.OSX.dll")); } [Fact] public void ExportsSources() { var description = CreateDescription( package: new LockFilePackageLibrary() { Files = new List<string>() { Path.Combine("shared", "file.cs") } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Name.Should().Be("file"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("shared", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "shared", "file.cs")); } [Fact] public void ExportsCopyToOutputContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { CopyToOutput = true, Path = Path.Combine("content", "file.txt"), OutputPath = Path.Combine("Out","Path.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.RuntimeAssets.Should().HaveCount(1); var libraryAsset = result.RuntimeAssets.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("Out", "Path.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsResourceContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.EmbeddedResource, Path = Path.Combine("content", "file.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.EmbeddedResources.Should().HaveCount(1); var libraryAsset = result.EmbeddedResources.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsCompileContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesOfProjectCodeLanguage() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something", CodeLanguage = "cs" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesWithNoLanguageIfProjectLanguageNotMathed() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.any")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.any")); } private LibraryExport ExportSingle(LibraryDescription description = null) { var rootProject = new Project() { Name = "RootProject", CompilerName = "csc" }; var rootProjectDescription = new ProjectDescription( new LibraryRange(), rootProject, new LibraryRange[] { }, new TargetFrameworkInformation(), true); if (description == null) { description = rootProjectDescription; } else { description.Parents.Add(rootProjectDescription); } var libraryManager = new LibraryManager(new[] { description }, new DiagnosticMessage[] { }, ""); var allExports = new LibraryExporter(rootProjectDescription, libraryManager, "config", "runtime", "basepath", "solutionroot").GetAllExports(); var export = allExports.Single(); return export; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.Reflection; using System.Collections.Generic; namespace Falken { /// <summary> /// <c>ActionsNotBoundException</c> thrown when access to an /// unbound action is forbidden. /// </summary> [Serializable] public class ActionsNotBoundException : Exception { internal ActionsNotBoundException() { } internal ActionsNotBoundException(string message) : base(message) { } internal ActionsNotBoundException(string message, Exception inner) : base(message, inner) { } } /// <summary> /// <c>ActionsBase</c> defines the set of attributes that /// can be generated by a brain or by a human. /// </summary> public class ActionsBase : Falken.AttributeContainer { /// <summary> /// Source of a set of actions. /// </summary> public enum Source { /// <summary> /// Should never be set. /// </summary> Invalid = 0, /// <summary> /// Actions were not generated by Falken. /// </summary> None, /// <summary> /// Actions were generated by a human demonstration. /// </summary> HumanDemonstration, /// <summary> /// Actions were generated by a Falken brain. /// </summary> BrainAction, }; // Internal Falken actions container this instance uses // to create attributes. private FalkenInternal.falken.ActionsBase _actions = null; /// <summary> /// Check if a given object is one of the following types: /// * Number /// * Boolean /// * Category /// </summary> protected override bool SupportsType(object fieldValue) { return Number.CanConvertToNumberType(fieldValue) || Boolean.CanConvertToBooleanType(fieldValue) || Category.CanConvertToCategoryType(fieldValue) || Joystick.CanConvertToJoystickType(fieldValue); } /// <summary> /// Bind all supported action types. /// <exception> AlreadyBoundException thrown when trying to /// bind the actions when it was bound already. </exception> /// </summary> internal void BindActions(FalkenInternal.falken.ActionsBase actions) { if (Bound) { throw new AlreadyBoundException( "Can't bind actions more than once."); } base.BindAttributes(actions); _actions = actions; } internal void Rebind(FalkenInternal.falken.ActionsBase actions) { base.Rebind(actions); _actions = actions; } internal void LoadActions(FalkenInternal.falken.ActionsBase actions) { base.LoadAttributes(actions); _actions = actions; } /// <summary> /// Convert a given an internal ActionsBase.Source to the /// public actions source. /// </summary> private static Falken.ActionsBase.Source FromInternalSource( FalkenInternal.falken.ActionsBase.Source internalSource) { Falken.ActionsBase.Source source = Falken.ActionsBase.Source.None; switch (internalSource) { case FalkenInternal.falken.ActionsBase.Source.kSourceInvalid: source = Falken.ActionsBase.Source.Invalid; break; case FalkenInternal.falken.ActionsBase.Source.kSourceNone: source = Falken.ActionsBase.Source.None; break; case FalkenInternal.falken.ActionsBase.Source.kSourceHumanDemonstration: source = Falken.ActionsBase.Source.HumanDemonstration; break; case FalkenInternal.falken.ActionsBase.Source.kSourceBrainAction: source = Falken.ActionsBase.Source.BrainAction; break; } return source; } /// <summary> /// Convert a given public actions source to the internal representation. /// </summary> private static FalkenInternal.falken.ActionsBase.Source ToInternalSource( Falken.ActionsBase.Source source) { FalkenInternal.falken.ActionsBase.Source internalSource = FalkenInternal.falken.ActionsBase.Source.kSourceNone; switch (source) { case Falken.ActionsBase.Source.Invalid: internalSource = FalkenInternal.falken.ActionsBase.Source.kSourceInvalid; break; case Falken.ActionsBase.Source.None: internalSource = FalkenInternal.falken.ActionsBase.Source.kSourceNone; break; case Falken.ActionsBase.Source.HumanDemonstration: internalSource = FalkenInternal.falken.ActionsBase.Source.kSourceHumanDemonstration; break; case Falken.ActionsBase.Source.BrainAction: internalSource = FalkenInternal.falken.ActionsBase.Source.kSourceBrainAction; break; } return internalSource; } /// <summary> /// Retrieve/set the source for this actions. /// </summary> public Falken.ActionsBase.Source ActionsSource { get { if (Bound) { return FromInternalSource(_actions.source()); } throw new ActionsNotBoundException( "Can't get the source from an unbound action."); } set { if (Bound) { _actions.set_source(ToInternalSource(value)); return; } throw new ActionsNotBoundException( "Can't set the source to an unbound action."); } } } }
namespace PTWin { partial class ResourceEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.Label FirstNameLabel; System.Windows.Forms.Label IdLabel; System.Windows.Forms.Label LastNameLabel; this.CloseButton = new System.Windows.Forms.Button(); this.ApplyButton = new System.Windows.Forms.Button(); this.Cancel_Button = new System.Windows.Forms.Button(); this.OKButton = new System.Windows.Forms.Button(); this.GroupBox1 = new System.Windows.Forms.GroupBox(); this.AssignmentsDataGridView = new System.Windows.Forms.DataGridView(); this.RoleListBindingSource = new System.Windows.Forms.BindingSource(this.components); this.AssignmentsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.ResourceBindingSource = new System.Windows.Forms.BindingSource(this.components); this.UnassignButton = new System.Windows.Forms.Button(); this.AssignButton = new System.Windows.Forms.Button(); this.FirstNameTextBox = new System.Windows.Forms.TextBox(); this.IdLabel1 = new System.Windows.Forms.Label(); this.LastNameTextBox = new System.Windows.Forms.TextBox(); this.ErrorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.ReadWriteAuthorization1 = new Csla.Windows.ReadWriteAuthorization(this.components); this.RefreshButton = new System.Windows.Forms.Button(); this.bindingSourceRefresh1 = new Csla.Windows.BindingSourceRefresh(this.components); this.projectIdDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.projectNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewLinkColumn(); this.assignedDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Role = new System.Windows.Forms.DataGridViewComboBoxColumn(); FirstNameLabel = new System.Windows.Forms.Label(); IdLabel = new System.Windows.Forms.Label(); LastNameLabel = new System.Windows.Forms.Label(); this.GroupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).BeginInit(); this.SuspendLayout(); // // FirstNameLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(FirstNameLabel, false); FirstNameLabel.AutoSize = true; FirstNameLabel.Location = new System.Drawing.Point(13, 42); FirstNameLabel.Name = "FirstNameLabel"; FirstNameLabel.Size = new System.Drawing.Size(60, 13); FirstNameLabel.TabIndex = 2; FirstNameLabel.Text = "First Name:"; // // IdLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(IdLabel, false); IdLabel.AutoSize = true; IdLabel.Location = new System.Drawing.Point(13, 13); IdLabel.Name = "IdLabel"; IdLabel.Size = new System.Drawing.Size(19, 13); IdLabel.TabIndex = 0; IdLabel.Text = "Id:"; // // LastNameLabel // this.ReadWriteAuthorization1.SetApplyAuthorization(LastNameLabel, false); LastNameLabel.AutoSize = true; LastNameLabel.Location = new System.Drawing.Point(13, 68); LastNameLabel.Name = "LastNameLabel"; LastNameLabel.Size = new System.Drawing.Size(61, 13); LastNameLabel.TabIndex = 4; LastNameLabel.Text = "Last Name:"; // // CloseButton // this.CloseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.CloseButton, false); this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CloseButton.Location = new System.Drawing.Point(501, 100); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(75, 23); this.CloseButton.TabIndex = 10; this.CloseButton.Text = "Close"; this.CloseButton.UseVisualStyleBackColor = true; this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click); // // ApplyButton // this.ApplyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.ApplyButton, false); this.ApplyButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.ApplyButton.Location = new System.Drawing.Point(501, 42); this.ApplyButton.Name = "ApplyButton"; this.ApplyButton.Size = new System.Drawing.Size(75, 23); this.ApplyButton.TabIndex = 8; this.ApplyButton.Text = "Apply"; this.ApplyButton.UseVisualStyleBackColor = true; this.ApplyButton.Click += new System.EventHandler(this.ApplyButton_Click); // // Cancel_Button // this.Cancel_Button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.Cancel_Button, false); this.Cancel_Button.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel_Button.Location = new System.Drawing.Point(501, 71); this.Cancel_Button.Name = "Cancel_Button"; this.Cancel_Button.Size = new System.Drawing.Size(75, 23); this.Cancel_Button.TabIndex = 9; this.Cancel_Button.Text = "Cancel"; this.Cancel_Button.UseVisualStyleBackColor = true; this.Cancel_Button.Click += new System.EventHandler(this.Cancel_Button_Click); // // OKButton // this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.OKButton, false); this.OKButton.Location = new System.Drawing.Point(501, 13); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(75, 23); this.OKButton.TabIndex = 7; this.OKButton.Text = "OK"; this.OKButton.UseVisualStyleBackColor = true; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // GroupBox1 // this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.GroupBox1, false); this.GroupBox1.Controls.Add(this.AssignmentsDataGridView); this.GroupBox1.Controls.Add(this.UnassignButton); this.GroupBox1.Controls.Add(this.AssignButton); this.GroupBox1.Location = new System.Drawing.Point(16, 91); this.GroupBox1.Name = "GroupBox1"; this.GroupBox1.Size = new System.Drawing.Size(449, 310); this.GroupBox1.TabIndex = 6; this.GroupBox1.TabStop = false; this.GroupBox1.Text = "Assigned projects"; // // AssignmentsDataGridView // this.AssignmentsDataGridView.AllowUserToAddRows = false; this.AssignmentsDataGridView.AllowUserToDeleteRows = false; this.AssignmentsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignmentsDataGridView, false); this.AssignmentsDataGridView.AutoGenerateColumns = false; this.AssignmentsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.AssignmentsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.projectIdDataGridViewTextBoxColumn, this.projectNameDataGridViewTextBoxColumn, this.assignedDataGridViewTextBoxColumn, this.Role}); this.AssignmentsDataGridView.DataSource = this.AssignmentsBindingSource; this.AssignmentsDataGridView.Location = new System.Drawing.Point(6, 19); this.AssignmentsDataGridView.MultiSelect = false; this.AssignmentsDataGridView.Name = "AssignmentsDataGridView"; this.AssignmentsDataGridView.RowHeadersVisible = false; this.AssignmentsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.AssignmentsDataGridView.Size = new System.Drawing.Size(356, 285); this.AssignmentsDataGridView.TabIndex = 0; this.AssignmentsDataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.AssignmentsDataGridView_CellContentClick); // // RoleListBindingSource // this.RoleListBindingSource.DataSource = typeof(ProjectTracker.Library.RoleList); this.bindingSourceRefresh1.SetReadValuesOnChange(this.RoleListBindingSource, false); // // AssignmentsBindingSource // this.AssignmentsBindingSource.DataMember = "Assignments"; this.AssignmentsBindingSource.DataSource = this.ResourceBindingSource; this.bindingSourceRefresh1.SetReadValuesOnChange(this.AssignmentsBindingSource, false); // // ResourceBindingSource // this.ResourceBindingSource.DataSource = typeof(ProjectTracker.Library.ResourceEdit); this.bindingSourceRefresh1.SetReadValuesOnChange(this.ResourceBindingSource, true); // // UnassignButton // this.UnassignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.UnassignButton, false); this.UnassignButton.Location = new System.Drawing.Point(368, 48); this.UnassignButton.Name = "UnassignButton"; this.UnassignButton.Size = new System.Drawing.Size(75, 23); this.UnassignButton.TabIndex = 2; this.UnassignButton.Text = "Unassign"; this.UnassignButton.UseVisualStyleBackColor = true; this.UnassignButton.Click += new System.EventHandler(this.UnassignButton_Click); // // AssignButton // this.AssignButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.AssignButton, false); this.AssignButton.Location = new System.Drawing.Point(368, 19); this.AssignButton.Name = "AssignButton"; this.AssignButton.Size = new System.Drawing.Size(75, 23); this.AssignButton.TabIndex = 1; this.AssignButton.Text = "Assign"; this.AssignButton.UseVisualStyleBackColor = true; this.AssignButton.Click += new System.EventHandler(this.AssignButton_Click); // // FirstNameTextBox // this.FirstNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.FirstNameTextBox, true); this.FirstNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "FirstName", true)); this.FirstNameTextBox.Location = new System.Drawing.Point(80, 39); this.FirstNameTextBox.Name = "FirstNameTextBox"; this.FirstNameTextBox.Size = new System.Drawing.Size(385, 20); this.FirstNameTextBox.TabIndex = 3; // // IdLabel1 // this.IdLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.IdLabel1, true); this.IdLabel1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "Id", true)); this.IdLabel1.Location = new System.Drawing.Point(80, 13); this.IdLabel1.Name = "IdLabel1"; this.IdLabel1.Size = new System.Drawing.Size(385, 23); this.IdLabel1.TabIndex = 1; // // LastNameTextBox // this.LastNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.LastNameTextBox, true); this.LastNameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ResourceBindingSource, "LastName", true)); this.LastNameTextBox.Location = new System.Drawing.Point(80, 65); this.LastNameTextBox.Name = "LastNameTextBox"; this.LastNameTextBox.Size = new System.Drawing.Size(385, 20); this.LastNameTextBox.TabIndex = 5; // // ErrorProvider1 // this.ErrorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink; this.ErrorProvider1.ContainerControl = this; this.ErrorProvider1.DataSource = this.ResourceBindingSource; // // RefreshButton // this.RefreshButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ReadWriteAuthorization1.SetApplyAuthorization(this.RefreshButton, false); this.RefreshButton.Location = new System.Drawing.Point(501, 129); this.RefreshButton.Name = "RefreshButton"; this.RefreshButton.Size = new System.Drawing.Size(75, 23); this.RefreshButton.TabIndex = 11; this.RefreshButton.Text = "Refresh"; this.RefreshButton.UseVisualStyleBackColor = true; this.RefreshButton.Click += new System.EventHandler(this.RefreshButton_Click); // // bindingSourceRefresh1 // this.bindingSourceRefresh1.Host = this; // // projectIdDataGridViewTextBoxColumn // this.projectIdDataGridViewTextBoxColumn.DataPropertyName = "ProjectId"; this.projectIdDataGridViewTextBoxColumn.HeaderText = "ProjectId"; this.projectIdDataGridViewTextBoxColumn.Name = "projectIdDataGridViewTextBoxColumn"; this.projectIdDataGridViewTextBoxColumn.ReadOnly = true; this.projectIdDataGridViewTextBoxColumn.Visible = false; this.projectIdDataGridViewTextBoxColumn.Width = 74; // // projectNameDataGridViewTextBoxColumn // this.projectNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.projectNameDataGridViewTextBoxColumn.DataPropertyName = "ProjectName"; this.projectNameDataGridViewTextBoxColumn.FillWeight = 200F; this.projectNameDataGridViewTextBoxColumn.HeaderText = "Project Name"; this.projectNameDataGridViewTextBoxColumn.Name = "projectNameDataGridViewTextBoxColumn"; this.projectNameDataGridViewTextBoxColumn.ReadOnly = true; this.projectNameDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.projectNameDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; // // assignedDataGridViewTextBoxColumn // this.assignedDataGridViewTextBoxColumn.DataPropertyName = "Assigned"; this.assignedDataGridViewTextBoxColumn.HeaderText = "Assigned"; this.assignedDataGridViewTextBoxColumn.Name = "assignedDataGridViewTextBoxColumn"; this.assignedDataGridViewTextBoxColumn.ReadOnly = true; this.assignedDataGridViewTextBoxColumn.Width = 75; // // Role // this.Role.DataPropertyName = "Role"; this.Role.DataSource = this.RoleListBindingSource; this.Role.DisplayMember = "Value"; this.Role.FillWeight = 200F; this.Role.HeaderText = "Role"; this.Role.Name = "Role"; this.Role.ValueMember = "Key"; this.Role.Width = 35; // // ResourceEdit // this.ReadWriteAuthorization1.SetApplyAuthorization(this, false); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.RefreshButton); this.Controls.Add(this.CloseButton); this.Controls.Add(this.ApplyButton); this.Controls.Add(this.Cancel_Button); this.Controls.Add(this.OKButton); this.Controls.Add(this.GroupBox1); this.Controls.Add(FirstNameLabel); this.Controls.Add(this.FirstNameTextBox); this.Controls.Add(IdLabel); this.Controls.Add(this.IdLabel1); this.Controls.Add(LastNameLabel); this.Controls.Add(this.LastNameTextBox); this.Name = "ResourceEdit"; this.Size = new System.Drawing.Size(588, 415); this.Load += new System.EventHandler(this.ResourceEdit_Load); this.GroupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsDataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.RoleListBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.AssignmentsBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ResourceBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ErrorProvider1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSourceRefresh1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion internal System.Windows.Forms.Button CloseButton; internal System.Windows.Forms.Button ApplyButton; internal System.Windows.Forms.Button Cancel_Button; internal System.Windows.Forms.Button OKButton; internal System.Windows.Forms.GroupBox GroupBox1; internal System.Windows.Forms.Button UnassignButton; internal System.Windows.Forms.Button AssignButton; internal System.Windows.Forms.TextBox FirstNameTextBox; internal System.Windows.Forms.Label IdLabel1; internal System.Windows.Forms.TextBox LastNameTextBox; internal Csla.Windows.ReadWriteAuthorization ReadWriteAuthorization1; internal System.Windows.Forms.DataGridView AssignmentsDataGridView; internal System.Windows.Forms.BindingSource RoleListBindingSource; internal System.Windows.Forms.BindingSource AssignmentsBindingSource; internal System.Windows.Forms.BindingSource ResourceBindingSource; internal System.Windows.Forms.ErrorProvider ErrorProvider1; private Csla.Windows.BindingSourceRefresh bindingSourceRefresh1; internal System.Windows.Forms.Button RefreshButton; private System.Windows.Forms.DataGridViewTextBoxColumn projectIdDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewLinkColumn projectNameDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn assignedDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewComboBoxColumn Role; } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // class ClippingPixelFormtProxy // //---------------------------------------------------------------------------- namespace MatterHackers.Agg.Image { public class ImageClippingProxy : ImageProxy { private RectangleInt m_ClippingRect; public const byte cover_full = 255; public ImageClippingProxy(IImageByte ren) : base(ren) { m_ClippingRect = new RectangleInt(0, 0, (int)ren.Width - 1, (int)ren.Height - 1); } public override void LinkToImage(IImageByte ren) { base.LinkToImage(ren); m_ClippingRect = new RectangleInt(0, 0, (int)ren.Width - 1, (int)ren.Height - 1); } public bool SetClippingBox(int x1, int y1, int x2, int y2) { RectangleInt cb = new RectangleInt(x1, y1, x2, y2); cb.normalize(); if (cb.clip(new RectangleInt(0, 0, (int)Width - 1, (int)Height - 1))) { m_ClippingRect = cb; return true; } m_ClippingRect.Left = 1; m_ClippingRect.Bottom = 1; m_ClippingRect.Right = 0; m_ClippingRect.Top = 0; return false; } public void reset_clipping(bool visibility) { if (visibility) { m_ClippingRect.Left = 0; m_ClippingRect.Bottom = 0; m_ClippingRect.Right = (int)Width - 1; m_ClippingRect.Top = (int)Height - 1; } else { m_ClippingRect.Left = 1; m_ClippingRect.Bottom = 1; m_ClippingRect.Right = 0; m_ClippingRect.Top = 0; } } public void clip_box_naked(int x1, int y1, int x2, int y2) { m_ClippingRect.Left = x1; m_ClippingRect.Bottom = y1; m_ClippingRect.Right = x2; m_ClippingRect.Top = y2; } public bool inbox(int x, int y) { return x >= m_ClippingRect.Left && y >= m_ClippingRect.Bottom && x <= m_ClippingRect.Right && y <= m_ClippingRect.Top; } public RectangleInt clip_box() { return m_ClippingRect; } private int xmin() { return m_ClippingRect.Left; } private int ymin() { return m_ClippingRect.Bottom; } private int xmax() { return m_ClippingRect.Right; } private int ymax() { return m_ClippingRect.Top; } public RectangleInt bounding_clip_box() { return m_ClippingRect; } public int bounding_xmin() { return m_ClippingRect.Left; } public int bounding_ymin() { return m_ClippingRect.Bottom; } public int bounding_xmax() { return m_ClippingRect.Right; } public int bounding_ymax() { return m_ClippingRect.Top; } public void clear(IColorType in_c) { int y; RGBA_Bytes c = new RGBA_Bytes(in_c.Red0To255, in_c.Green0To255, in_c.Blue0To255, in_c.Alpha0To255); if (Width != 0) { for (y = 0; y < Height; y++) { base.copy_hline(0, (int)y, (int)Width, c); } } } public override void copy_pixel(int x, int y, byte[] c, int ByteOffset) { if (inbox(x, y)) { base.copy_pixel(x, y, c, ByteOffset); } } public override RGBA_Bytes GetPixel(int x, int y) { return inbox(x, y) ? base.GetPixel(x, y) : new RGBA_Bytes(); } public override void copy_hline(int x1, int y, int x2, RGBA_Bytes c) { if (x1 > x2) { int t = (int)x2; x2 = (int)x1; x1 = t; } if (y > ymax()) return; if (y < ymin()) return; if (x1 > xmax()) return; if (x2 < xmin()) return; if (x1 < xmin()) x1 = xmin(); if (x2 > xmax()) x2 = (int)xmax(); base.copy_hline(x1, y, (int)(x2 - x1 + 1), c); } public override void copy_vline(int x, int y1, int y2, RGBA_Bytes c) { if (y1 > y2) { int t = (int)y2; y2 = (int)y1; y1 = t; } if (x > xmax()) return; if (x < xmin()) return; if (y1 > ymax()) return; if (y2 < ymin()) return; if (y1 < ymin()) y1 = ymin(); if (y2 > ymax()) y2 = (int)ymax(); base.copy_vline(x, y1, (int)(y2 - y1 + 1), c); } public override void blend_hline(int x1, int y, int x2, RGBA_Bytes c, byte cover) { if (x1 > x2) { int t = (int)x2; x2 = x1; x1 = t; } if (y > ymax()) return; if (y < ymin()) return; if (x1 > xmax()) return; if (x2 < xmin()) return; if (x1 < xmin()) x1 = xmin(); if (x2 > xmax()) x2 = xmax(); base.blend_hline(x1, y, x2, c, cover); } public override void blend_vline(int x, int y1, int y2, RGBA_Bytes c, byte cover) { if (y1 > y2) { int t = y2; y2 = y1; y1 = t; } if (x > xmax()) return; if (x < xmin()) return; if (y1 > ymax()) return; if (y2 < ymin()) return; if (y1 < ymin()) y1 = ymin(); if (y2 > ymax()) y2 = ymax(); base.blend_vline(x, y1, y2, c, cover); } public override void blend_solid_hspan(int x, int y, int len, RGBA_Bytes c, byte[] covers, int coversIndex) { #if false FileStream file = new FileStream("pixels.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(file); sw.Write("h-x=" + x.ToString() + ",y=" + y.ToString() + ",len=" + len.ToString() + "\n"); sw.Close(); file.Close(); #endif if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { len -= xmin() - x; if (len <= 0) return; coversIndex += xmin() - x; x = xmin(); } if (x + len > xmax()) { len = xmax() - x + 1; if (len <= 0) return; } base.blend_solid_hspan(x, y, len, c, covers, coversIndex); } public override void blend_solid_vspan(int x, int y, int len, RGBA_Bytes c, byte[] covers, int coversIndex) { #if false FileStream file = new FileStream("pixels.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(file); sw.Write("v-x=" + x.ToString() + ",y=" + y.ToString() + ",len=" + len.ToString() + "\n"); sw.Close(); file.Close(); #endif if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { len -= (ymin() - y); if (len <= 0) return; coversIndex += ymin() - y; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.blend_solid_vspan(x, y, len, c, covers, coversIndex); } public override void copy_color_hspan(int x, int y, int len, RGBA_Bytes[] colors, int colorsIndex) { if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { int d = xmin() - x; len -= d; if (len <= 0) return; colorsIndex += d; x = xmin(); } if (x + len > xmax()) { len = (xmax() - x + 1); if (len <= 0) return; } base.copy_color_hspan(x, y, len, colors, colorsIndex); } public override void copy_color_vspan(int x, int y, int len, RGBA_Bytes[] colors, int colorsIndex) { if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { int d = ymin() - y; len -= d; if (len <= 0) return; colorsIndex += d; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.copy_color_vspan(x, y, len, colors, colorsIndex); } public override void blend_color_hspan(int x, int y, int in_len, RGBA_Bytes[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { int len = (int)in_len; if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { int d = xmin() - x; len -= d; if (len <= 0) return; if (covers != null) coversIndex += d; colorsIndex += d; x = xmin(); } if (x + len - 1 > xmax()) { len = xmax() - x + 1; if (len <= 0) return; } base.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public void copy_from(IImageByte src) { CopyFrom(src, new RectangleInt(0, 0, (int)src.Width, (int)src.Height), 0, 0); } public override void SetPixel(int x, int y, RGBA_Bytes color) { if ((uint)x < Width && (uint)y < Height) { base.SetPixel(x, y, color); } } public override void CopyFrom(IImageByte sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset) { RectangleInt destRect = sourceImageRect; destRect.Offset(destXOffset, destYOffset); RectangleInt clippedSourceRect = new RectangleInt(); if (clippedSourceRect.IntersectRectangles(destRect, m_ClippingRect)) { // move it back relative to the source clippedSourceRect.Offset(-destXOffset, -destYOffset); base.CopyFrom(sourceImage, clippedSourceRect, destXOffset, destYOffset); } } public RectangleInt clip_rect_area(ref RectangleInt destRect, ref RectangleInt sourceRect, int sourceWidth, int sourceHeight) { RectangleInt rc = new RectangleInt(0, 0, 0, 0); RectangleInt cb = clip_box(); ++cb.Right; ++cb.Top; if (sourceRect.Left < 0) { destRect.Left -= sourceRect.Left; sourceRect.Left = 0; } if (sourceRect.Bottom < 0) { destRect.Bottom -= sourceRect.Bottom; sourceRect.Bottom = 0; } if (sourceRect.Right > sourceWidth) sourceRect.Right = sourceWidth; if (sourceRect.Top > sourceHeight) sourceRect.Top = sourceHeight; if (destRect.Left < cb.Left) { sourceRect.Left += cb.Left - destRect.Left; destRect.Left = cb.Left; } if (destRect.Bottom < cb.Bottom) { sourceRect.Bottom += cb.Bottom - destRect.Bottom; destRect.Bottom = cb.Bottom; } if (destRect.Right > cb.Right) destRect.Right = cb.Right; if (destRect.Top > cb.Top) destRect.Top = cb.Top; rc.Right = destRect.Right - destRect.Left; rc.Top = destRect.Top - destRect.Bottom; if (rc.Right > sourceRect.Right - sourceRect.Left) rc.Right = sourceRect.Right - sourceRect.Left; if (rc.Top > sourceRect.Top - sourceRect.Bottom) rc.Top = sourceRect.Top - sourceRect.Bottom; return rc; } public override void blend_color_vspan(int x, int y, int len, RGBA_Bytes[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { int d = ymin() - y; len -= d; if (len <= 0) return; if (covers != null) coversIndex += d; colorsIndex += d; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } } public class ImageClippingProxyFloat : ImageProxyFloat { private RectangleInt m_ClippingRect; public const byte cover_full = 255; public ImageClippingProxyFloat(IImageFloat ren) : base(ren) { m_ClippingRect = new RectangleInt(0, 0, (int)ren.Width - 1, (int)ren.Height - 1); } public override void LinkToImage(IImageFloat ren) { base.LinkToImage(ren); m_ClippingRect = new RectangleInt(0, 0, (int)ren.Width - 1, (int)ren.Height - 1); } public bool SetClippingBox(int x1, int y1, int x2, int y2) { RectangleInt cb = new RectangleInt(x1, y1, x2, y2); cb.normalize(); if (cb.clip(new RectangleInt(0, 0, (int)Width - 1, (int)Height - 1))) { m_ClippingRect = cb; return true; } m_ClippingRect.Left = 1; m_ClippingRect.Bottom = 1; m_ClippingRect.Right = 0; m_ClippingRect.Top = 0; return false; } public void reset_clipping(bool visibility) { if (visibility) { m_ClippingRect.Left = 0; m_ClippingRect.Bottom = 0; m_ClippingRect.Right = (int)Width - 1; m_ClippingRect.Top = (int)Height - 1; } else { m_ClippingRect.Left = 1; m_ClippingRect.Bottom = 1; m_ClippingRect.Right = 0; m_ClippingRect.Top = 0; } } public void clip_box_naked(int x1, int y1, int x2, int y2) { m_ClippingRect.Left = x1; m_ClippingRect.Bottom = y1; m_ClippingRect.Right = x2; m_ClippingRect.Top = y2; } public bool inbox(int x, int y) { return x >= m_ClippingRect.Left && y >= m_ClippingRect.Bottom && x <= m_ClippingRect.Right && y <= m_ClippingRect.Top; } public RectangleInt clip_box() { return m_ClippingRect; } private int xmin() { return m_ClippingRect.Left; } private int ymin() { return m_ClippingRect.Bottom; } private int xmax() { return m_ClippingRect.Right; } private int ymax() { return m_ClippingRect.Top; } public RectangleInt bounding_clip_box() { return m_ClippingRect; } public int bounding_xmin() { return m_ClippingRect.Left; } public int bounding_ymin() { return m_ClippingRect.Bottom; } public int bounding_xmax() { return m_ClippingRect.Right; } public int bounding_ymax() { return m_ClippingRect.Top; } public void clear(IColorType in_c) { int y; RGBA_Floats colorFloat = in_c.GetAsRGBA_Floats(); if (Width != 0) { for (y = 0; y < Height; y++) { base.copy_hline(0, (int)y, (int)Width, colorFloat); } } } public override void copy_pixel(int x, int y, float[] c, int ByteOffset) { if (inbox(x, y)) { base.copy_pixel(x, y, c, ByteOffset); } } public override RGBA_Floats GetPixel(int x, int y) { return inbox(x, y) ? base.GetPixel(x, y) : new RGBA_Floats(); } public override void copy_hline(int x1, int y, int x2, RGBA_Floats c) { if (x1 > x2) { int t = (int)x2; x2 = (int)x1; x1 = t; } if (y > ymax()) return; if (y < ymin()) return; if (x1 > xmax()) return; if (x2 < xmin()) return; if (x1 < xmin()) x1 = xmin(); if (x2 > xmax()) x2 = (int)xmax(); base.copy_hline(x1, y, (int)(x2 - x1 + 1), c); } public override void copy_vline(int x, int y1, int y2, RGBA_Floats c) { if (y1 > y2) { int t = (int)y2; y2 = (int)y1; y1 = t; } if (x > xmax()) return; if (x < xmin()) return; if (y1 > ymax()) return; if (y2 < ymin()) return; if (y1 < ymin()) y1 = ymin(); if (y2 > ymax()) y2 = (int)ymax(); base.copy_vline(x, y1, (int)(y2 - y1 + 1), c); } public override void blend_hline(int x1, int y, int x2, RGBA_Floats c, byte cover) { if (x1 > x2) { int t = (int)x2; x2 = x1; x1 = t; } if (y > ymax()) return; if (y < ymin()) return; if (x1 > xmax()) return; if (x2 < xmin()) return; if (x1 < xmin()) x1 = xmin(); if (x2 > xmax()) x2 = xmax(); base.blend_hline(x1, y, x2, c, cover); } public override void blend_vline(int x, int y1, int y2, RGBA_Floats c, byte cover) { if (y1 > y2) { int t = y2; y2 = y1; y1 = t; } if (x > xmax()) return; if (x < xmin()) return; if (y1 > ymax()) return; if (y2 < ymin()) return; if (y1 < ymin()) y1 = ymin(); if (y2 > ymax()) y2 = ymax(); base.blend_vline(x, y1, y2, c, cover); } public override void blend_solid_hspan(int x, int y, int in_len, RGBA_Floats c, byte[] covers, int coversIndex) { int len = (int)in_len; if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { len -= xmin() - x; if (len <= 0) return; coversIndex += xmin() - x; x = xmin(); } if (x + len > xmax()) { len = xmax() - x + 1; if (len <= 0) return; } base.blend_solid_hspan(x, y, len, c, covers, coversIndex); } public override void blend_solid_vspan(int x, int y, int len, RGBA_Floats c, byte[] covers, int coversIndex) { if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { len -= (ymin() - y); if (len <= 0) return; coversIndex += ymin() - y; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.blend_solid_vspan(x, y, len, c, covers, coversIndex); } public override void copy_color_hspan(int x, int y, int len, RGBA_Floats[] colors, int colorsIndex) { if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { int d = xmin() - x; len -= d; if (len <= 0) return; colorsIndex += d; x = xmin(); } if (x + len > xmax()) { len = (xmax() - x + 1); if (len <= 0) return; } base.copy_color_hspan(x, y, len, colors, colorsIndex); } public override void copy_color_vspan(int x, int y, int len, RGBA_Floats[] colors, int colorsIndex) { if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { int d = ymin() - y; len -= d; if (len <= 0) return; colorsIndex += d; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.copy_color_vspan(x, y, len, colors, colorsIndex); } public override void blend_color_hspan(int x, int y, int in_len, RGBA_Floats[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { int len = (int)in_len; if (y > ymax()) return; if (y < ymin()) return; if (x < xmin()) { int d = xmin() - x; len -= d; if (len <= 0) return; if (covers != null) coversIndex += d; colorsIndex += d; x = xmin(); } if (x + len - 1 > xmax()) { len = xmax() - x + 1; if (len <= 0) return; } base.blend_color_hspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } public void copy_from(IImageFloat src) { CopyFrom(src, new RectangleInt(0, 0, (int)src.Width, (int)src.Height), 0, 0); } public override void SetPixel(int x, int y, RGBA_Floats color) { if ((uint)x < Width && (uint)y < Height) { base.SetPixel(x, y, color); } } public override void CopyFrom(IImageFloat sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset) { RectangleInt destRect = sourceImageRect; destRect.Offset(destXOffset, destYOffset); RectangleInt clippedSourceRect = new RectangleInt(); if (clippedSourceRect.IntersectRectangles(destRect, m_ClippingRect)) { // move it back relative to the source clippedSourceRect.Offset(-destXOffset, -destYOffset); base.CopyFrom(sourceImage, clippedSourceRect, destXOffset, destYOffset); } } public RectangleInt clip_rect_area(ref RectangleInt destRect, ref RectangleInt sourceRect, int sourceWidth, int sourceHeight) { RectangleInt rc = new RectangleInt(0, 0, 0, 0); RectangleInt cb = clip_box(); ++cb.Right; ++cb.Top; if (sourceRect.Left < 0) { destRect.Left -= sourceRect.Left; sourceRect.Left = 0; } if (sourceRect.Bottom < 0) { destRect.Bottom -= sourceRect.Bottom; sourceRect.Bottom = 0; } if (sourceRect.Right > sourceWidth) sourceRect.Right = sourceWidth; if (sourceRect.Top > sourceHeight) sourceRect.Top = sourceHeight; if (destRect.Left < cb.Left) { sourceRect.Left += cb.Left - destRect.Left; destRect.Left = cb.Left; } if (destRect.Bottom < cb.Bottom) { sourceRect.Bottom += cb.Bottom - destRect.Bottom; destRect.Bottom = cb.Bottom; } if (destRect.Right > cb.Right) destRect.Right = cb.Right; if (destRect.Top > cb.Top) destRect.Top = cb.Top; rc.Right = destRect.Right - destRect.Left; rc.Top = destRect.Top - destRect.Bottom; if (rc.Right > sourceRect.Right - sourceRect.Left) rc.Right = sourceRect.Right - sourceRect.Left; if (rc.Top > sourceRect.Top - sourceRect.Bottom) rc.Top = sourceRect.Top - sourceRect.Bottom; return rc; } public override void blend_color_vspan(int x, int y, int len, RGBA_Floats[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll) { if (x > xmax()) return; if (x < xmin()) return; if (y < ymin()) { int d = ymin() - y; len -= d; if (len <= 0) return; if (covers != null) coversIndex += d; colorsIndex += d; y = ymin(); } if (y + len > ymax()) { len = (ymax() - y + 1); if (len <= 0) return; } base.blend_color_vspan(x, y, len, colors, colorsIndex, covers, coversIndex, firstCoverForAll); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; using System; using System.Linq; using MoonSharp.Interpreter; using MoonSharp.VsCodeDebugger; namespace Fungus { /// <summary> /// Wrapper for a MoonSharp Lua Script instance. /// A debug server is started automatically when running in the Unity Editor. Use VS Code to debug Lua scripts. /// </summary> public class LuaEnvironment : MonoBehaviour { /// <summary> /// The MoonSharp interpreter instance. /// </summary> protected Script interpreter; /// <summary> /// Flag used to avoid startup dependency issues. /// </summary> protected bool initialised = false; protected virtual void Start() { InitEnvironment(); } /// <summary> /// Detach the MoonSharp script from the debugger. /// </summary> protected virtual void OnDestroy() { if (DebugServer != null) { DebugServer.Detach(interpreter); } } /// <summary> /// Register all Lua files in the project so they can be accessed at runtime. /// </summary> protected virtual void InitLuaScriptFiles() { object[] result = Resources.LoadAll("Lua", typeof(TextAsset)); interpreter.Options.ScriptLoader = new LuaScriptLoader(result.OfType<TextAsset>()); } /// <summary> /// A Unity coroutine method which updates a Lua coroutine each frame. /// <param name="closure">A MoonSharp closure object representing a function.</param> /// <param name="onComplete">A delegate method that is called when the coroutine completes. Includes return parameter.</param> /// </summary> protected virtual IEnumerator RunLuaCoroutine(Closure closure, Action<DynValue> onComplete = null) { DynValue co = interpreter.CreateCoroutine(closure); DynValue returnValue = null; while (co.Coroutine.State != CoroutineState.Dead) { try { returnValue = co.Coroutine.Resume(); } catch (InterpreterException ex) { LogException(ex.DecoratedMessage, GetSourceCode()); } yield return null; } if (onComplete != null) { onComplete(returnValue); } } protected virtual string GetSourceCode() { // Get most recently executed source code string sourceCode = ""; if (interpreter.SourceCodeCount > 0) { MoonSharp.Interpreter.Debugging.SourceCode sc = interpreter.GetSourceCode(interpreter.SourceCodeCount - 1); if (sc != null) { sourceCode = sc.Code; } } return sourceCode; } /// <summary> /// Starts a standard Unity coroutine. /// The coroutine is managed by the LuaEnvironment monobehavior, so you can call StopAllCoroutines to /// stop all active coroutines later. /// </summary> protected virtual IEnumerator RunUnityCoroutineImpl(IEnumerator coroutine) { if (coroutine == null) { UnityEngine.Debug.LogWarning("Coroutine must not be null"); yield break; } yield return StartCoroutine(coroutine); } protected virtual void StartVSCodeDebugger() { if (DebugServer == null) { // Create the debugger server DebugServer = new MoonSharpVsCodeDebugServer(); // Start the debugger server DebugServer.Start(); } } /// <summary> /// Writes a MoonSharp exception to the debug log in a helpful format. /// </summary> /// <param name="decoratedMessage">Decorated message from a MoonSharp exception</param> /// <param name="debugInfo">Debug info, usually the Lua script that was running.</param> protected static void LogException(string decoratedMessage, string debugInfo) { string output = decoratedMessage + "\n"; char[] separators = { '\r', '\n' }; string[] lines = debugInfo.Split(separators, StringSplitOptions.None); // Show line numbers for script listing int count = 1; foreach (string line in lines) { output += count.ToString() + ": " + line + "\n"; count++; } UnityEngine.Debug.LogError(output); } #region Public members /// <summary> /// Instance of VS Code debug server when debugging option is enabled. /// </summary> public static MoonSharpVsCodeDebugServer DebugServer { get; private set; } /// <summary> /// Returns the first Lua Environment found in the scene, or creates one if none exists. /// This is a slow operation, call it once at startup and cache the returned value. /// </summary> public static LuaEnvironment GetLua() { var luaEnv = GameObject.FindObjectOfType<LuaEnvironment>(); if (luaEnv == null) { GameObject prefab = Resources.Load<GameObject>("Prefabs/LuaEnvironment"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "LuaEnvironment"; luaEnv = go.GetComponent<LuaEnvironment>(); } } return luaEnv; } /// <summary> /// Register a type given it's assembly qualified name. /// </summary> public static void RegisterType(string typeName, bool extensionType = false) { System.Type t = null; try { t = System.Type.GetType(typeName); } catch {} if (t == null) { UnityEngine.Debug.LogWarning("Type not found: " + typeName); return; } // Registering System.Object breaks MoonSharp's automated conversion of Lists and Dictionaries to Lua tables. if (t == typeof(System.Object)) { return; } if (!UserData.IsTypeRegistered(t)) { try { if (extensionType) { UserData.RegisterExtensionType(t); } else { UserData.RegisterType(t); } } catch (ArgumentException ex) { UnityEngine.Debug.LogWarning(ex.Message); } } } /// <summary> /// Start a Unity coroutine from a Lua call. /// </summary> public virtual Task RunUnityCoroutine(IEnumerator coroutine) { if (coroutine == null) { return null; } // We use the Task class so we can poll the coroutine to check if it has finished. // Standard Unity coroutines don't support this check. return new Task(RunUnityCoroutineImpl(coroutine)); } /// <summary> /// Initialise the Lua interpreter so we can start running Lua code. /// </summary> public virtual void InitEnvironment() { if (initialised) { return; } Script.DefaultOptions.DebugPrint = (s) => { UnityEngine.Debug.Log(s); }; // In some use cases (e.g. downloadable Lua files) some Lua modules can pose a potential security risk. // You can restrict which core lua modules are available here if needed. See the MoonSharp documentation for details. interpreter = new Script(CoreModules.Preset_Complete); // Load all Lua scripts in the project InitLuaScriptFiles(); // Initialize any attached initializer components (e.g. LuaUtils) LuaEnvironmentInitializer[] initializers = GetComponents<LuaEnvironmentInitializer>(); foreach (LuaEnvironmentInitializer initializer in initializers) { initializer.Initialize(); } // // Change this to #if UNITY_STANDALONE if you want to debug a standalone build. // #if UNITY_EDITOR StartVSCodeDebugger(); // Attach the MoonSharp script to the debugger DebugServer.AttachToScript(interpreter, gameObject.name); #endif initialised = true; } /// <summary> /// The MoonSharp interpreter instance used to run Lua code. /// </summary> public virtual Script Interpreter { get { return interpreter; } } /// <summary> /// Loads and compiles a string containing Lua script, returning a closure (Lua function) which can be executed later. /// <param name="luaString">The Lua code to be run.</param> /// <param name="friendlyName">A descriptive name to be used in error reports.</param> /// </summary> public virtual Closure LoadLuaFunction(string luaString, string friendlyName) { InitEnvironment(); string processedString; var initializer = GetComponent<LuaEnvironmentInitializer>(); if (initializer != null) { processedString = initializer.PreprocessScript(luaString); } else { processedString = luaString; } // Load the Lua script DynValue res = null; try { res = interpreter.LoadString(processedString, null, friendlyName); } catch (InterpreterException ex) { LogException(ex.DecoratedMessage, luaString); } if (res == null || res.Type != DataType.Function) { UnityEngine.Debug.LogError("Failed to create Lua function from Lua string"); return null; } return res.Function; } /// <summary> /// Load and run a previously compiled Lua script. May be run as a coroutine. /// <param name="fn">A previously compiled Lua function.</param> /// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param> /// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param> /// </summary> public virtual void RunLuaFunction(Closure fn, bool runAsCoroutine, Action<DynValue> onComplete = null) { if (fn == null) { if (onComplete != null) { onComplete(null); } return; } // Execute the Lua script if (runAsCoroutine) { StartCoroutine(RunLuaCoroutine(fn, onComplete)); } else { DynValue returnValue = null; try { returnValue = fn.Call(); } catch (InterpreterException ex) { LogException(ex.DecoratedMessage, GetSourceCode()); } if (onComplete != null) { onComplete(returnValue); } } } /// <summary> /// Load and run a string containing Lua script. May be run as a coroutine. /// <param name="luaString">The Lua code to be run.</param> /// <param name="friendlyName">A descriptive name to be used in error reports.</param> /// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param> /// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param> /// </summary> public virtual void DoLuaString(string luaString, string friendlyName, bool runAsCoroutine, Action<DynValue> onComplete = null) { Closure fn = LoadLuaFunction(luaString, friendlyName); RunLuaFunction(fn, runAsCoroutine, onComplete); } #endregion } }
using GitHub.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace GitHub.Unity { public abstract class BaseSettings : ISettings { public abstract bool Exists(string key); public abstract string Get(string key, string fallback = ""); public abstract T Get<T>(string key, T fallback = default(T)); public abstract void Initialize(); public abstract void Rename(string oldKey, string newKey); public abstract void Set<T>(string key, T value); public abstract void Unset(string key); public NPath SettingsPath { get; set; } protected virtual string SettingsFileName { get; set; } } public class JsonBackedSettings : BaseSettings { private string cachePath; protected Dictionary<string, object> cacheData; private Action<string> dirCreate; private Func<string, bool> dirExists; private Action<string> fileDelete; private Func<string, bool> fileExists; private Func<string, Encoding, string> readAllText; private Action<string, string> writeAllText; private readonly ILogging logger; public JsonBackedSettings() { logger = LogHelper.GetLogger(GetType()); fileExists = (path) => File.Exists(path); readAllText = (path, encoding) => File.ReadAllText(path, encoding); writeAllText = (path, content) => File.WriteAllText(path, content); fileDelete = (path) => File.Delete(path); dirExists = (path) => Directory.Exists(path); dirCreate = (path) => Directory.CreateDirectory(path); } public override void Initialize() { cachePath = SettingsPath.Combine(SettingsFileName); LoadFromCache(cachePath); } public override bool Exists(string key) { if (cacheData == null) Initialize(); return cacheData.ContainsKey(key); } public override string Get(string key, string fallback = "") { return Get<string>(key, fallback); } public override T Get<T>(string key, T fallback = default(T)) { if (cacheData == null) Initialize(); object value = null; if (cacheData.TryGetValue(key, out value)) { if (typeof(T) == typeof(DateTimeOffset)) { DateTimeOffset dt; if (DateTimeOffset.TryParseExact(value?.ToString().ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { value = dt; cacheData[key] = dt; } } if (value == null && fallback != null) { value = fallback; cacheData[key] = fallback; } else if (!(value is T)) { try { value = value.FromObject<T>(); cacheData[key] = value; } catch { value = fallback; cacheData[key] = fallback; } } return (T)value; } return fallback; } public override void Set<T>(string key, T value) { if (cacheData == null) Initialize(); try { object val = value; if (value is DateTimeOffset) val = ((DateTimeOffset)(object)value).ToString(Constants.Iso8601Format); if (!cacheData.ContainsKey(key)) cacheData.Add(key, val); else cacheData[key] = val; SaveToCache(cachePath); } catch (Exception e) { logger.Error(e, "Error storing to cache"); throw; } } public override void Unset(string key) { if (cacheData == null) Initialize(); if (cacheData.ContainsKey(key)) cacheData.Remove(key); SaveToCache(cachePath); } public override void Rename(string oldKey, string newKey) { if (cacheData == null) Initialize(); object value = null; if (cacheData.TryGetValue(oldKey, out value)) { cacheData.Remove(oldKey); Set(newKey, value); } SaveToCache(cachePath); } protected virtual void LoadFromCache(string path) { EnsureCachePath(path); if (!fileExists(path)) { cacheData = new Dictionary<string, object>(); return; } var data = readAllText(path, Encoding.UTF8); try { var c = data.FromJson<Dictionary<string, object>>(); if (c != null) { // upgrade from old format if (c.ContainsKey("GitHubUnity")) { var oldRoot = c["GitHubUnity"]; cacheData = oldRoot.FromObject<Dictionary<string, object>>(); SaveToCache(path); } else cacheData = c; } else cacheData = null; } catch(Exception ex) { logger.Error(ex, "LoadFromCache Error"); cacheData = null; } if (cacheData == null) { // cache is corrupt, remove fileDelete(path); cacheData = new Dictionary<string, object>(); } } protected virtual bool SaveToCache(string path) { EnsureCachePath(path); try { var data = cacheData.ToJson(); writeAllText(path, data); } catch (Exception ex) { logger.Error(ex, "SaveToCache Error"); return false; } return true; } private void EnsureCachePath(string path) { if (fileExists(path)) return; var di = Path.GetDirectoryName(path); if (!dirExists(di)) dirCreate(di); } } public class LocalSettings : JsonBackedSettings { private const string RelativeSettingsPath = "ProjectSettings"; private const string settingsFileName = "GitHub.local.json"; public LocalSettings(IEnvironment environment) { SettingsPath = environment.UnityProjectPath.Combine(RelativeSettingsPath); } protected override string SettingsFileName { get { return settingsFileName; } } } public class UserSettings : JsonBackedSettings { private const string settingsFileName = "usersettings.json"; private const string oldSettingsFileName = "settings.json"; public UserSettings(IEnvironment environment) { SettingsPath = environment.UserCachePath; } public override void Initialize() { var cachePath = SettingsPath.Combine(settingsFileName); if (!cachePath.FileExists()) { var oldSettings = SettingsPath.Combine(oldSettingsFileName); if (oldSettings.FileExists()) oldSettings.Copy(cachePath); } base.Initialize(); } protected override string SettingsFileName { get { return settingsFileName; } } } public class SystemSettings : JsonBackedSettings { private const string settingsFileName = "systemsettings.json"; private const string oldSettingsFileName = "settings.json"; public SystemSettings(IEnvironment environment) { SettingsPath = environment.SystemCachePath; } public override void Initialize() { var cachePath = SettingsPath.Combine(settingsFileName); if (!cachePath.FileExists()) { var oldSettings = SettingsPath.Combine(oldSettingsFileName); if (oldSettings.FileExists()) oldSettings.Copy(cachePath); } base.Initialize(); } protected override string SettingsFileName { get { return settingsFileName; } } } }
// // InternetRadioSource.cs // // Author: // Aaron Bockover <abockover@novell.com> // // 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 Mono.Unix; using Gtk; using Hyena; using Banshee.Base; using Banshee.Sources; using Banshee.Streaming; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.PlaybackController; using Banshee.Gui; using Banshee.Sources.Gui; namespace Banshee.InternetRadio { public class InternetRadioSource : PrimarySource, IDisposable, IBasicPlaybackController { private uint ui_id; public InternetRadioSource () : base (Catalog.GetString ("Radio"), Catalog.GetString ("Radio"), "internet-radio", 52) { Properties.SetString ("Icon.Name", "radio"); TypeUniqueId = "internet-radio"; IsLocal = false; AfterInitialized (); InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); uia_service.GlobalActions.Add ( new ActionEntry ("AddRadioStationAction", Stock.Add, Catalog.GetString ("Add Station"), null, Catalog.GetString ("Add a new Internet Radio station or playlist"), OnAddStation) ); uia_service.GlobalActions["AddRadioStationAction"].IsImportant = false; ui_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml"); Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml"); Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true); Properties.Set<bool> ("SourceView.HideCount", true); Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", typeof(InternetRadioSource).Assembly); Properties.SetString ("GtkActionPath", "/InternetRadioContextMenu"); Properties.Set<bool> ("Nereid.SourceContentsPropagate", true); Properties.Set<ISourceContents> ("Nereid.SourceContents", new LazyLoadSourceContents<InternetRadioSourceContents> ()); Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search your stations")); Properties.SetString ("TrackEditorActionLabel", Catalog.GetString ("Edit Station")); Properties.Set<InvokeHandler> ("TrackEditorActionHandler", delegate { var track_actions = ServiceManager.Get<InterfaceActionService> ().TrackActions; var tracks = track_actions.SelectedTracks; if (tracks == null || tracks.Count <= 0) { return; } foreach (var track in tracks) { var station_track = track as DatabaseTrackInfo; if (station_track != null) { EditStation (station_track); return; } } }); Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@" <column-controller> <!--<column modify-default=""IndicatorColumn""> <renderer type=""Banshee.Podcasting.Gui.ColumnCellPodcastStatusIndicator"" /> </column>--> <add-default column=""IndicatorColumn"" /> <add-default column=""GenreColumn"" /> <column modify-default=""GenreColumn""> <visible>false</visible> </column> <add-default column=""TitleColumn"" /> <column modify-default=""TitleColumn""> <title>{0}</title> <long-title>{0}</long-title> </column> <add-default column=""ArtistColumn"" /> <column modify-default=""ArtistColumn""> <title>{1}</title> <long-title>{1}</long-title> </column> <add-default column=""CommentColumn"" /> <column modify-default=""CommentColumn""> <title>{2}</title> <long-title>{2}</long-title> </column> <add-default column=""RatingColumn"" /> <add-default column=""PlayCountColumn"" /> <add-default column=""LastPlayedColumn"" /> <add-default column=""LastSkippedColumn"" /> <add-default column=""DateAddedColumn"" /> <add-default column=""UriColumn"" /> <sort-column direction=""asc"">genre</sort-column> </column-controller>", Catalog.GetString ("Station"), Catalog.GetString ("Creator"), Catalog.GetString ("Description") )); ServiceManager.PlayerEngine.TrackIntercept += OnPlayerEngineTrackIntercept; //ServiceManager.PlayerEngine.ConnectEvent (OnTrackInfoUpdated, Banshee.MediaEngine.PlayerEvent.TrackInfoUpdated); TrackEqualHandler = delegate (DatabaseTrackInfo a, TrackInfo b) { RadioTrackInfo radio_track = b as RadioTrackInfo; return radio_track != null && DatabaseTrackInfo.TrackEqual ( radio_track.ParentTrack as DatabaseTrackInfo, a); }; if (new XspfMigrator (this).Migrate ()) { Reload (); } } public override string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} station", "{0} stations", count); } protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src) { DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection, Catalog.GetString ("All Genres ({0})"), src.UniqueId, Banshee.Query.BansheeQuery.GenreField, "Genre"); if (this == src) { this.genre_model = genre_model; } yield return genre_model; } public override void Dispose () { base.Dispose (); //ServiceManager.PlayerEngine.DisconnectEvent (OnTrackInfoUpdated); InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service == null) { return; } if (ui_id > 0) { uia_service.UIManager.RemoveUi (ui_id); uia_service.GlobalActions.Remove ("AddRadioStationAction"); ui_id = 0; } ServiceManager.PlayerEngine.TrackIntercept -= OnPlayerEngineTrackIntercept; } // TODO the idea with this is to grab and display cover art when we get updated info // for a radio station (eg it changes song and lets us know). The problem is I'm not sure // if that info ever/usually includes the album name, and also we would probably want to mark // such downloaded/cached cover art as temporary. /*private void OnTrackInfoUpdated (Banshee.MediaEngine.PlayerEventArgs args) { RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null) { Banshee.Metadata.MetadataService.Instance.Lookup (radio_track); } }*/ private bool OnPlayerEngineTrackIntercept (TrackInfo track) { DatabaseTrackInfo station = track as DatabaseTrackInfo; if (station == null || station.PrimarySource != this) { return false; } new RadioTrackInfo (station).Play (); return true; } private void OnAddStation (object o, EventArgs args) { EditStation (null); } private void EditStation (DatabaseTrackInfo track) { StationEditor editor = new StationEditor (track); editor.Response += OnStationEditorResponse; editor.Show (); } private void OnStationEditorResponse (object o, ResponseArgs args) { StationEditor editor = (StationEditor)o; bool destroy = true; try { if (args.ResponseId == ResponseType.Ok) { DatabaseTrackInfo track = editor.Track ?? new DatabaseTrackInfo (); track.PrimarySource = this; track.IsLive = true; try { track.Uri = new SafeUri (editor.StreamUri); } catch { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a valid station URI"); } if (!String.IsNullOrEmpty (editor.StationCreator)) { track.ArtistName = editor.StationCreator; } track.Comment = editor.Description; if (!String.IsNullOrEmpty (editor.Genre)) { track.Genre = editor.Genre; } else { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a station genre"); } if (!String.IsNullOrEmpty (editor.StationTitle)) { track.TrackTitle = editor.StationTitle; track.AlbumTitle = editor.StationTitle; } else { destroy = false; editor.ErrorMessage = Catalog.GetString ("Please provide a station title"); } track.Rating = editor.Rating; if (destroy) { track.Save (); } } } finally { if (destroy) { editor.Response -= OnStationEditorResponse; editor.Destroy (); } } } #region IBasicPlaybackController implementation public bool First () { return false; } public bool Next (bool restart, bool changeImmediately) { /* * TODO: It should be technically possible to handle changeImmediately=False * correctly here, but the current implementation is quite hostile. * For the moment, just SetNextTrack (null), and go on to OpenPlay if * the engine isn't currently playing. */ if (!changeImmediately) { ServiceManager.PlayerEngine.SetNextTrack ((SafeUri)null); if (ServiceManager.PlayerEngine.IsPlaying ()) { return true; } } RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null && radio_track.PlayNextStream ()) { return true; } else { return false; } } public bool Previous (bool restart) { RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo; if (radio_track != null && radio_track.PlayPreviousStream ()) { return true; } else { return false; } } #endregion public override bool AcceptsInputFromSource (Source source) { return false; } public override bool CanDeleteTracks { get { return false; } } public override bool ShowBrowser { get { return true; } } public override bool CanRename { get { return false; } } protected override bool HasArtistAlbum { get { return false; } } public override bool HasViewableTrackProperties { get { return false; } } public override bool HasEditableTrackProperties { get { return true; } } } }
/* * Copyright (c) 2010, www.wojilu.com. All rights reserved. */ using System; using System.Collections.Generic; using wojilu.Web.Mvc; using wojilu.Web.Mvc.Attr; using wojilu.Members.Users.Service; using wojilu.Members.Users.Domain; using wojilu.Members.Users.Interface; using wojilu.Common.Feeds.Service; using wojilu.Common.Feeds.Interface; using wojilu.Common.AppBase; using wojilu.Common.Tags; using wojilu.Apps.Blog.Domain; using wojilu.Apps.Blog.Service; using wojilu.Apps.Blog.Interface; using System.Text.RegularExpressions; namespace wojilu.Web.Controller.Blog.Admin { [App( typeof( BlogApp ) )] public partial class PostController : ControllerBase { public IBlogService blogService { get; set; } public IBlogCategoryService categoryService { get; set; } public IBlogPostService postService { get; set; } public IFeedService feedService { get; set; } public IFriendService friendService { get; set; } public PostController() { blogService = new BlogService(); postService = new BlogPostService(); categoryService = new BlogCategoryService(); feedService = new FeedService(); friendService = new FriendService(); } public void Add() { List<BlogCategory> categories = categoryService.GetByApp( ctx.app.Id ); Boolean showCategoryBox = categories.Count == 0; set( "showCategoryBox", showCategoryBox.ToString().ToLower() ); target( Create ); bindAdd( categories ); } [HttpPost, DbTransaction] public void Create() { BlogPost data = new BlogPost(); BlogCategory category = new BlogCategory(); category.Id = ctx.PostInt( "CategoryId" ); data.Category = category; data.Title = ctx.Post( "Title" ); data.Content = Regex.Replace(ctx.PostHtml("Content"), "font-size", "", RegexOptions.IgnoreCase); data.Abstract = ctx.Post("Abstract"); if (category.Id <= 0) errors.Add( lang( "exUnCategoryTip" ) ); if (strUtil.IsNullOrEmpty( data.Content )) errors.Add( lang( "exContent" ) ); if (ctx.HasErrors) { echoError(); return; } //if (ctx.PostIsCheck( "saveContentPic" ) == 1) { // // data.Content = wojilu.Net.PageLoader.ProcessPic( data.Content, null ); // data.IsPick = 1; //} //if (ctx.PostIsCheck("IsTop") == 1) //{ // //post.Content = wojilu.Net.PageLoader.ProcessPic( post.Content, null ); // data.IsTop = 1; //} if (ctx.PostIsCheck("IsRecommend") == 1) { //post.Content = wojilu.Net.PageLoader.ProcessPic( post.Content, null ); data.IsPic = 1; } if (strUtil.IsNullOrEmpty( data.Title )) data.Title = getDefaultTitle(); data.AccessStatus = (int)AccessStatusUtil.GetPostValue( ctx.PostInt( "AccessStatus" ) ); data.CommentCondition = cvt.ToInt( ctx.Post( "IsCloseComment" ) ); data.SaveStatus = 0; String tagStr = strUtil.SubString( ctx.Post( "TagList" ), 200 ); data.Tags = TagService.ResetRawTagString( tagStr ); populatePost( data ); Result result = postService.Insert( data ); if (result.IsValid) { echoRedirectPart( lang( "opok" ), to( new MyListController().Index ), 1 ); } else { echoError( result ); } } //-------------------------------- edit&save ------------------------------------------- public void Edit( int id ) { target( Update, id ); BlogPost data = postService.GetById( id, ctx.owner.Id ); if (data == null) { echoRedirect( lang( "exDataNotFound" ) ); return; } List<BlogCategory> categories = categoryService.GetByApp( ctx.app.Id ); bindEdit( data, categories ); } [HttpPost, DbTransaction] public void Update( int id ) { BlogPost post = postService.GetById( id, ctx.owner.Id ); if (post == null) { echoRedirect( lang( "exDataNotFound" ) ); return; } BlogCategory category = new BlogCategory(); category.Id = cvt.ToInt( ctx.Post( "CategoryId" ) ); post.Category = category; post.Abstract = ctx.Post( "Abstract" ); //post.Content = ctx.PostHtml( "Content" ); post.Content = Regex.Replace(ctx.PostHtml("Content"), "font-size", "", RegexOptions.IgnoreCase); post.Title = ctx.Post( "Title" ); if (strUtil.IsNullOrEmpty( post.Title ) || strUtil.IsNullOrEmpty( post.Content )) { echoRedirect( lang( "exTitleContent" ) ); return; } //if (ctx.PostIsCheck( "saveContentPic" ) == 1) { // //post.Content = wojilu.Net.PageLoader.ProcessPic( post.Content, null ); // post.IsPick = 1; //} //if (ctx.PostIsCheck("IsTop") == 1) //{ // //post.Content = wojilu.Net.PageLoader.ProcessPic( post.Content, null ); // post.IsTop = 1; //} if (ctx.PostIsCheck("IsRecommend") == 1) { //post.Content = wojilu.Net.PageLoader.ProcessPic( post.Content, null ); post.IsPic = 1; } post.AccessStatus = cvt.ToInt( ctx.Post( "AccessStatus" ) ); post.CommentCondition = cvt.ToInt( ctx.Post( "IsCloseComment" ) ); if (post.SaveStatus == SaveStatus.Draft) post.Created = DateTime.Now; post.SaveStatus = SaveStatus.Normal; post.Ip = ctx.Ip; Result result = db.update( post ); if (result.IsValid) { TagService.SaveDataTag( post, ctx.Post( "TagList" ) ); echoRedirectPart( lang( "opok" ), to( new MyListController().Index ), 1 ); } else { echoRedirect( result.ErrorsHtml ); } } //------------------------------ helper --------------------------------------------- private String getDefaultTitle() { return string.Format( "{0} " + lang( "log" ), DateTime.Now.ToShortDateString() ); } private void populatePost( BlogPost data ) { data.Ip = ctx.Ip; data.OwnerId = ctx.owner.Id; data.OwnerUrl = ctx.owner.obj.Url; data.OwnerType = ctx.owner.obj.GetType().FullName; data.Creator = (User)ctx.viewer.obj; data.CreatorUrl = ctx.viewer.obj.Url; data.AppId = ctx.app.Id; } private void bindAdd( List<BlogCategory> categories ) { set( "categoryAddUrl", to( new CategoryController().New ) ); set( "DraftActionUrl", to( new DraftController().SaveDraft ) ); //String dropList = Html.DropList( categories, "CategoryId", "Name", "Id", null ); //set( "categoryDropList", dropList ); dropList( "CategoryId", categories, "Name=Id", null ); editor( "Content", "", "400px" ); } private void bindEdit( BlogPost data, List<BlogCategory> categories ) { //String categoryDropList = Html.DropList( categories, "CategoryId", "Name", "Id", data.Category.Id ); //set( "data.CatetgoryId", categoryDropList ); dropList( "CategoryId", categories, "Name=Id", data.Category.Id ); set( "data.Id", data.Id ); set( "data.Abstract", data.Abstract ); set( "data.TagList", data.Tag.TextString ); set( "data.Title", data.Title ); editor( "Content", data.Content, "400px" ); set( "data.AccessStatus", AccessStatusUtil.GetRadioList( data.AccessStatus ) ); set( "data.IsCloseComment", Html.CheckBox( "IsCloseComment", lang( "closeComment" ), "1", cvt.ToBool( data.CommentCondition ) ) ); } } }
/* Copyright 2014 David Bordoley 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; namespace SQLitePCL.pretty { /// <summary> /// Represents information about a single column in <see cref="IStatement"/> result set. /// </summary> public sealed class ColumnInfo : IEquatable<ColumnInfo>, IComparable<ColumnInfo>, IComparable { /// <summary> /// Indicates whether the two ColumnInfo instances are equal to each other. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the two instances are equal to each other; otherwise, <see langword="false"/>.</returns> public static bool operator ==(ColumnInfo x, ColumnInfo y) => object.ReferenceEquals(x, null) ? object.ReferenceEquals(y, null) : x.Equals(y); /// <summary> /// Indicates whether the two ColumnInfo instances are not equal each other. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the two instances are not equal to each other; otherwise, <see langword="false"/>.</returns> public static bool operator !=(ColumnInfo x, ColumnInfo y) => !(x == y); /// <summary> /// Indicates if the the first ColumnInfo is greater than or equal to the second. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the the first ColumnInfo is greater than or equal to the second; otherwise, <see langword="false"/>.</returns> public static bool operator >=(ColumnInfo x, ColumnInfo y) => x.CompareTo(y) >= 0; /// <summary> /// Indicates if the the first ColumnInfo is greater than the second. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the the first ColumnInfo is greater than the second; otherwise, <see langword="false"/>.</returns> public static bool operator >(ColumnInfo x, ColumnInfo y) => x.CompareTo(y) > 0; /// <summary> /// Indicates if the the first ColumnInfo is less than or equal to the second. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the the first ColumnInfo is less than or equal to the second; otherwise, <see langword="false"/>.</returns> public static bool operator <=(ColumnInfo x, ColumnInfo y) => x.CompareTo(y) <= 0; /// <summary> /// Indicates if the the first ColumnInfo is less than the second. /// </summary> /// <param name="x">A ColumnInfo instance.</param> /// <param name="y">A ColumnInfo instance.</param> /// <returns><see langword="true"/> if the the first ColumnInfo is less than the second; otherwise, <see langword="false"/>.</returns> public static bool operator <(ColumnInfo x, ColumnInfo y) => x.CompareTo(y) < 0; private static T TryOrDefault<T>(Func<T> f, T defaultValue) { try { return f(); } catch { return defaultValue; } } internal static ColumnInfo Create(StatementImpl stmt, int index) => new ColumnInfo( raw.sqlite3_column_name(stmt.sqlite3_stmt, index), TryOrDefault (() => raw.sqlite3_column_database_name(stmt.sqlite3_stmt, index), ""), TryOrDefault (() => raw.sqlite3_column_origin_name(stmt.sqlite3_stmt, index), ""), TryOrDefault (() => raw.sqlite3_column_table_name(stmt.sqlite3_stmt, index), ""), raw.sqlite3_column_decltype(stmt.sqlite3_stmt, index)); /// <summary> /// The column name. /// </summary> /// <seealso href="https://sqlite.org/c3ref/column_name.html"/> public string Name { get; } /// <summary> /// The database that is the origin of this particular result column. /// </summary> /// <seealso href="https://sqlite.org/c3ref/column_database_name.html"/> public string DatabaseName { get; } /// <summary> /// The table that is the origin of this particular result column. /// </summary> /// <seealso href="https://sqlite.org/c3ref/column_database_name.html"/> public string TableName { get; } /// <summary> /// The column that is the origin of this particular result column. /// </summary> /// <seealso href="https://sqlite.org/c3ref/column_database_name.html"/> public string OriginName { get; } /// <summary> /// Returns the declared type of a column in a result set or null if no type is declared. /// </summary> /// <seealso href="https://sqlite.org/c3ref/column_decltype.html"/> public string DeclaredType { get; } internal ColumnInfo(string name, string databaseName, string originName, string tableName, string declaredType) { this.Name = name; this.DatabaseName = databaseName; this.OriginName = originName; this.TableName = tableName; this.DeclaredType = declaredType; } /// <inheritdoc/> public bool Equals(ColumnInfo other) { if (Object.ReferenceEquals(other, null)) { return false; } if (Object.ReferenceEquals(this, other)) { return true; } return this.Name == other.Name && this.DatabaseName == other.DatabaseName && this.OriginName == other.OriginName && this.TableName == other.TableName && this.DeclaredType == other.DeclaredType; } /// <inheritdoc/> public override bool Equals(object other) => other is ColumnInfo && this == (ColumnInfo)other; /// <inheritdoc/> public override int GetHashCode() { int hash = 17; hash = hash * 31 + this.Name.GetHashCode(); hash = hash * 31 + this.DatabaseName.GetHashCode(); hash = hash * 31 + this.OriginName.GetHashCode(); hash = hash * 31 + this.TableName.GetHashCode(); hash = hash * 32 + this.DeclaredType.GetHashCode(); return hash; } /// <inheritdoc/> public int CompareTo(ColumnInfo other) { if (!Object.ReferenceEquals(other, null)) { var result = String.CompareOrdinal(this.Name, other.Name); if (result != 0) { return result; } result = String.CompareOrdinal(this.DatabaseName, other.DatabaseName); if (result != 0) { return result; } result = String.CompareOrdinal(this.TableName, other.TableName); if (result != 0) { return result; } result = String.CompareOrdinal(this.OriginName, other.OriginName); if (result != 0) { return result; } return String.CompareOrdinal(this.DeclaredType, other.DeclaredType); } else { return 1; } } /// <inheritdoc/>> int IComparable.CompareTo(object obj) => System.Object.ReferenceEquals(obj, null) ? 1 : this.CompareTo((ColumnInfo)obj); } }
using System; using System.ComponentModel; using System.Windows.Forms; namespace SmartFighter { public partial class App : Form { private GameState gameState; private Connector connector; private BackgroundWorker apiWorker; private BackgroundWorker connectorWorker; private Nfc nfcReader; private BackgroundWorker nfcWorker; private Input inputReader; private BackgroundWorker inputWorker; private Overlay overlay; private Timer overlayTimer; private bool overlayEnabled = true; private int? playerSelection = null; private bool sfvHasFocus = true; private enum WorkerState { Stopped, Running, Stopping, }; public App() { InitializeComponent(); Logger logger = Logger.Instance; logger.LogEvent += appendToLogs; Config.load(); overlay = new Overlay(); overlay.Owner = this; overlayTimer = new Timer(); overlayTimer.Interval = 5000; overlayTimer.Tick += (sender, args) => stopOverlayDisconnect(); apiWorker = new BackgroundWorker(); apiWorker.WorkerSupportsCancellation = true; apiWorker.DoWork += ApiQueue.run; apiWorker.RunWorkerCompleted += (sender, args) => onApiQueueExit(); updateWorkerState(WorkerState.Running, apiButton, apiLabel); apiWorker.RunWorkerAsync(); nfcReader = new Nfc(); nfcReader.NfcCardEvent += onCardRead; nfcWorker = new BackgroundWorker(); nfcWorker.WorkerSupportsCancellation = true; nfcWorker.DoWork += nfcReader.run; nfcWorker.RunWorkerCompleted += (sender, args) => onNfcExit(); updateWorkerState(WorkerState.Running, nfcButton, nfcLabel); nfcWorker.RunWorkerAsync(); inputReader = new Input(); inputReader.Player1ButtonEvent += onPlayer1Button; inputReader.Player2ButtonEvent += onPlayer2Button; inputWorker = new BackgroundWorker(); inputWorker.WorkerSupportsCancellation = true; inputWorker.DoWork += inputReader.run; inputWorker.RunWorkerCompleted += (sender, args) => onInputExit(); updateWorkerState(WorkerState.Running, inputButton, inputLabel); inputWorker.RunWorkerAsync(); gameState = new GameState(); gameState.ScoresUpdatedEvent += updateOverlayScores; connector = new Connector(gameState); connector.server.GameModeChangedEvent += onGameModeChanged; connector.SFVFocusChangedEvent += onFocusChanged; connectorWorker = new BackgroundWorker(); connectorWorker.WorkerSupportsCancellation = true; connectorWorker.DoWork += connector.run; connectorWorker.RunWorkerCompleted += (sender, args) => onConnectorExit((bool)args.Result); updateWorkerState(WorkerState.Running, connectorButton, connectorLabel); connectorWorker.RunWorkerAsync(); } private void onPlayer1Button() { if (InvokeRequired) { Invoke(new Action(onPlayer1Button)); return; } if (!overlayEnabled) { return; } if (playerSelection == 1) { gameState.player1Id = null; overlay.player1Name.Text = ""; overlay.hideScores(); } playerSelection = 1; if (gameState.player1Id != null) { overlay.setDisconnectPlayer1(); overlayTimer.Start(); } else { overlayTimer.Stop(); overlay.setScanPlayer1(); } } private void onPlayer2Button() { if (InvokeRequired) { Invoke(new Action(onPlayer2Button)); return; } if (!overlayEnabled) { return; } if (playerSelection == 2) { gameState.player2Id = null; overlay.player2Name.Text = ""; overlay.hideScores(); } playerSelection = 2; if (gameState.player2Id != null) { overlay.setDisconnectPlayer2(); overlayTimer.Start(); } else { overlayTimer.Stop(); overlay.setScanPlayer2(); } } private void onCardRead(string uid) { if (InvokeRequired) { Invoke(new Action<string>(onCardRead), uid); return; } if (!overlayEnabled) { return; } Api.Player player = Api.getPlayer(uid); if (player == null) { return; } if (playerSelection == 1 && gameState.player2Id != uid) { gameState.player1Id = uid; overlay.player1Name.Text = player.name; if (gameState.player2Id == null) { playerSelection = 2; overlay.setScanPlayer2(); } else { stopOverlayDisconnect(); gameState.resetScores(); updateOverlayScores(); overlay.showScores(); } } else if (playerSelection == 2 && gameState.player1Id != uid) { gameState.player2Id = uid; overlay.player2Name.Text = player.name; if (gameState.player1Id == null) { playerSelection = 1; overlay.setScanPlayer1(); } else { stopOverlayDisconnect(); gameState.resetScores(); updateOverlayScores(); overlay.showScores(); } } } private void onGameModeChanged() { if (InvokeRequired) { Invoke(new Action(onGameModeChanged)); return; } if (!gameState.isInVersus()) { gameState.player1Id = null; gameState.player2Id = null; overlay.player1Name.Text = ""; overlay.player2Name.Text = ""; playerSelection = null; overlay.hideScores(); } updateOverlayVisibility(); } private void onFocusChanged(bool hasFocus) { if (InvokeRequired) { Invoke(new Action<bool>(onFocusChanged), hasFocus); return; } sfvHasFocus = hasFocus; updateOverlayVisibility(); } private void updateOverlayVisibility() { if (sfvHasFocus && gameState.isInVersus()) { overlay.Show(); } else { overlay.Hide(); } } private void stopOverlayDisconnect() { overlayTimer.Stop(); playerSelection = null; overlay.hideInfoLabels(); } private void updateOverlayScores() { if (InvokeRequired) { Invoke(new Action(updateOverlayScores)); return; } overlay.player1Score.Text = gameState.player1Score.ToString(); overlay.player2Score.Text = gameState.player2Score.ToString(); } private void onConnectorExit(bool isSuccess) { updateWorkerState(WorkerState.Stopped, connectorButton, connectorLabel); if (!isSuccess) { appendToLogs("Connector ended with errors."); } } private void onApiQueueExit() { updateWorkerState(WorkerState.Stopped, apiButton, apiLabel); } private void onNfcExit() { updateWorkerState(WorkerState.Stopped, nfcButton, nfcLabel); } private void onInputExit() { updateWorkerState(WorkerState.Stopped, inputButton, inputLabel); } public void appendToLogs(string message) { if (InvokeRequired) { Invoke(new Action<string>(appendToLogs), new object[] { message }); return; } logBox.AppendText(message); } private void connectorButton_Click(object sender, EventArgs e) { toggleWorkerState(connectorWorker, connectorButton, connectorLabel); } private void apiButton_Click(object sender, EventArgs e) { toggleWorkerState(apiWorker, apiButton, apiLabel); } private void nfcButton_Click(object sender, EventArgs e) { toggleWorkerState(nfcWorker, nfcButton, nfcLabel); } private void inputButton_Click(object sender, EventArgs e) { toggleWorkerState(inputWorker, inputButton, inputLabel); } private void toggleWorkerState(BackgroundWorker worker, Button button, Label label) { if (!worker.CancellationPending) { if (worker.IsBusy) { updateWorkerState(WorkerState.Stopping, button, label); worker.CancelAsync(); } else { updateWorkerState(WorkerState.Running, button, label); worker.RunWorkerAsync(); } } } private void updateWorkerState(WorkerState state, Button button, Label label) { switch (state) { case WorkerState.Running: button.Text = "Stop"; button.Enabled = true; label.Text = "Running"; break; case WorkerState.Stopping: button.Text = "Stop"; button.Enabled = false; label.Text = "Stopping..."; break; case WorkerState.Stopped: button.Text = "Start"; button.Enabled = true; label.Text = "Stopped"; break; } } private void configurationMenuItem_Click(object sender, EventArgs e) { ConfigDialog dlg = new ConfigDialog(); dlg.Owner = this; Config.Instance.initDialog(dlg); if (dlg.ShowDialog() == DialogResult.OK) { Config.Instance.updateFromDialog(dlg); } } private void registerAPlayerToolStripMenuItem_Click(object sender, EventArgs e) { RegisterDialog dlg = new RegisterDialog(nfcReader); dlg.Owner = this; overlayEnabled = false; if (dlg.ShowDialog() == DialogResult.OK) { if (Api.createPlayer(dlg.cardId, dlg.nameValue.Text)) { Logger.Instance.log("Player {0} registered.", dlg.nameValue.Text); } } overlayEnabled = true; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ namespace IronPython.Compiler.Ast { /// <summary> /// PythonWalker class - The Python AST Walker (default result is true) /// </summary> public class PythonWalker { // This is generated by the scripts\generate_walker.py script. // That will scan all types that derive from the IronPython AST nodes and inject into here. #region Generated Python AST Walker // *** BEGIN GENERATED CODE *** // generated by function: gen_python_walker from: generate_walker.py // AndExpression public virtual bool Walk(AndExpression node) { return true; } public virtual void PostWalk(AndExpression node) { } // BinaryExpression public virtual bool Walk(BinaryExpression node) { return true; } public virtual void PostWalk(BinaryExpression node) { } // CallExpression public virtual bool Walk(CallExpression node) { return true; } public virtual void PostWalk(CallExpression node) { } // ConditionalExpression public virtual bool Walk(ConditionalExpression node) { return true; } public virtual void PostWalk(ConditionalExpression node) { } // ConstantExpression public virtual bool Walk(ConstantExpression node) { return true; } public virtual void PostWalk(ConstantExpression node) { } // DictionaryComprehension public virtual bool Walk(DictionaryComprehension node) { return true; } public virtual void PostWalk(DictionaryComprehension node) { } // DictionaryExpression public virtual bool Walk(DictionaryExpression node) { return true; } public virtual void PostWalk(DictionaryExpression node) { } // ErrorExpression public virtual bool Walk(ErrorExpression node) { return true; } public virtual void PostWalk(ErrorExpression node) { } // GeneratorExpression public virtual bool Walk(GeneratorExpression node) { return true; } public virtual void PostWalk(GeneratorExpression node) { } // IndexExpression public virtual bool Walk(IndexExpression node) { return true; } public virtual void PostWalk(IndexExpression node) { } // LambdaExpression public virtual bool Walk(LambdaExpression node) { return true; } public virtual void PostWalk(LambdaExpression node) { } // ListComprehension public virtual bool Walk(ListComprehension node) { return true; } public virtual void PostWalk(ListComprehension node) { } // ListExpression public virtual bool Walk(ListExpression node) { return true; } public virtual void PostWalk(ListExpression node) { } // MemberExpression public virtual bool Walk(MemberExpression node) { return true; } public virtual void PostWalk(MemberExpression node) { } // NameExpression public virtual bool Walk(NameExpression node) { return true; } public virtual void PostWalk(NameExpression node) { } // OrExpression public virtual bool Walk(OrExpression node) { return true; } public virtual void PostWalk(OrExpression node) { } // ParenthesisExpression public virtual bool Walk(ParenthesisExpression node) { return true; } public virtual void PostWalk(ParenthesisExpression node) { } // SetComprehension public virtual bool Walk(SetComprehension node) { return true; } public virtual void PostWalk(SetComprehension node) { } // SetExpression public virtual bool Walk(SetExpression node) { return true; } public virtual void PostWalk(SetExpression node) { } // SliceExpression public virtual bool Walk(SliceExpression node) { return true; } public virtual void PostWalk(SliceExpression node) { } // StarredExpression public virtual bool Walk(StarredExpression node) { return true; } public virtual void PostWalk(StarredExpression node) { } // TupleExpression public virtual bool Walk(TupleExpression node) { return true; } public virtual void PostWalk(TupleExpression node) { } // UnaryExpression public virtual bool Walk(UnaryExpression node) { return true; } public virtual void PostWalk(UnaryExpression node) { } // YieldExpression public virtual bool Walk(YieldExpression node) { return true; } public virtual void PostWalk(YieldExpression node) { } // AssertStatement public virtual bool Walk(AssertStatement node) { return true; } public virtual void PostWalk(AssertStatement node) { } // AssignmentStatement public virtual bool Walk(AssignmentStatement node) { return true; } public virtual void PostWalk(AssignmentStatement node) { } // AugmentedAssignStatement public virtual bool Walk(AugmentedAssignStatement node) { return true; } public virtual void PostWalk(AugmentedAssignStatement node) { } // BreakStatement public virtual bool Walk(BreakStatement node) { return true; } public virtual void PostWalk(BreakStatement node) { } // ClassDefinition public virtual bool Walk(ClassDefinition node) { return true; } public virtual void PostWalk(ClassDefinition node) { } // ContinueStatement public virtual bool Walk(ContinueStatement node) { return true; } public virtual void PostWalk(ContinueStatement node) { } // DelStatement public virtual bool Walk(DelStatement node) { return true; } public virtual void PostWalk(DelStatement node) { } // EmptyStatement public virtual bool Walk(EmptyStatement node) { return true; } public virtual void PostWalk(EmptyStatement node) { } // ExpressionStatement public virtual bool Walk(ExpressionStatement node) { return true; } public virtual void PostWalk(ExpressionStatement node) { } // ForStatement public virtual bool Walk(ForStatement node) { return true; } public virtual void PostWalk(ForStatement node) { } // FromImportStatement public virtual bool Walk(FromImportStatement node) { return true; } public virtual void PostWalk(FromImportStatement node) { } // FunctionDefinition public virtual bool Walk(FunctionDefinition node) { return true; } public virtual void PostWalk(FunctionDefinition node) { } // GlobalStatement public virtual bool Walk(GlobalStatement node) { return true; } public virtual void PostWalk(GlobalStatement node) { } // NonlocalStatement public virtual bool Walk(NonlocalStatement node) { return true; } public virtual void PostWalk(NonlocalStatement node) { } // IfStatement public virtual bool Walk(IfStatement node) { return true; } public virtual void PostWalk(IfStatement node) { } // ImportStatement public virtual bool Walk(ImportStatement node) { return true; } public virtual void PostWalk(ImportStatement node) { } // PythonAst public virtual bool Walk(PythonAst node) { return true; } public virtual void PostWalk(PythonAst node) { } // RaiseStatement public virtual bool Walk(RaiseStatement node) { return true; } public virtual void PostWalk(RaiseStatement node) { } // ReturnStatement public virtual bool Walk(ReturnStatement node) { return true; } public virtual void PostWalk(ReturnStatement node) { } // SuiteStatement public virtual bool Walk(SuiteStatement node) { return true; } public virtual void PostWalk(SuiteStatement node) { } // TryStatement public virtual bool Walk(TryStatement node) { return true; } public virtual void PostWalk(TryStatement node) { } // WhileStatement public virtual bool Walk(WhileStatement node) { return true; } public virtual void PostWalk(WhileStatement node) { } // WithStatement public virtual bool Walk(WithStatement node) { return true; } public virtual void PostWalk(WithStatement node) { } // Arg public virtual bool Walk(Arg node) { return true; } public virtual void PostWalk(Arg node) { } // ComprehensionFor public virtual bool Walk(ComprehensionFor node) { return true; } public virtual void PostWalk(ComprehensionFor node) { } // ComprehensionIf public virtual bool Walk(ComprehensionIf node) { return true; } public virtual void PostWalk(ComprehensionIf node) { } // DottedName public virtual bool Walk(DottedName node) { return true; } public virtual void PostWalk(DottedName node) { } // IfStatementTest public virtual bool Walk(IfStatementTest node) { return true; } public virtual void PostWalk(IfStatementTest node) { } // ModuleName public virtual bool Walk(ModuleName node) { return true; } public virtual void PostWalk(ModuleName node) { } // Parameter public virtual bool Walk(Parameter node) { return true; } public virtual void PostWalk(Parameter node) { } // RelativeModuleName public virtual bool Walk(RelativeModuleName node) { return true; } public virtual void PostWalk(RelativeModuleName node) { } // TryStatementHandler public virtual bool Walk(TryStatementHandler node) { return true; } public virtual void PostWalk(TryStatementHandler node) { } // *** END GENERATED CODE *** #endregion } /// <summary> /// PythonWalkerNonRecursive class - The Python AST Walker (default result is false) /// </summary> public class PythonWalkerNonRecursive : PythonWalker { #region Generated Python AST Walker Nonrecursive // *** BEGIN GENERATED CODE *** // generated by function: gen_python_walker_nr from: generate_walker.py // AndExpression public override bool Walk(AndExpression node) { return false; } public override void PostWalk(AndExpression node) { } // BinaryExpression public override bool Walk(BinaryExpression node) { return false; } public override void PostWalk(BinaryExpression node) { } // CallExpression public override bool Walk(CallExpression node) { return false; } public override void PostWalk(CallExpression node) { } // ConditionalExpression public override bool Walk(ConditionalExpression node) { return false; } public override void PostWalk(ConditionalExpression node) { } // ConstantExpression public override bool Walk(ConstantExpression node) { return false; } public override void PostWalk(ConstantExpression node) { } // DictionaryComprehension public override bool Walk(DictionaryComprehension node) { return false; } public override void PostWalk(DictionaryComprehension node) { } // DictionaryExpression public override bool Walk(DictionaryExpression node) { return false; } public override void PostWalk(DictionaryExpression node) { } // ErrorExpression public override bool Walk(ErrorExpression node) { return false; } public override void PostWalk(ErrorExpression node) { } // GeneratorExpression public override bool Walk(GeneratorExpression node) { return false; } public override void PostWalk(GeneratorExpression node) { } // IndexExpression public override bool Walk(IndexExpression node) { return false; } public override void PostWalk(IndexExpression node) { } // LambdaExpression public override bool Walk(LambdaExpression node) { return false; } public override void PostWalk(LambdaExpression node) { } // ListComprehension public override bool Walk(ListComprehension node) { return false; } public override void PostWalk(ListComprehension node) { } // ListExpression public override bool Walk(ListExpression node) { return false; } public override void PostWalk(ListExpression node) { } // MemberExpression public override bool Walk(MemberExpression node) { return false; } public override void PostWalk(MemberExpression node) { } // NameExpression public override bool Walk(NameExpression node) { return false; } public override void PostWalk(NameExpression node) { } // OrExpression public override bool Walk(OrExpression node) { return false; } public override void PostWalk(OrExpression node) { } // ParenthesisExpression public override bool Walk(ParenthesisExpression node) { return false; } public override void PostWalk(ParenthesisExpression node) { } // SetComprehension public override bool Walk(SetComprehension node) { return false; } public override void PostWalk(SetComprehension node) { } // SetExpression public override bool Walk(SetExpression node) { return false; } public override void PostWalk(SetExpression node) { } // SliceExpression public override bool Walk(SliceExpression node) { return false; } public override void PostWalk(SliceExpression node) { } // TupleExpression public override bool Walk(TupleExpression node) { return false; } public override void PostWalk(TupleExpression node) { } // UnaryExpression public override bool Walk(UnaryExpression node) { return false; } public override void PostWalk(UnaryExpression node) { } // YieldExpression public override bool Walk(YieldExpression node) { return false; } public override void PostWalk(YieldExpression node) { } // AssertStatement public override bool Walk(AssertStatement node) { return false; } public override void PostWalk(AssertStatement node) { } // AssignmentStatement public override bool Walk(AssignmentStatement node) { return false; } public override void PostWalk(AssignmentStatement node) { } // AugmentedAssignStatement public override bool Walk(AugmentedAssignStatement node) { return false; } public override void PostWalk(AugmentedAssignStatement node) { } // BreakStatement public override bool Walk(BreakStatement node) { return false; } public override void PostWalk(BreakStatement node) { } // ClassDefinition public override bool Walk(ClassDefinition node) { return false; } public override void PostWalk(ClassDefinition node) { } // ContinueStatement public override bool Walk(ContinueStatement node) { return false; } public override void PostWalk(ContinueStatement node) { } // DelStatement public override bool Walk(DelStatement node) { return false; } public override void PostWalk(DelStatement node) { } // EmptyStatement public override bool Walk(EmptyStatement node) { return false; } public override void PostWalk(EmptyStatement node) { } // ExpressionStatement public override bool Walk(ExpressionStatement node) { return false; } public override void PostWalk(ExpressionStatement node) { } // ForStatement public override bool Walk(ForStatement node) { return false; } public override void PostWalk(ForStatement node) { } // FromImportStatement public override bool Walk(FromImportStatement node) { return false; } public override void PostWalk(FromImportStatement node) { } // FunctionDefinition public override bool Walk(FunctionDefinition node) { return false; } public override void PostWalk(FunctionDefinition node) { } // GlobalStatement public override bool Walk(GlobalStatement node) { return false; } public override void PostWalk(GlobalStatement node) { } // IfStatement public override bool Walk(IfStatement node) { return false; } public override void PostWalk(IfStatement node) { } // ImportStatement public override bool Walk(ImportStatement node) { return false; } public override void PostWalk(ImportStatement node) { } // PythonAst public override bool Walk(PythonAst node) { return false; } public override void PostWalk(PythonAst node) { } // RaiseStatement public override bool Walk(RaiseStatement node) { return false; } public override void PostWalk(RaiseStatement node) { } // ReturnStatement public override bool Walk(ReturnStatement node) { return false; } public override void PostWalk(ReturnStatement node) { } // SuiteStatement public override bool Walk(SuiteStatement node) { return false; } public override void PostWalk(SuiteStatement node) { } // TryStatement public override bool Walk(TryStatement node) { return false; } public override void PostWalk(TryStatement node) { } // WhileStatement public override bool Walk(WhileStatement node) { return false; } public override void PostWalk(WhileStatement node) { } // WithStatement public override bool Walk(WithStatement node) { return false; } public override void PostWalk(WithStatement node) { } // Arg public override bool Walk(Arg node) { return false; } public override void PostWalk(Arg node) { } // ComprehensionFor public override bool Walk(ComprehensionFor node) { return false; } public override void PostWalk(ComprehensionFor node) { } // ComprehensionIf public override bool Walk(ComprehensionIf node) { return false; } public override void PostWalk(ComprehensionIf node) { } // DottedName public override bool Walk(DottedName node) { return false; } public override void PostWalk(DottedName node) { } // IfStatementTest public override bool Walk(IfStatementTest node) { return false; } public override void PostWalk(IfStatementTest node) { } // ModuleName public override bool Walk(ModuleName node) { return false; } public override void PostWalk(ModuleName node) { } // Parameter public override bool Walk(Parameter node) { return false; } public override void PostWalk(Parameter node) { } // RelativeModuleName public override bool Walk(RelativeModuleName node) { return false; } public override void PostWalk(RelativeModuleName node) { } // TryStatementHandler public override bool Walk(TryStatementHandler node) { return false; } public override void PostWalk(TryStatementHandler node) { } // *** END GENERATED CODE *** #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using Cimbalino.Phone.Toolkit.Services; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Messaging; using InTwo.Model; using Microsoft.Phone.Controls; using Newtonsoft.Json; using Nokia.Music.Types; using ScottIsAFool.WindowsPhone.ViewModel; namespace InTwo.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private readonly IExtendedNavigationService _navigationService; private readonly IAsyncStorageService _asyncStorageService; private readonly IApplicationSettingsService _settingsService; private bool _hasCheckedForData; private bool _isFirstRun = true; /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel(IExtendedNavigationService navigationService, IAsyncStorageService asyncStorageService, IApplicationSettingsService settingsService) { _navigationService = navigationService; _asyncStorageService = asyncStorageService; _settingsService = settingsService; if (IsInDesignMode) { DataExists = true; } } public List<Genre> Genres { get; set; } public bool DataExists { get; set; } public override void WireMessages() { Messenger.Default.Register<NotificationMessage>(this, m => { if (m.Notification.Equals(Constants.Messages.UpdatePrimaryTileMsg)) { TileService.Current.UpdatePrimaryTile(); } }); } private async Task<bool> CheckForGameData() { var genres = _settingsService.Get("Genres", default(List<Genre>)); if (genres != default(List<Genre>)) { await _asyncStorageService.WriteAllTextAsync(Constants.GenreDataFile, await JsonConvert.SerializeObjectAsync(genres)); _settingsService.Reset("Genres"); } else { if (!await _asyncStorageService.FileExistsAsync(Constants.GenreDataFile)) { return false; } var genreJson = await _asyncStorageService.ReadAllTextAsync(Constants.GenreDataFile); genres = await JsonConvert.DeserializeObjectAsync<List<Genre>>(genreJson); if (genres == null || !genres.Any()) { return false; } var allGenreCheck = genres.FirstOrDefault(x => x.Name.Equals(GameViewModel.AllGenres)); if (allGenreCheck == default(Genre)) { genres.Insert(0, new Genre {Name = GameViewModel.AllGenres}); } var comedyGenreCheck = genres.FirstOrDefault(x => x.Name.Equals("Comedy")); if (comedyGenreCheck != default(Genre)) { genres.Remove(comedyGenreCheck); } } Genres = genres; App.SettingsWrapper.AppSettings.DefaultGenre = Genres.FirstOrDefault(x => x.Name.Equals(App.SettingsWrapper.AppSettings.DefaultGenre.Name)); if (SimpleIoc.Default.GetInstance<GameViewModel>() == null) return false; Messenger.Default.Send(new NotificationMessage(genres, Constants.Messages.HereAreTheGenresMsg)); if (!await _asyncStorageService.FileExistsAsync(Constants.GameDataFile)) { return false; } var tracksJson = await _asyncStorageService.ReadAllTextAsync(Constants.GameDataFile); try { var tracks = await JsonConvert.DeserializeObjectAsync<List<Product>>(tracksJson); if (tracks.Any()) { Messenger.Default.Send(new NotificationMessage(tracks, Constants.Messages.HereAreTheTracksMsg)); return true; } } catch (Exception ex) { Log.ErrorException("Deserializing tracks", ex); } return false; } private void DisplayGetDataMessage() { Log.Info("Get game data prompt"); var message = new CustomMessageBox { Caption = "No game data present", Message = "We can't find any game data saved to your phone. " + "This data needs to be downloaded in order for you to play, would you like us to download that now? " + "Please note, this doesn't download any music.", LeftButtonContent = "yes", RightButtonContent = "no", IsFullScreen = false }; message.Dismissed += (sender, args) => { if (args.Result == CustomMessageBoxResult.LeftButton) { ((CustomMessageBox)sender).Dismissing += (o, eventArgs) => eventArgs.Cancel = true; NavigateTo(Constants.Pages.DownloadingSongs); } }; message.Show(); } private void NavigateTo(string link) { Log.Info("Navigating to " + link); _navigationService.NavigateTo(link); } #region Commands public RelayCommand MainPageLoaded { get { return new RelayCommand(async () => { Log.Info("MainPage Loaded"); if (!App.SettingsWrapper.AppSettings.DontShowAllowStopMusicMessage) { DisplayStopAudioMessage(); } if (_hasCheckedForData && DataExists) return; Log.Info("Checking for data"); DataExists = await CheckForGameData(); if (!DataExists) { Log.Info("Data not acquired, prompting for download"); DisplayGetDataMessage(); } _hasCheckedForData = true; if (_isFirstRun) { _isFirstRun = false; } else { if (ReviewBugger.IsTimeForReview()) { ReviewBugger.PromptUser(); } } if (App.CurrentPlayer != null) { Log.Info("Player exists, requesting latest data"); Messenger.Default.Send(new NotificationMessage(Constants.Messages.RefreshCurrentPlayerInfoMsg)); } }); } } private void DisplayStopAudioMessage() { var message = new CustomMessageBox { Title = "Stop music", Message = "If you already have music playing, do we have your permission to stop your music in order to play the game?\n\nThis can be changed in the app settings.", LeftButtonContent = "yes", RightButtonContent = "no", Content = Utils.CreateDontShowCheckBox("DontShowAllowStopMusicMessage") }; message.Dismissed += (sender, args) => App.SettingsWrapper.AppSettings.AllowStopMusic = args.Result == CustomMessageBoxResult.LeftButton; message.Show(); } public RelayCommand<string> NavigateToPage { get { return new RelayCommand<string>(NavigateTo); } } public RelayCommand LoginLogoutCommand { get { return new RelayCommand(() => { if (App.CurrentPlayer == null) { NavigateTo(Constants.Pages.Scoreoid.SignIn); } else { App.CurrentPlayer = null; } }); } } public RelayCommand GoToGameCommand { get { return new RelayCommand(async () => { await Task.Run(() => { #if !DEBUG if (!_navigationService.IsNetworkAvailable) return; #endif if (DataExists) { Deployment.Current.Dispatcher.BeginInvoke(() => { if (SimpleIoc.Default.GetInstance<GameViewModel>() == null) return; Messenger.Default.Send(new NotificationMessage(Constants.Messages.NewGameMsg)); NavigateTo(Constants.Pages.Game); }); return; } Deployment.Current.Dispatcher.BeginInvoke(DisplayGetDataMessage); }); }); } } public RelayCommand GoToSettingsCommand { get { return new RelayCommand(() => NavigateTo(Constants.Pages.SettingsView)); } } public RelayCommand GoToRemoveAdsCommand { get { return new RelayCommand(() => NavigateTo(Constants.Pages.Removeads)); } } public RelayCommand RefreshGameDataCommand { get { return new RelayCommand(() => NavigateTo(Constants.Pages.DownloadingSongs)); } } public RelayCommand GoToHowToPlayCommand { get { return new RelayCommand(() => NavigateTo(Constants.Pages.HowToPlay)); } } public RelayCommand GoToScoreboardCommand { get{ return new RelayCommand(() => NavigateTo(Constants.Pages.ScoreBoard));} } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.Net.Tests { public class WebRequestTest : RemoteExecutorTestBase { static WebRequestTest() { // Capture the value of DefaultWebProxy before any tests run. // This lets us test the default value without imposing test // ordering constraints which aren't natively supported by xunit. initialDefaultWebProxy = WebRequest.DefaultWebProxy; initialDefaultWebProxyCredentials = initialDefaultWebProxy.Credentials; } private readonly NetworkCredential _explicitCredentials = new NetworkCredential("user", "password", "domain"); private static IWebProxy initialDefaultWebProxy; private static ICredentials initialDefaultWebProxyCredentials; [Fact] public void DefaultWebProxy_VerifyDefaults_Success() { Assert.NotNull(initialDefaultWebProxy); Assert.Null(initialDefaultWebProxyCredentials); } [Fact] public void DefaultWebProxy_SetThenGet_ValuesMatch() { RemoteInvoke(() => { IWebProxy p = new WebProxy(); WebRequest.DefaultWebProxy = p; Assert.Same(p, WebRequest.DefaultWebProxy); return SuccessExitCode; }).Dispose(); } [Fact] public void DefaultWebProxy_SetCredentialsToNullThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; proxy.Credentials = null; Assert.Equal(null, proxy.Credentials); } [Fact] public void DefaultWebProxy_SetCredentialsToDefaultCredentialsThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; proxy.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, proxy.Credentials); } [Fact] public void DefaultWebProxy_SetCredentialsToExplicitCredentialsThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; ICredentials oldCreds = proxy.Credentials; try { proxy.Credentials = _explicitCredentials; Assert.Equal(_explicitCredentials, proxy.Credentials); } finally { // Reset the credentials so as not to interfere with any subsequent tests, // e.g. DefaultWebProxy_VerifyDefaults_Success proxy.Credentials = oldCreds; } } [Theory] [InlineData("http")] [InlineData("https")] [InlineData("ftp")] public void Create_ValidWebRequestUriScheme_Success(string scheme) { var uri = new Uri($"{scheme}://example.com/folder/resource.txt"); WebRequest request = WebRequest.Create(uri); } [Theory] [InlineData("ws")] [InlineData("wss")] [InlineData("custom")] public void Create_InvalidWebRequestUriScheme_Throws(string scheme) { var uri = new Uri($"{scheme}://example.com/folder/resource.txt"); Assert.Throws<NotSupportedException>(() => WebRequest.Create(uri)); } [Fact] public void Create_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.Create((string)null)); Assert.Throws<ArgumentNullException>(() => WebRequest.Create((Uri)null)); } [Fact] public void CreateDefault_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.CreateDefault(null)); } [Fact] public void CreateHttp_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.CreateHttp((string)null)); Assert.Throws<ArgumentNullException>(() => WebRequest.CreateHttp((Uri)null)); } [Fact] public void CreateHttp_InvalidScheme_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => WebRequest.CreateHttp(new Uri("ftp://microsoft.com"))); } [Fact] public void BaseMembers_NotCall_ThrowsNotImplementedException() { WebRequest request = new FakeRequest(); Assert.Throws<NotImplementedException>(() => request.ConnectionGroupName); Assert.Throws<NotImplementedException>(() => request.ConnectionGroupName = null); Assert.Throws<NotImplementedException>(() => request.Method); Assert.Throws<NotImplementedException>(() => request.Method = null); Assert.Throws<NotImplementedException>(() => request.RequestUri); Assert.Throws<NotImplementedException>(() => request.Headers); Assert.Throws<NotImplementedException>(() => request.Headers = null); Assert.Throws<NotImplementedException>(() => request.ContentLength); Assert.Throws<NotImplementedException>(() => request.ContentLength = 0); Assert.Throws<NotImplementedException>(() => request.ContentType); Assert.Throws<NotImplementedException>(() => request.ContentType = null); Assert.Throws<NotImplementedException>(() => request.Credentials); Assert.Throws<NotImplementedException>(() => request.Credentials = null); Assert.Throws<NotImplementedException>(() => request.Timeout); Assert.Throws<NotImplementedException>(() => request.Timeout = 0); Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials); Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials = true); Assert.Throws<NotImplementedException>(() => request.GetRequestStream()); Assert.Throws<NotImplementedException>(() => request.GetResponse()); Assert.Throws<NotImplementedException>(() => request.BeginGetResponse(null, null)); Assert.Throws<NotImplementedException>(() => request.EndGetResponse(null)); Assert.Throws<NotImplementedException>(() => request.BeginGetRequestStream(null, null)); Assert.Throws<NotImplementedException>(() => request.EndGetRequestStream(null)); Assert.Throws<NotImplementedException>(() => request.Abort()); Assert.Throws<NotImplementedException>(() => request.PreAuthenticate); Assert.Throws<NotImplementedException>(() => request.PreAuthenticate = true); Assert.Throws<NotImplementedException>(() => request.Proxy); Assert.Throws<NotImplementedException>(() => request.Proxy = null); } public void GetSystemWebProxy_NoArguments_ExpectNotNull() { IWebProxy webProxy = WebRequest.GetSystemWebProxy(); Assert.NotNull(webProxy); } [Fact] public void RegisterPrefix_PrefixOrCreatorNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.RegisterPrefix(null, new FakeRequestFactory())); Assert.Throws<ArgumentNullException>(() => WebRequest.RegisterPrefix("http://", null)); } [Fact] public void RegisterPrefix_HttpWithFakeFactory_Success() { bool success = WebRequest.RegisterPrefix("sta:", new FakeRequestFactory()); Assert.True(success); Assert.IsType<FakeRequest>(WebRequest.Create("sta://anything")); } [Fact] public void RegisterPrefix_DuplicateHttpWithFakeFactory_ExpectFalse() { bool success = WebRequest.RegisterPrefix("stb:", new FakeRequestFactory()); Assert.True(success); success = WebRequest.RegisterPrefix("stb:", new FakeRequestFactory()); Assert.False(success); } private class FakeRequest : WebRequest { private readonly Uri _uri; public override Uri RequestUri => _uri ?? base.RequestUri; public FakeRequest(Uri uri = null) { _uri = uri; } } private class FakeRequestFactory : IWebRequestCreate { public WebRequest Create(Uri uri) { return new FakeRequest(uri); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using System.Xml; #pragma warning disable 618 namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using NEWAPI = Apache.Geode.Client.Tests; //using Region = Apache.Geode.Client.IRegion<Object, Object>; /// <summary> /// Exception thrown when 'Call' is invoked on a client thread/process/... /// that has already exited (either due to some error/exception on the /// client side or due to its 'Dispose' function being called). /// </summary> [Serializable] public class FwkException : Exception { /// <summary> /// Constructor to create an exception object with empty message. /// </summary> public FwkException() : base() { } /// <summary> /// Constructor to create an exception object with the given message. /// </summary> /// <param name="message">The exception message.</param> public FwkException(string message) : base(message) { } /// <summary> /// Constructor to create an exception object with the given message /// and with the given inner Exception. /// </summary> /// <param name="message">The exception message.</param> /// <param name="innerException">The inner Exception object.</param> public FwkException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Constructor to allow deserialization of this exception by .Net remoting /// </summary> public FwkException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public struct FwkTaskData { #region Private members private string m_regionTag; private string m_name; private int m_numClients; private int m_numKeys; private int m_valueSize; private int m_numThreads; #endregion #region Constructor public FwkTaskData(string regionTag, string name, int numClients, int numKeys, int valueSize, int numThreads) { m_regionTag = regionTag; m_name = name; m_numClients = numClients; m_numKeys = numKeys; m_valueSize = valueSize; m_numThreads = numThreads; } #endregion #region Public methods and accessors public string RegionTag { get { return m_regionTag; } } public string Name { get { return m_name; } } public int NumClients { get { return m_numClients; } } public int NumKeys { get { return m_numKeys; } } public int ValueSize { get { return m_valueSize; } } public int NumThreads { get { return m_numThreads; } } public string GetLogString() { return string.Format("{0}-{1}-Clients-{2}-Keys-{3}-VSize-{4}-Threads-{5}", m_regionTag, m_name, m_numClients, m_numKeys, m_valueSize, m_numThreads); } public string GetCSVString() { return string.Format("{0},{1},{2},{3},{4},{5}", m_regionTag, m_name, m_numClients, m_numKeys, m_valueSize, m_numThreads); } #endregion } public abstract class FwkTest<TKey, TVal> : FwkReadData { #region Private members private static FwkTest<TKey, TVal> m_currentTest = null; private FwkTaskData m_taskData; private List<string> m_taskRecords; private const NEWAPI.CredentialGenerator.ClassCode DefaultSecurityCode = NEWAPI.CredentialGenerator.ClassCode.LDAP; #endregion #region Public accessors and constants public static FwkTest<TKey, TVal> CurrentTest { get { return m_currentTest; } } public const string JavaServerBB = "Cacheservers"; public const string EndPointTag = "ENDPOINT:"; public const string HeapLruLimitKey = "heapLruLimit"; public const string RedundancyLevelKey = "redundancyLevel"; public const string ConflateEventsKey = "conflateEvents"; public const string SecurityParams = "securityParams"; public const string SecurityScheme = "securityScheme"; public const string JavaServerEPCountKey = "ServerEPCount"; public const string EndPoints = "EndPoints"; public static Properties<string, string> PER_CLIENT_FOR_MULTIUSER = null; #endregion #region Protected members protected FwkTaskData TaskData { get { return m_taskData; } } #endregion #region Public methods public FwkTest() : base() { m_currentTest = this; m_taskData = new FwkTaskData(); m_taskRecords = new List<string>(); } public virtual void FwkException(string message) { FwkSevere(message); throw new FwkException(message); } public virtual void FwkException(string fmt, params object[] paramList) { FwkException(string.Format(fmt, paramList)); } public virtual void FwkSevere(string message) { Util.Log(Util.LogLevel.Error, "FWKLIB:: Task[{0}] Severe: {1}", TaskName, message); } public virtual void FwkSevere(string fmt, params object[] paramList) { FwkSevere(string.Format(fmt, paramList)); } public virtual void FwkWarn(string message) { Util.Log(Util.LogLevel.Warning, "FWKLIB:: Task[{0}]: {1}", TaskName, message); } public virtual void FwkWarn(string fmt, params object[] paramList) { FwkWarn(string.Format(fmt, paramList)); } public virtual void FwkInfo(string message) { Util.Log(Util.LogLevel.Info, "FWKLIB:: Task[{0}]: {1}", TaskName, message); } public virtual void FwkInfo(string fmt, params object[] paramList) { FwkInfo(string.Format(fmt, paramList)); } public virtual void FwkAssert(bool condition, string message) { if (!condition) { FwkException(message); } } public virtual void FwkAssert(bool condition, string fmt, params object[] paramList) { if (!condition) { FwkException(fmt, paramList); } } public static void LogException(string message) { throw new FwkException(message); } public static void LogException(string fmt, params object[] paramList) { LogException(string.Format(fmt, paramList)); } public static void LogSevere(string message) { Util.Log(Util.LogLevel.Error, "FWKLIB:: Severe: {0}", message); } public static void LogSevere(string fmt, params object[] paramList) { LogSevere(string.Format(fmt, paramList)); } public static void LogWarn(string message) { Util.Log(Util.LogLevel.Warning, "FWKLIB:: {0}", message); } public static void LogWarn(string fmt, params object[] paramList) { LogWarn(string.Format(fmt, paramList)); } public static void LogInfo(string message) { Util.Log(Util.LogLevel.Info, "FWKLIB:: {0}", message); } public static void LogInfo(string fmt, params object[] paramList) { LogInfo(string.Format(fmt, paramList)); } public static void LogAssert(bool condition, string message) { if (!condition) { LogException(message); } } public static void LogAssert(bool condition, string fmt, params object[] paramList) { if (!condition) { LogException(fmt, paramList); } } public virtual IRegion<TKey, TVal> GetRootRegion() { string rootRegionData = GetStringValue("regionSpec"); //rootRegionData = rootRegionData + "New"; if (rootRegionData == null) { return null; } string rootRegionName = GetRegionName(rootRegionData); try { return CacheHelper<TKey, TVal>.GetVerifyRegion(rootRegionName); } catch { return null; } } public CredentialGenerator GetCredentialGenerator() { int schemeNumber; try { schemeNumber = (int)Util.BBGet(string.Empty, FwkReadData.TestRunNumKey); } catch (Exception) { schemeNumber = 1; } int schemeSkip = 1; string securityScheme; string bb = "GFE_BB"; string key = "scheme"; do { securityScheme = GetStringValue(SecurityScheme); Util.BBSet(bb, key, securityScheme); } while (++schemeSkip <= schemeNumber); NEWAPI.CredentialGenerator.ClassCode secCode; try { secCode = (NEWAPI.CredentialGenerator.ClassCode)Enum.Parse(typeof( NEWAPI.CredentialGenerator.ClassCode), securityScheme, true); } catch (Exception) { FwkWarn("Skipping unknown security scheme {0}. Using default " + "security scheme {1}.", securityScheme, DefaultSecurityCode); secCode = DefaultSecurityCode; } if (secCode == NEWAPI.CredentialGenerator.ClassCode.None) { return null; } NEWAPI.CredentialGenerator gen = NEWAPI.CredentialGenerator.Create(secCode, false); if (gen == null) { FwkWarn("Skipping security scheme {0} with no generator. Using " + "default security scheme.", secCode, DefaultSecurityCode); secCode = DefaultSecurityCode; gen = NEWAPI.CredentialGenerator.Create(secCode, false); } return gen; } public void GetClientSecurityProperties(ref Properties<string, string> props, string regionName) { string securityParams = GetStringValue(SecurityParams); NEWAPI.CredentialGenerator gen;//= GetCredentialGenerator(); if (securityParams == null || securityParams.Length == 0 || (gen = GetCredentialGenerator()) == null) { FwkInfo("Security is DISABLED."); return; } FwkInfo("Security params is: " + securityParams); FwkInfo("Security scheme: " + gen.GetClassCode()); string dataDir = Util.GetFwkLogDir(Util.SystemType) + "/data"; gen.Init(dataDir, dataDir); if (props == null) { props = new Properties<string, string>(); } Properties<string, string> credentials; Random rnd = new Random(); if (securityParams.Equals("valid")) { FwkInfo("Getting valid credentials"); credentials = gen.GetValidCredentials(rnd.Next()); } else if (securityParams.Equals("invalid")) { FwkInfo("Getting invalid credentials"); credentials = gen.GetInvalidCredentials(rnd.Next()); } else { FwkInfo("Getting credentials for a list of operations"); List<OperationCode> opCodes = new List<OperationCode>(); while (securityParams != null && securityParams.Length > 0) { securityParams = securityParams.ToLower().Replace("_", ""); OperationCode opCode; if (securityParams == "create" || securityParams == "update") { opCode = OperationCode.Put; } else { opCode = (OperationCode)Enum.Parse(typeof( OperationCode), securityParams, true); } opCodes.Add(opCode); securityParams = GetStringValue(SecurityParams); FwkInfo("Next security params: {0}", securityParams); } // For now only XML based authorization is supported NEWAPI.AuthzCredentialGenerator authzGen = new NEWAPI.XmlAuthzCredentialGenerator(); authzGen.Init(gen); List<string> regionNameList = new List<string>(); if (regionName == null || regionName.Length == 0) { regionName = GetStringValue("regionPaths"); } while (regionName != null && regionName.Length > 0) { regionNameList.Add(regionName); regionName = GetStringValue("regionPaths"); } string[] regionNames = null; if (regionNameList.Count > 0) { regionNames = regionNameList.ToArray(); } credentials = authzGen.GetAllowedCredentials(opCodes.ToArray(), regionNames, rnd.Next()); } PER_CLIENT_FOR_MULTIUSER = credentials; NEWAPI.Utility.GetClientProperties(gen.AuthInit, credentials, ref props); FwkInfo("Security properties entries: {0}", props); } private string[] GetRoundRobinEP() { int contactnum = GetUIntValue("contactNum"); string label = "EndPoints"; int epCount = (int)Util.BBGet(JavaServerBB, JavaServerEPCountKey); //int epCount = (int)Util.BBGet("GFE_BB", "EP_COUNT"); if (contactnum < 0) contactnum = epCount; string[] rbEP = new string[contactnum]; string currEPKey = "CURRENTEP_COUNT"; int currentEP = (int)Util.BBIncrement("GFERR_BB", currEPKey); for (int i = 0; i < contactnum; i++) { if (currentEP > epCount) { Util.BBSet("GFERR_BB", currEPKey, 0); currentEP = (int)Util.BBIncrement("GFERR_BB", currEPKey); } string key = label + "_" + currentEP.ToString(); string ep = (string)Util.BBGet(JavaServerBB, key); rbEP[i] = ep; FwkInfo("GetRoundRobinEP = {0} key = {1} currentEP = {2}", ep, key, currentEP); // rbEP[i] = ep; } return rbEP; } private void XMLParseEndPoints(string ep, bool isServer, PoolFactory pf) { string[] eps = ep.Split(','); if (isServer) { bool disableShufflingEP = GetBoolValue("disableShufflingEP"); // smoke perf test if (disableShufflingEP) { string[] rbep = GetRoundRobinEP(); for (int cnt = 0; cnt < rbep.Length; cnt++) { FwkInfo("round robin endpoint = {0}", rbep[cnt]); //string[] rep = rbep[cnt].Split(','); //foreach (string endpoint in eps) //{ string hostName = rbep[cnt].Split(':')[0]; int portNum = int.Parse(rbep[cnt].Split(':')[1]); pf.AddServer(hostName, portNum); //} } } else { foreach (string endpoint in eps) { string hostName = endpoint.Split(':')[0]; int portNum = int.Parse(endpoint.Split(':')[1]); pf.AddServer(hostName, portNum); } } } else { foreach (string endpoint in eps) { string hostName = endpoint.Split(':')[0]; int portNum = int.Parse(endpoint.Split(':')[1]); pf.AddLocator(hostName, portNum); } } } private void CreateCache() { Properties<string,string> dsProps = new Properties<string,string>(); ResetKey("PdxReadSerialized"); bool pdxReadSerialized = GetBoolValue("PdxReadSerialized"); ResetKey("isDurable"); bool isDC = GetBoolValue("isDurable"); ResetKey("durableTimeout"); int durableTimeout = 300; string durableClientId = ""; string conflateEvents = GetStringValue(ConflateEventsKey); if (isDC) { durableTimeout = GetUIntValue("durableTimeout"); bool isFeeder = GetBoolValue("isFeeder"); if (isFeeder) { durableClientId = "Feeder"; // VJR: Setting FeederKey because listener cannot read boolean isFeeder // FeederKey is used later on by Verify task to identify feeder's key in BB durableClientId = String.Format("ClientName_{0}_Count", Util.ClientNum); } else { durableClientId = String.Format("ClientName_{0}", Util.ClientNum); } //Util.BBSet("DURABLEBB", durableClientId,0); CacheHelper<TKey, TVal>.InitConfigForPoolDurable(durableClientId, durableTimeout, conflateEvents, false); } else if (pdxReadSerialized) { CacheHelper<TKey, TVal>.InitConfigPdxReadSerialized(dsProps, pdxReadSerialized); } else CacheHelper<TKey, TVal>.InitConfigPool(dsProps); } public void CreateCacheConnect() { CreateCache(); } public virtual void CreatePool() { CreateCache(); PoolFactory pf = PoolManager.CreateFactory(); ResetKey("poolSpec"); string poolRegionData = GetStringValue("poolSpec"); FwkInfo("PoolSpec is :{0}", poolRegionData); string poolName = null; SetPoolAttributes(pf, poolRegionData, ref poolName); if (PoolManager.Find(poolName) == null) { Pool pool = pf.Create(poolName); FwkInfo("Pool attributes are {0}:", PoolAttributesToString(pool)); } } public void SetPoolAttributes(PoolFactory pf, string spec, ref string poolName) { ReadXmlData(null, pf, spec, ref poolName); } private void SetThisPoolAttributes(PoolFactory pf,string key, string value) { switch (key) { case "free-connection-timeout": int fct = int.Parse(value); pf.SetFreeConnectionTimeout(fct); break; case "idle-timeout": int it = int.Parse(value); pf.SetIdleTimeout(it); break; case "load-conditioning-interval": int lci = int.Parse(value); pf.SetLoadConditioningInterval(lci); break; case "max-connections": int mxc = int.Parse(value); pf.SetMaxConnections(mxc); break; case "min-connections": int minc = int.Parse(value); pf.SetMinConnections(minc); break; case "ping-interval": int pi = int.Parse(value); pf.SetPingInterval(pi); break; case "read-timeout": int rt = int.Parse(value); pf.SetReadTimeout(rt); break; case "retry-attempts": int ra = int.Parse(value); pf.SetRetryAttempts(ra); break; case "server-group": pf.SetServerGroup(value); break; case "socket-buffer-size": int bs = int.Parse(value); pf.SetSocketBufferSize(bs); break; case "subscription-ack-interval": int acki = int.Parse(value); pf.SetSubscriptionAckInterval(acki); break; case "subscription-enabled": if (value == "true") { pf.SetSubscriptionEnabled(true); } else { pf.SetSubscriptionEnabled(false); } break; case "thread-local-connections": if (value == "true") { pf.SetThreadLocalConnections(true); } else { pf.SetThreadLocalConnections(false); } break; case "subscription-message-tracking-timeout": int smtt = int.Parse(value); pf.SetSubscriptionMessageTrackingTimeout(smtt); break; case "subscription-redundancy": int sr = int.Parse(value); pf.SetSubscriptionRedundancy(sr); break; case "locators": string locatorAddress = (string)Util.BBGet(string.Empty, "LOCATOR_ADDRESS_POOL"); XMLParseEndPoints(locatorAddress, false, pf); break; case "servers": string ServerEndPoints = (string)Util.BBGet("Cacheservers", "ENDPOINT:"); XMLParseEndPoints(ServerEndPoints, true, pf); break; } } /* public PoolFactory CreatePoolFactoryAndSetAttribute() { PoolFactory pf = PoolManager.CreateFactory(); ResetKey("poolSpec"); string poolRegionData = GetStringValue("poolSpec"); //FwkInfo("PoolSpec is :{0}", poolRegionData); //Properties prop = GetNewPoolAttributes(poolRegionData); staing poolName = null; SetPoolAttributes(pf, poolRegionData,poolName); return pf; }*/ private void ReadXmlData(RegionFactory af, PoolFactory pf,string spec, ref string poolname) { const string DriverNodeName = "test-driver"; string xmlFile = Util.BBGet(string.Empty, "XMLFILE") as string; XmlNode node = XmlNodeReaderWriter.GetInstance(xmlFile).GetNode( '/' + DriverNodeName); XmlNodeList xmlNodes = node.SelectNodes("data"); if (xmlNodes != null) { foreach (XmlNode xmlNode in xmlNodes) { XmlAttribute tmpattr = xmlNode.Attributes["name"]; if(tmpattr.Value == spec) { if (xmlNode.FirstChild.Name == "snippet") { string regionName; if (xmlNode.FirstChild.FirstChild.Name == "region") { //Util.Log("rjk reading region xml data attri name in fwktest"); XmlAttribute nameattr = xmlNode.FirstChild.FirstChild.Attributes["name"]; regionName = nameattr.Value; XmlNode attrnode = xmlNode.FirstChild.FirstChild.FirstChild; //AttributesFactory af = new AttributesFactory(); if (attrnode.Name == "region-attributes") { XmlAttributeCollection attrcoll = attrnode.Attributes; if (attrcoll != null) { foreach (XmlAttribute eachattr in attrcoll) { //Util.Log("rjk fwktest region attri xml data attri name = {0} , attri value = {1}", eachattr.Name, eachattr.Value); SetThisAttribute(eachattr.Name, eachattr, af, ref poolname); } } if (attrnode.ChildNodes != null) { foreach (XmlNode tmpnode in attrnode.ChildNodes) { //Util.Log("rjk fwktest region attri tmpnode xml data attri name = {0} , attri value = {1}", tmpnode.Name, tmpnode.Value); SetThisAttribute(tmpnode.Name, tmpnode, af, ref poolname); } } else { throw new IllegalArgException("The xml file passed has an unknown format"); } } } else if (xmlNode.FirstChild.FirstChild.Name == "pool") { XmlAttribute nameattr = xmlNode.FirstChild.FirstChild.Attributes["name"]; poolname = nameattr.Value; // Now collect the pool atributes Properties<string,string> prop = new Properties<string,string>(); XmlAttributeCollection attrcoll = xmlNode.FirstChild.FirstChild.Attributes; if (attrcoll != null) { foreach (XmlAttribute eachattr in attrcoll) { //Util.Log("rjk fwktest xml data attri name = {0} , attri value = {1}", eachattr.Name, eachattr.Value); SetThisPoolAttributes(pf, eachattr.Name, eachattr.Value); } } else { throw new IllegalArgException("The xml file passed has an unknown format"); } } } } } } } private static ExpirationAction StrToExpirationAction(string str) { return (ExpirationAction)Enum.Parse(typeof(ExpirationAction), str.Replace("-", string.Empty), true); } public void SetRegionAttributes(RegionFactory af, string spec, ref string poolname) { ReadXmlData(af, null,spec, ref poolname); } public static void SetThisAttribute(string name, XmlNode node, RegionFactory af, ref string poolname) { string value = node.Value; switch (name) { case "caching-enabled": if (value == "true") { af.SetCachingEnabled(true); } else { af.SetCachingEnabled(false); } break; case "load-factor": float lf = float.Parse(value); af.SetLoadFactor(lf); break; case "concurrency-level": int cl = int.Parse(value); af.SetConcurrencyLevel(cl); break; case "lru-entries-limit": uint lel = uint.Parse(value); af.SetLruEntriesLimit(lel); break; case "initial-capacity": int ic = int.Parse(value); af.SetInitialCapacity(ic); break; case "disk-policy": if (value == "none") { af.SetDiskPolicy(DiskPolicyType.None); } else if (value == "overflows") { af.SetDiskPolicy(DiskPolicyType.Overflows); } else { throw new IllegalArgException("Unknown disk policy"); } break; case "concurrency-checks-enabled": bool cce = bool.Parse(value); af.SetConcurrencyChecksEnabled(cce); break; case "pool-name": if (value.Length != 0) { af.SetPoolName(value); } else { af.SetPoolName(value); } poolname = value; break; case "region-time-to-live": XmlNode nlrttl = node.FirstChild; if (nlrttl.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlrttl.Attributes; ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string rttl = exAttrColl["timeout"].Value; af.SetRegionTimeToLive(action, uint.Parse(rttl)); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "region-idle-time": XmlNode nlrit = node.FirstChild; if (nlrit.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlrit.Attributes; ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string rit = exAttrColl["timeout"].Value; af.SetRegionIdleTimeout(action, uint.Parse(rit)); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "entry-time-to-live": XmlNode nlettl = node.FirstChild; if (nlettl.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nlettl.Attributes; ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string ettl = exAttrColl["timeout"].Value; af.SetEntryTimeToLive(action, uint.Parse(ettl)); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "entry-idle-time": XmlNode nleit = node.FirstChild; if (nleit.Name == "expiration-attributes") { XmlAttributeCollection exAttrColl = nleit.Attributes; ExpirationAction action = StrToExpirationAction(exAttrColl["action"].Value); string eit = exAttrColl["timeout"].Value; af.SetEntryIdleTimeout(action, uint.Parse(eit)); } else { throw new IllegalArgException("The xml file passed has an unknowk format"); } break; case "cache-loader": XmlAttributeCollection loaderattrs = node.Attributes; string loaderlibrary = null; string loaderfunction = null; foreach (XmlAttribute tmpattr in loaderattrs) { if (tmpattr.Name == "library") { loaderlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { loaderfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-loader attributes in improper format"); } } if (loaderlibrary != null && loaderfunction != null) { if (loaderfunction.IndexOf('.') < 0) { Type myType = typeof(FwkTest<TKey, TVal>); loaderfunction = myType.Namespace + '.' + loaderlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + loaderfunction; loaderlibrary = myType.Assembly.FullName; ICacheLoader<TKey, TVal> loader = null; String createCacheLoader = myType.Namespace + '.' + loaderlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createCacheLoader"; if (String.Compare(loaderfunction, createCacheLoader, true) == 0) { loader = new PerfCacheLoader<TKey, TVal>(); } Util.Log(Util.LogLevel.Info, "Instantiated Loader = {0} ", loaderfunction); af.SetCacheLoader(loader); } //af.SetCacheLoader(loaderlibrary, loaderfunction); } break; case "cache-listener": XmlAttributeCollection listenerattrs = node.Attributes; string listenerlibrary = null; string listenerfunction = null; foreach (XmlAttribute tmpattr in listenerattrs) { if (tmpattr.Name == "library") { listenerlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { listenerfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-listener attributes in improper format"); } } if (listenerlibrary != null && listenerfunction != null) { if (listenerfunction.IndexOf('.') < 0) { Type myType = typeof(FwkTest<TKey, TVal>); listenerfunction = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + listenerfunction; //Util.Log(Util.LogLevel.Info, "rjk1 cache listener in fwktest: myType.Namespace {0} " + // " listenerlibrary {1} listenerfunction {2}", myType.Namespace, listenerlibrary, listenerfunction); //listenerlibrary = myType.Assembly.FullName; //Util.Log(Util.LogLevel.Info, "rjk cache listener in fwktest inside if condition: listenerlibrary {0} listenerfunction {1}", listenerlibrary, listenerfunction); Util.Log(Util.LogLevel.Info, "listenerlibrary is {0} and listenerfunction is {1}", listenerlibrary, listenerfunction); ICacheListener<TKey, TVal> listener = null; String perfTestCacheListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createPerfTestCacheListener"; String conflationTestCacheListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createConflationTestCacheListener"; String latencyListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createLatencyListenerP"; String dupChecker = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createDupChecker"; String createDurableCacheListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createDurableCacheListener"; String createConflationTestCacheListenerDC = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createConflationTestCacheListenerDC"; String createDurablePerfListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createDurablePerfListener"; String CreateDurableCacheListenerSP = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createDurableCacheListenerSP"; String createLatencyListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createLatencyListener"; String createSilenceListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createSilenceListener"; String createDeltaValidationCacheListener = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createDeltaValidationCacheListener"; String createSilenceListenerPdx = myType.Namespace + '.' + listenerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + "createSilenceListenerPdx"; if (String.Compare(listenerfunction, perfTestCacheListener, true) == 0) { listener = new PerfTestCacheListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, conflationTestCacheListener, true) == 0) { listener = new ConflationTestCacheListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, latencyListener, true) == 0) { listener = new LatencyListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, dupChecker, true) == 0) { listener = new DupChecker<TKey, TVal>(); } else if (String.Compare(listenerfunction, createDurableCacheListener, true) == 0) { listener = new DurableListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, createConflationTestCacheListenerDC, true) == 0) { listener = new ConflationTestCacheListenerDC<TKey, TVal>(); } else if (String.Compare(listenerfunction, createDurablePerfListener, true) == 0) { listener = new DurablePerfListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, CreateDurableCacheListenerSP, true) == 0) { listener = new DurableCacheListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, createLatencyListener, true) == 0) { listener = new LatencyListeners<TKey, TVal>(InitPerfStat.perfstat[0]); } else if (String.Compare(listenerfunction, createSilenceListener, true) == 0) { listener = new SilenceListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, createSilenceListenerPdx, true) == 0) { listener = new PDXSilenceListener<TKey, TVal>(); } else if (String.Compare(listenerfunction, createDeltaValidationCacheListener, true) == 0) { listener = new DeltaClientValidationListener<TKey, TVal>(); } Util.Log(Util.LogLevel.Info, "Instantiated Listener = {0} ", listenerfunction); af.SetCacheListener(listener); } //af.SetCacheListener(listenerlibrary, listenerfunction); } break; case "cache-writer": XmlAttributeCollection writerattrs = node.Attributes; string writerlibrary = null; string writerfunction = null; foreach (XmlAttribute tmpattr in writerattrs) { if (tmpattr.Name == "library") { writerlibrary = tmpattr.Value; } else if (tmpattr.Name == "function") { writerfunction = tmpattr.Value; } else { throw new IllegalArgException("cahe-loader attributes in improper format"); } } if (writerlibrary != null && writerfunction != null) { if (writerfunction.IndexOf('.') < 0) { Type myType = typeof(FwkTest<TKey, TVal>); writerfunction = myType.Namespace + '.' + writerlibrary + "<" + typeof(TKey) + "," + typeof(TVal) + ">." + writerfunction; writerlibrary = myType.Assembly.FullName; } af.SetCacheWriter(writerlibrary, writerfunction); } break; case "persistence-manager": string pmlibrary = null; string pmfunction = null; Properties<string, string> prop = new Properties<string, string>(); XmlAttributeCollection pmattrs = node.Attributes; foreach (XmlAttribute attr in pmattrs) { if (attr.Name == "library") { pmlibrary = attr.Value; } else if (attr.Name == "function") { pmfunction = attr.Value; } else { throw new IllegalArgException("Persistence Manager attributes in wrong format: " + attr.Name); } } if (node.FirstChild.Name == "properties") { XmlNodeList pmpropnodes = node.FirstChild.ChildNodes; foreach (XmlNode propnode in pmpropnodes) { if (propnode.Name == "property") { XmlAttributeCollection keyval = propnode.Attributes; XmlAttribute keynode = keyval["name"]; XmlAttribute valnode = keyval["value"]; if (keynode.Value == "PersistenceDirectory" || keynode.Value == "EnvironmentDirectory") { prop.Insert(keynode.Value, valnode.Value); } else if (keynode.Value == "CacheSizeGb" || keynode.Value == "CacheSizeMb" || keynode.Value == "PageSize" || keynode.Value == "MaxFileSize") { prop.Insert(keynode.Value, valnode.Value); } } } } af.SetPersistenceManager(pmlibrary, pmfunction, prop); break; } } private static string ConvertStringArrayToString(string[] array) { // // Concatenate all the elements into a StringBuilder. // StringBuilder builder = new StringBuilder(); foreach (string value in array) { builder.Append(value); builder.Append('.'); } return builder.ToString(); } private string PoolAttributesToString(Pool attrs) { StringBuilder attrsSB = new StringBuilder(); attrsSB.Append(Environment.NewLine + "poolName: " + attrs.Name); attrsSB.Append(Environment.NewLine + "FreeConnectionTimeout: " + attrs.FreeConnectionTimeout); attrsSB.Append(Environment.NewLine + "LoadConditioningInterval: " + attrs.LoadConditioningInterval); attrsSB.Append(Environment.NewLine + "SocketBufferSize: " + attrs.SocketBufferSize); attrsSB.Append(Environment.NewLine + "ReadTimeout: " + attrs.ReadTimeout); attrsSB.Append(Environment.NewLine + "MinConnections: " + attrs.MinConnections); attrsSB.Append(Environment.NewLine + "MaxConnections: " + attrs.MaxConnections); attrsSB.Append(Environment.NewLine + "StatisticInterval: " + attrs.StatisticInterval); attrsSB.Append(Environment.NewLine + "RetryAttempts: " + attrs.RetryAttempts); attrsSB.Append(Environment.NewLine + "SubscriptionEnabled: " + attrs.SubscriptionEnabled); attrsSB.Append(Environment.NewLine + "SubscriptionRedundancy: " + attrs.SubscriptionRedundancy); attrsSB.Append(Environment.NewLine + "SubscriptionAckInterval: " + attrs.SubscriptionAckInterval); attrsSB.Append(Environment.NewLine + "SubscriptionMessageTrackingTimeout: " + attrs.SubscriptionMessageTrackingTimeout); attrsSB.Append(Environment.NewLine + "ServerGroup: " + attrs.ServerGroup); attrsSB.Append(Environment.NewLine + "IdleTimeout: " + attrs.IdleTimeout); attrsSB.Append(Environment.NewLine + "PingInterval: " + attrs.PingInterval); attrsSB.Append(Environment.NewLine + "ThreadLocalConnections: " + attrs.ThreadLocalConnections); attrsSB.Append(Environment.NewLine + "MultiuserAuthentication: " + attrs.MultiuserAuthentication); attrsSB.Append(Environment.NewLine + "PRSingleHopEnabled: " + attrs.PRSingleHopEnabled); attrsSB.Append(Environment.NewLine + "Locators: " ); if (attrs.Locators != null && attrs.Locators.Length > 0) { foreach (string value in attrs.Locators) { attrsSB.Append(value); attrsSB.Append(','); } } attrsSB.Append(Environment.NewLine + "Servers: " ); if (attrs.Servers != null && attrs.Servers.Length > 0) { foreach (string value in attrs.Servers) { attrsSB.Append(value); attrsSB.Append(','); } } attrsSB.Append(Environment.NewLine); return attrsSB.ToString(); } public virtual IRegion<TKey,TVal> CreateRootRegion() { return CreateRootRegion(null); } public virtual IRegion<TKey, TVal> CreateRootRegion(string regionName) { string rootRegionData = GetStringValue("regionSpec"); return CreateRootRegion(regionName, rootRegionData); } public virtual IRegion<TKey, TVal> CreateRootRegion(string regionName, string rootRegionData) { string tagName = GetStringValue("TAG"); string endpoints = Util.BBGet(JavaServerBB, EndPointTag + tagName) as string; return CreateRootRegion(regionName, rootRegionData, endpoints); } public virtual IRegion<TKey, TVal> CreateRootRegion(string regionName, string rootRegionData, string endpoints) { if (rootRegionData != null && rootRegionData.Length > 0) { string rootRegionName; if (regionName == null || regionName.Length == 0) { rootRegionName = GetRegionName(rootRegionData); } else { rootRegionName = regionName; } if (rootRegionName != null && rootRegionName.Length > 0) { IRegion<TKey, TVal> region; if ((region = CacheHelper<TKey, TVal>.GetRegion(rootRegionName)) == null) { Properties<string,string> dsProps = new Properties<string,string>(); GetClientSecurityProperties(ref dsProps, rootRegionName); // Check for any setting of heap LRU limit int heapLruLimit = GetUIntValue(HeapLruLimitKey); if (heapLruLimit > 0) { dsProps.Insert("heap-lru-limit", heapLruLimit.ToString()); } string conflateEvents = GetStringValue(ConflateEventsKey); if (conflateEvents != null && conflateEvents.Length > 0) { dsProps.Insert("conflate-events", conflateEvents); } ResetKey("sslEnable"); bool isSslEnable = GetBoolValue("sslEnable"); if (isSslEnable) { dsProps.Insert("ssl-enabled", "true"); string keyStorePath = Util.GetFwkLogDir(Util.SystemType) + "/data/keystore"; string pubkey = keyStorePath + "/client_truststore.pem"; string privkey = keyStorePath + "/client_keystore.pem"; dsProps.Insert("ssl-keystore", privkey); dsProps.Insert("ssl-truststore", pubkey); } //Properties rootAttrs = GetNewRegionAttributes(rootRegionData); // Check if this is a thin-client region; if so set the endpoints RegionFactory rootAttrs = null; //RegionFactory rootAttrs = CacheHelper.DCache.CreateRegionFactory(RegionShortcut.PROXY); string m_isPool = null; //SetRegionAttributes(rootAttrs, rootRegionData, ref m_isPool); int redundancyLevel = 0; redundancyLevel = GetUIntValue(RedundancyLevelKey); //string m_isPool = rootAttrs.Find("pool-name"); string mode = Util.GetEnvironmentVariable("POOLOPT"); if (endpoints != null && endpoints.Length > 0) { //redundancyLevel = GetUIntValue(RedundancyLevelKey); //if (redundancyLevel > 0) //{ if (mode == "poolwithendpoints" || mode == "poolwithlocator" )//|| m_isPool != null) { FwkInfo("Setting the pool-level configurations"); CacheHelper<TKey, TVal>.InitConfigPool(dsProps); } try { rootAttrs = CacheHelper<TKey, TVal>.DCache.CreateRegionFactory(RegionShortcut.PROXY); } catch (Exception e) { FwkException("GOT this {0}",e.Message); } FwkInfo("Creating region factory"); SetRegionAttributes(rootAttrs, rootRegionData, ref m_isPool); } rootAttrs = CreatePool(rootAttrs, redundancyLevel); ResetKey("NumberOfRegion"); int numRegions = GetUIntValue("NumberOfRegion"); if (numRegions < 1) numRegions = 1; for (int i = 0; i < numRegions; i++) { if(i>0) region = CacheHelper<TKey, TVal>.CreateRegion(rootRegionName+"_"+i, rootAttrs); else region = CacheHelper<TKey, TVal>.CreateRegion(rootRegionName, rootAttrs); } Apache.Geode.Client.RegionAttributes<TKey, TVal> regAttr = region.Attributes; FwkInfo("Region attributes for {0}: {1}", rootRegionName, CacheHelper<TKey, TVal>.RegionAttributesToString(regAttr)); } Log.Info("<ExpectedException action=add>NotAuthorizedException" + "</ExpectedException>"); return region; } } return null; } private void ParseEndPoints(string ep, bool isServer, int redundancyLevel) { string poolName = "_Test_Pool"; PoolFactory pf = PoolManager.CreateFactory(); string[] eps = ep.Split(','); foreach (string endpoint in eps) { string hostName = endpoint.Split(':')[0]; int portNum = int.Parse(endpoint.Split(':')[1]); if (isServer) { FwkInfo("adding pool host port for server"); pf.AddServer(hostName, portNum); } else { FwkInfo("adding pool host port for server"); pf.AddLocator(hostName, portNum); } } pf.SetSubscriptionEnabled(true); ResetKey("multiUserMode"); bool multiUserMode = GetBoolValue("multiUserMode"); if (multiUserMode) { pf.SetMultiuserAuthentication(true); FwkInfo("MultiUser Mode is set to true"); } else { pf.SetMultiuserAuthentication(false); FwkInfo("MultiUser Mode is set to false"); } pf.SetFreeConnectionTimeout(180000); pf.SetReadTimeout(180000); pf.SetMinConnections(20); pf.SetMaxConnections(30); if (redundancyLevel > 0) pf.SetSubscriptionRedundancy(redundancyLevel); if (PoolManager.Find(poolName) == null) { Pool pool = pf.Create(poolName); FwkInfo("Pool attributes are {0}:", PoolAttributesToString(pool)); } FwkInfo("Create Pool complete with poolName= {0}", poolName); } public virtual RegionFactory CreatePool(RegionFactory attr, int redundancyLevel) { string mode = Util.GetEnvironmentVariable("POOLOPT"); if (mode == "poolwithendpoints") { string EndPoints = Util.BBGet(JavaServerBB, EndPointTag) as string; ParseEndPoints(EndPoints, true, redundancyLevel); attr = attr.SetPoolName("_Test_Pool"); } else if (mode == "poolwithlocator") { string locatorAddress = (string)Util.BBGet(string.Empty, "LOCATOR_ADDRESS_POOL"); ParseEndPoints(locatorAddress, false, redundancyLevel); attr = attr.SetPoolName("_Test_Pool"); } return attr; } // TODO: format an appropriate line for logging. public virtual void SetTaskRunInfo(string regionTag, string taskName, int numKeys, int numClients, int valueSize, int numThreads) { m_taskData = new FwkTaskData(regionTag, taskName, numKeys, numClients, valueSize, numThreads); } public virtual void AddTaskRunRecord(int iters, TimeSpan elapsedTime) { double opsPerSec = iters / elapsedTime.TotalSeconds; double micros = elapsedTime.TotalMilliseconds * 1000; string recordStr = string.Format("{0} -- {1}ops/sec, {2} ops, {3} micros", m_taskData.GetLogString(), opsPerSec, iters, micros); lock (((ICollection)m_taskRecords).SyncRoot) { m_taskRecords.Add(recordStr); } Util.RawLog(string.Format("[PerfSuite] {0}{1}", recordStr, Environment.NewLine)); Util.RawLog(string.Format("[PerfData],{0},{1},{2},{3},{4}{5}", m_taskData.GetCSVString(), opsPerSec, iters, micros, DateTime.Now.ToString("G"), Environment.NewLine)); } public virtual void RunTask(ClientTask task, int numThreads, int iters, int timedInterval, int maxTime, object data) { ClientBase client = null; try { if (numThreads > 1) { client = ClientGroup.Create(UnitThread.Create, numThreads); } else { client = new UnitThread(); } UnitFnMethod<UnitFnMethod<int, object>, int, object> taskDeleg = new UnitFnMethod<UnitFnMethod<int, object>, int, object>( client.Call<int, object>); task.StartRun(); IAsyncResult taskRes = taskDeleg.BeginInvoke( task.DoTask, iters, data, null, null); if (timedInterval > 0) { System.Threading.Thread.Sleep(timedInterval); task.EndRun(); } if (maxTime <= 0) { taskRes.AsyncWaitHandle.WaitOne(); } else if (!taskRes.AsyncWaitHandle.WaitOne(maxTime, false)) { throw new ClientTimeoutException("RunTask() timed out."); } taskDeleg.EndInvoke(taskRes); task.EndRun(); } finally { if (client != null) { client.Dispose(); } } } public virtual void EndTask() { lock (((ICollection)m_taskRecords).SyncRoot) { if (m_taskRecords.Count > 0) { StringBuilder summarySB = new StringBuilder(); foreach (string taskRecord in m_taskRecords) { summarySB.Append(Environment.NewLine + '\t' + taskRecord); } FwkInfo("TIMINGS:: Summary: {0}", summarySB.ToString()); m_taskRecords.Clear(); } } ClearCachedKeys(); PopTaskName(); } public QueryService<TKey, object> CheckQueryService() { string mode = Util.GetEnvironmentVariable("POOLOPT"); Pool/*<TKey, TVal>*/ pool = PoolManager/*<TKey, TVal>*/.Find("_Test_Pool"); return pool.GetQueryService<TKey, object>(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------- // // Microsoft Windows Client Platform // // // File: PriorityQueue.cs // // Contents: Implementation of PriorityQueue class. // // Created: 2-14-2005 Niklas Borson (niklasb) // //------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Collections.Generic; namespace MS.Internal { /// <summary> /// PriorityQueue provides a stack-like interface, except that objects /// "pushed" in arbitrary order are "popped" in order of priority, i.e., /// from least to greatest as defined by the specified comparer. /// </summary> /// <remarks> /// Push and Pop are each O(log N). Pushing N objects and them popping /// them all is equivalent to performing a heap sort and is O(N log N). /// </remarks> internal class PriorityQueue<T> { // // The _heap array represents a binary tree with the "shape" property. // If we number the nodes of a binary tree from left-to-right and top- // to-bottom as shown, // // 0 // / \ // / \ // 1 2 // / \ / \ // 3 4 5 6 // /\ / // 7 8 9 // // The shape property means that there are no gaps in the sequence of // numbered nodes, i.e., for all N > 0, if node N exists then node N-1 // also exists. For example, the next node added to the above tree would // be node 10, the right child of node 4. // // Because of this constraint, we can easily represent the "tree" as an // array, where node number == array index, and parent/child relationships // can be calculated instead of maintained explicitly. For example, for // any node N > 0, the parent of N is at array index (N - 1) / 2. // // In addition to the above, the first _count members of the _heap array // compose a "heap", meaning each child node is greater than or equal to // its parent node; thus, the root node is always the minimum (i.e., the // best match for the specified style, weight, and stretch) of the nodes // in the heap. // // Initially _count < 0, which means we have not yet constructed the heap. // On the first call to MoveNext, we construct the heap by "pushing" all // the nodes into it. Each successive call "pops" a node off the heap // until the heap is empty (_count == 0), at which time we've reached the // end of the sequence. // #region constructors internal PriorityQueue(int capacity, IComparer<T> comparer) { _heap = new T[capacity > 0 ? capacity : DefaultCapacity]; _count = 0; _comparer = comparer; } #endregion #region internal members /// <summary> /// Gets the number of items in the priority queue. /// </summary> internal int Count { get { return _count; } } /// <summary> /// Gets the first or topmost object in the priority queue, which is the /// object with the minimum value. /// </summary> internal T Top { get { Debug.Assert(_count > 0); if (!_isHeap) { Heapify(); } return _heap[0]; } } /// <summary> /// Adds an object to the priority queue. /// </summary> internal void Push(T value) { // Increase the size of the array if necessary. if (_count == _heap.Length) { Array.Resize<T>(ref _heap, _count * 2); } // A common usage is to Push N items, then Pop them. Optimize for that // case by treating Push as a simple append until the first Top or Pop, // which establishes the heap property. After that, Push needs // to maintain the heap property. if (_isHeap) { SiftUp(_count, ref value, 0); } else { _heap[_count] = value; } _count++; } /// <summary> /// Removes the first node (i.e., the logical root) from the heap. /// </summary> internal void Pop() { Debug.Assert(_count != 0); if (!_isHeap) { Heapify(); } if (_count > 0) { --_count; // discarding the root creates a gap at position 0. We fill the // gap with the item x from the last position, after first sifting // the gap to a position where inserting x will maintain the // heap property. This is done in two phases - SiftDown and SiftUp. // // The one-phase method found in many textbooks does 2 comparisons // per level, while this method does only 1. The one-phase method // examines fewer levels than the two-phase method, but it does // more comparisons unless x ends up in the top 2/3 of the tree. // That accounts for only n^(2/3) items, and x is even more likely // to end up near the bottom since it came from the bottom in the // first place. Overall, the two-phase method is noticeably better. T x = _heap[_count]; // lift item x out from the last position int index = SiftDown(0); // sift the gap at the root down to the bottom SiftUp(index, ref x, 0); // sift the gap up, and insert x in its rightful position _heap[_count] = default(T); // don't leak x } } #endregion #region private members // sift a gap at the given index down to the bottom of the heap, // return the resulting index private int SiftDown(int index) { // Loop invariants: // // 1. parent is the index of a gap in the logical tree // 2. leftChild is // (a) the index of parent's left child if it has one, or // (b) a value >= _count if parent is a leaf node // int parent = index; int leftChild = HeapLeftChild(parent); while (leftChild < _count) { int rightChild = HeapRightFromLeft(leftChild); int bestChild = (rightChild < _count && _comparer.Compare(_heap[rightChild], _heap[leftChild]) < 0) ? rightChild : leftChild; // Promote bestChild to fill the gap left by parent. _heap[parent] = _heap[bestChild]; // Restore invariants, i.e., let parent point to the gap. parent = bestChild; leftChild = HeapLeftChild(parent); } return parent; } // sift a gap at index up until it reaches the correct position for x, // or reaches the given boundary. Place x in the resulting position. private void SiftUp(int index, ref T x, int boundary) { while (index > boundary) { int parent = HeapParent(index); if (_comparer.Compare(_heap[parent], x) > 0) { _heap[index] = _heap[parent]; index = parent; } else { break; } } _heap[index] = x; } // Establish the heap property: _heap[k] >= _heap[HeapParent(k)], for 0<k<_count // Do this "bottom up", by iterating backwards. At each iteration, the // property inductively holds for k >= HeapLeftChild(i)+2; the body of // the loop extends the property to the children of position i (namely // k=HLC(i) and k=HLC(i)+1) by lifting item x out from position i, sifting // the resulting gap down to the bottom, then sifting it back up (within // the subtree under i) until finding x's rightful position. // // Iteration i does work proportional to the height (distance to leaf) // of the node at position i. Half the nodes are leaves with height 0; // there's nothing to do for these nodes, so we skip them by initializing // i to the last non-leaf position. A quarter of the nodes have height 1, // an eigth have height 2, etc. so the total work is ~ 1*n/4 + 2*n/8 + // 3*n/16 + ... = O(n). This is much cheaper than maintaining the // heap incrementally during the "Push" phase, which would cost O(n*log n). private void Heapify() { if (!_isHeap) { for (int i = _count/2 - 1; i >= 0; --i) { // we use a two-phase method for the same reason Pop does T x = _heap[i]; int index = SiftDown(i); SiftUp(index, ref x, i); } _isHeap = true; } } /// <summary> /// Calculate the parent node index given a child node's index, taking advantage /// of the "shape" property. /// </summary> private static int HeapParent(int i) { return (i - 1) / 2; } /// <summary> /// Calculate the left child's index given the parent's index, taking advantage of /// the "shape" property. If there is no left child, the return value is >= _count. /// </summary> private static int HeapLeftChild(int i) { return (i * 2) + 1; } /// <summary> /// Calculate the right child's index from the left child's index, taking advantage /// of the "shape" property (i.e., sibling nodes are always adjacent). If there is /// no right child, the return value >= _count. /// </summary> private static int HeapRightFromLeft(int i) { return i + 1; } private T[] _heap; private int _count; private IComparer<T> _comparer; private bool _isHeap; private const int DefaultCapacity = 6; #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="ExpandedLandingPageViewServiceClient"/> instances.</summary> public sealed partial class ExpandedLandingPageViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ExpandedLandingPageViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ExpandedLandingPageViewServiceSettings"/>.</returns> public static ExpandedLandingPageViewServiceSettings GetDefault() => new ExpandedLandingPageViewServiceSettings(); /// <summary> /// Constructs a new <see cref="ExpandedLandingPageViewServiceSettings"/> object with default settings. /// </summary> public ExpandedLandingPageViewServiceSettings() { } private ExpandedLandingPageViewServiceSettings(ExpandedLandingPageViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetExpandedLandingPageViewSettings = existing.GetExpandedLandingPageViewSettings; OnCopy(existing); } partial void OnCopy(ExpandedLandingPageViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ExpandedLandingPageViewServiceClient.GetExpandedLandingPageView</c> and /// <c>ExpandedLandingPageViewServiceClient.GetExpandedLandingPageViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetExpandedLandingPageViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ExpandedLandingPageViewServiceSettings"/> object.</returns> public ExpandedLandingPageViewServiceSettings Clone() => new ExpandedLandingPageViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="ExpandedLandingPageViewServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class ExpandedLandingPageViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ExpandedLandingPageViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ExpandedLandingPageViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ExpandedLandingPageViewServiceClientBuilder() { UseJwtAccessWithScopes = ExpandedLandingPageViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ExpandedLandingPageViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ExpandedLandingPageViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ExpandedLandingPageViewServiceClient Build() { ExpandedLandingPageViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ExpandedLandingPageViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ExpandedLandingPageViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ExpandedLandingPageViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ExpandedLandingPageViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<ExpandedLandingPageViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ExpandedLandingPageViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ExpandedLandingPageViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ExpandedLandingPageViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ExpandedLandingPageViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ExpandedLandingPageViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch expanded landing page views. /// </remarks> public abstract partial class ExpandedLandingPageViewServiceClient { /// <summary> /// The default endpoint for the ExpandedLandingPageViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ExpandedLandingPageViewService scopes.</summary> /// <remarks> /// The default ExpandedLandingPageViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ExpandedLandingPageViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ExpandedLandingPageViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> public static stt::Task<ExpandedLandingPageViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ExpandedLandingPageViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ExpandedLandingPageViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ExpandedLandingPageViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> public static ExpandedLandingPageViewServiceClient Create() => new ExpandedLandingPageViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ExpandedLandingPageViewServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ExpandedLandingPageViewServiceSettings"/>.</param> /// <returns>The created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> internal static ExpandedLandingPageViewServiceClient Create(grpccore::CallInvoker callInvoker, ExpandedLandingPageViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient = new ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient(callInvoker); return new ExpandedLandingPageViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ExpandedLandingPageViewService client</summary> public virtual ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageView(new GetExpandedLandingPageViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageViewAsync(new GetExpandedLandingPageViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(gagvr::ExpandedLandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageView(new GetExpandedLandingPageViewRequest { ResourceNameAsExpandedLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(gagvr::ExpandedLandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageViewAsync(new GetExpandedLandingPageViewRequest { ResourceNameAsExpandedLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(gagvr::ExpandedLandingPageViewName resourceName, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ExpandedLandingPageViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch expanded landing page views. /// </remarks> public sealed partial class ExpandedLandingPageViewServiceClientImpl : ExpandedLandingPageViewServiceClient { private readonly gaxgrpc::ApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView> _callGetExpandedLandingPageView; /// <summary> /// Constructs a client wrapper for the ExpandedLandingPageViewService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ExpandedLandingPageViewServiceSettings"/> used within this client. /// </param> public ExpandedLandingPageViewServiceClientImpl(ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient, ExpandedLandingPageViewServiceSettings settings) { GrpcClient = grpcClient; ExpandedLandingPageViewServiceSettings effectiveSettings = settings ?? ExpandedLandingPageViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetExpandedLandingPageView = clientHelper.BuildApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView>(grpcClient.GetExpandedLandingPageViewAsync, grpcClient.GetExpandedLandingPageView, effectiveSettings.GetExpandedLandingPageViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetExpandedLandingPageView); Modify_GetExpandedLandingPageViewApiCall(ref _callGetExpandedLandingPageView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetExpandedLandingPageViewApiCall(ref gaxgrpc::ApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView> call); partial void OnConstruction(ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient, ExpandedLandingPageViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ExpandedLandingPageViewService client</summary> public override ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient GrpcClient { get; } partial void Modify_GetExpandedLandingPageViewRequest(ref GetExpandedLandingPageViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ExpandedLandingPageView GetExpandedLandingPageView(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExpandedLandingPageViewRequest(ref request, ref callSettings); return _callGetExpandedLandingPageView.Sync(request, callSettings); } /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExpandedLandingPageViewRequest(ref request, ref callSettings); return _callGetExpandedLandingPageView.Async(request, callSettings); } } }
// 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.Diagnostics; using System.IO; using System.Linq; using System.Text; using Microsoft.Cci; using Microsoft.Cci.Extensions; using Microsoft.Cci.MutableCodeModel; using System.Globalization; using Microsoft.DiaSymReader.Tools; using System.Runtime.InteropServices; namespace GenFacades { public class Generator { private const uint ReferenceAssemblyFlag = 0x70; public static bool Execute( string seeds, string contracts, string facadePath, Version assemblyFileVersion = null, bool clearBuildAndRevision = false, bool ignoreMissingTypes = false, bool ignoreBuildAndRevisionMismatch = false, bool buildDesignTimeFacades = false, string inclusionContracts = null, ErrorTreatment seedLoadErrorTreatment = ErrorTreatment.Default, ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default, string[] seedTypePreferencesUnsplit = null, bool forceZeroVersionSeeds = false, bool producePdb = true, string partialFacadeAssemblyPath = null, bool buildPartialReferenceFacade = false) { if (!Directory.Exists(facadePath)) Directory.CreateDirectory(facadePath); var nameTable = new NameTable(); var internFactory = new InternFactory(); try { Dictionary<string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit); using (var contractHost = new HostEnvironment(nameTable, internFactory)) using (var seedHost = new HostEnvironment(nameTable, internFactory)) { contractHost.LoadErrorTreatment = contractLoadErrorTreatment; seedHost.LoadErrorTreatment = seedLoadErrorTreatment; var contractAssemblies = LoadAssemblies(contractHost, contracts); IReadOnlyDictionary<string, IEnumerable<string>> docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts); IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray(); IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef; if (forceZeroVersionSeeds) { // Create a deep copier, copy the seed assemblies, and zero out their versions. var copier = new MetadataDeepCopier(seedHost); for (int i = 0; i < seedAssemblies.Length; i++) { var mutableSeed = copier.Copy(seedAssemblies[i]); mutableSeed.Version = new Version(0, 0, 0, 0); // Copy the modified seed assembly back. seedAssemblies[i] = mutableSeed; if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey) { seedCoreAssemblyRef = mutableSeed; } } } var typeTable = GenerateTypeTable(seedAssemblies); var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion); if (buildPartialReferenceFacade && ignoreMissingTypes) { throw new FacadeGenerationException( "When buildPartialReferenceFacade is specified ignoreMissingTypes must not be specified."); } if (partialFacadeAssemblyPath != null) { if (contractAssemblies.Count() != 1) { throw new FacadeGenerationException( "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified."); } if (buildPartialReferenceFacade) { throw new FacadeGenerationException( "When partialFacadeAssemblyPath is specified, buildPartialReferenceFacade must not be specified."); } IAssembly contractAssembly = contractAssemblies.First(); IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath); if (contractAssembly.Name != partialFacadeAssembly.Name || contractAssembly.Version.Major != partialFacadeAssembly.Version.Major || contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor || (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) || (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) || contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken()) { throw new FacadeGenerationException( string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}", contractAssembly.AssemblyIdentity, partialFacadeAssembly.AssemblyIdentity)); } Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly, forceAssemblyReferenceVersionsToZero: forceZeroVersionSeeds); if (filledPartialFacade == null) { Trace.TraceError("Errors were encountered while generating the facade."); return false; } string pdbLocation = null; if (producePdb) { string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath); pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb"); if (producePdb && !File.Exists(pdbLocation)) { pdbLocation = null; Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated."); } } OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation); } else { foreach (var contract in contractAssemblies) { Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes, buildPartialReferenceFacade: buildPartialReferenceFacade); if (facade == null) { #if !COREFX Debug.Assert(Environment.ExitCode != 0); #endif return false; } OutputFacadeToFile(facadePath, seedHost, facade, contract); } } } return true; } catch (FacadeGenerationException ex) { Trace.TraceError(ex.Message); #if !COREFX Debug.Assert(Environment.ExitCode != 0); #endif return false; } } private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null) { bool needsConversion = false; string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb"); string finalPdbOutputPath = pdbOutputPath; // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name. string facadeFileName = Path.GetFileName(contract.Location); string facadeOutputPath = Path.Combine(facadePath, facadeFileName); using (Stream peOutStream = File.Create(facadeOutputPath)) { if (pdbLocation != null) { if (File.Exists(pdbLocation)) { // Convert from portable to windows PDBs if necessary. If we convert // set the pdbOutput path to a *.windows.pdb file so we can convert it back // to 'finalPdbOutputPath'. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) needsConversion = ConvertFromPortableIfNecessary(facade.Location, ref pdbLocation); if (needsConversion) { // We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server string pdbOutputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbOutputPath), "WindowsPdb"); Directory.CreateDirectory(pdbOutputPathPdbDir); pdbOutputPath = Path.Combine(pdbOutputPathPdbDir, Path.GetFileName(pdbOutputPath)); } // do the main GenFacades logic (which today only works with windows PDBs). using (Stream pdbReadStream = File.OpenRead(pdbLocation)) using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost)) using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader)) { PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter); } } else { throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation); } } else { PeWriter.WritePeToStream(facade, seedHost, peOutStream); } } // If we started with Portable PDBs we need to convert the output to portable again. // We have to do this after facadeOutputPath is closed for writing. if (needsConversion) { Trace.TraceInformation("Converting PDB generated by GenFacades " + pdbOutputPath + " to portable format " + finalPdbOutputPath); ConvertFromWindowsPdb(facadeOutputPath, pdbOutputPath, finalPdbOutputPath); } } /// <summary> /// Given dllInputPath determine if it is portable. If so convert it *\WindowsPdb\*.pdb and update 'pdbInputPath' to /// point to this converted file. /// Returns true if the conversion was done (that is the original file was protable). /// 'dllInputPath' is the DLL that goes along with 'pdbInputPath'. /// </summary> private static bool ConvertFromPortableIfNecessary(string dllInputPath, ref string pdbInputPath) { string originalPdbInputPath = pdbInputPath; using (Stream pdbReadStream = File.OpenRead(pdbInputPath)) { // If the input is not portable, there is nothing to do, and we can early out. if (!PdbConverter.IsPortable(pdbReadStream)) return false; // We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server string pdbInputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbInputPath), "WindowsPdb"); Directory.CreateDirectory(pdbInputPathPdbDir); pdbInputPath = Path.Combine(pdbInputPathPdbDir, Path.GetFileName(pdbInputPath)); Trace.TraceInformation("PDB " + originalPdbInputPath + " is a portable PDB, converting it to " + pdbInputPath); PdbConverter converter = new PdbConverter(d => Trace.TraceError(d.ToString(CultureInfo.InvariantCulture))); using (Stream peStream = File.OpenRead(dllInputPath)) using (Stream pdbWriteStream = File.OpenWrite(pdbInputPath)) { converter.ConvertPortableToWindows(peStream, pdbReadStream, pdbWriteStream, PdbConversionOptions.SuppressSourceLinkConversion); } } return true; } /// <summary> /// Convert the windows PDB winPdbInputPath to portablePdbOutputPath. /// 'dllInputPath' is the DLL that goes along with 'winPdbInputPath'. /// </summary> private static void ConvertFromWindowsPdb(string dllInputPath, string winPdbInputPath, string portablePdbOutputPath) { PdbConverter converter = new PdbConverter(d => Trace.TraceError(d.ToString(CultureInfo.InvariantCulture))); using (Stream peStream = File.OpenRead(dllInputPath)) using (Stream pdbReadStream = File.OpenRead(winPdbInputPath)) using (Stream pdbWriteStream = File.OpenWrite(portablePdbOutputPath)) { converter.ConvertWindowsToPortable(peStream, pdbReadStream, pdbWriteStream); } } private static Dictionary<string, string> ParseSeedTypePreferences(string[] preferences) { var dictionary = new Dictionary<string, string>(StringComparer.Ordinal); if (preferences != null) { foreach (string preference in preferences) { int i = preference.IndexOf('='); if (i < 0) { throw new FacadeGenerationException("Invalid seed type preference. Correct usage is /preferSeedType:FullTypeName=AssemblyName"); } string key = preference.Substring(0, i); string value = preference.Substring(i + 1); if (!key.StartsWith("T:", StringComparison.Ordinal)) { key = "T:" + key; } string existingValue; if (dictionary.TryGetValue(key, out existingValue)) { Trace.TraceWarning("Overriding /preferSeedType:{0}={1} with /preferSeedType:{2}={3}.", key, existingValue, key, value); } dictionary[key] = value; } } return dictionary; } private static IEnumerable<IAssembly> LoadAssemblies(HostEnvironment host, string assemblyPaths) { host.UnifyToLibPath = true; string[] splitPaths = HostEnvironment.SplitPaths(assemblyPaths); foreach (string path in splitPaths) { if (Directory.Exists(path)) { host.AddLibPath(Path.GetFullPath(path)); } else if (File.Exists(path)) { host.AddLibPath(Path.GetDirectoryName(Path.GetFullPath(path))); } } return host.LoadAssemblies(splitPaths); } private static IReadOnlyDictionary<string, IEnumerable<string>> GenerateDocIdTable(IEnumerable<IAssembly> contractAssemblies, string inclusionContracts) { Dictionary<string, HashSet<string>> mutableDocIdTable = new Dictionary<string, HashSet<string>>(); foreach (IAssembly contractAssembly in contractAssemblies) { string simpleName = contractAssembly.AssemblyIdentity.Name.Value; if (mutableDocIdTable.ContainsKey(simpleName)) throw new FacadeGenerationException(string.Format("Multiple contracts named \"{0}\" specified on -contracts.", simpleName)); mutableDocIdTable[simpleName] = new HashSet<string>(EnumerateDocIdsToForward(contractAssembly)); } if (inclusionContracts != null) { foreach (string inclusionContractPath in HostEnvironment.SplitPaths(inclusionContracts)) { // Assembly identity conflicts are permitted and normal in the inclusion contract list so load each one in a throwaway host to avoid problems. using (HostEnvironment inclusionHost = new HostEnvironment(new NameTable(), new InternFactory())) { IAssembly inclusionAssembly = inclusionHost.LoadAssemblyFrom(inclusionContractPath); if (inclusionAssembly == null || inclusionAssembly is Dummy) throw new FacadeGenerationException(string.Format("Could not load assembly \"{0}\".", inclusionContractPath)); string simpleName = inclusionAssembly.Name.Value; HashSet<string> hashset; if (!mutableDocIdTable.TryGetValue(simpleName, out hashset)) { Trace.TraceWarning("An assembly named \"{0}\" was specified in the -include list but no contract was specified named \"{0}\". Ignoring.", simpleName); } else { foreach (string docId in EnumerateDocIdsToForward(inclusionAssembly)) { hashset.Add(docId); } } } } } Dictionary<string, IEnumerable<string>> docIdTable = new Dictionary<string, IEnumerable<string>>(); foreach (KeyValuePair<string, HashSet<string>> kv in mutableDocIdTable) { string key = kv.Key; IEnumerable<string> sortedDocIds = kv.Value.OrderBy(s => s, StringComparer.OrdinalIgnoreCase); docIdTable.Add(key, sortedDocIds); } return docIdTable; } private static IEnumerable<string> EnumerateDocIdsToForward(IAssembly contractAssembly) { // Use INamedTypeReference instead of INamespaceTypeReference in order to also include nested // class type-forwards. var typeForwardsToForward = contractAssembly.ExportedTypes.Select(alias => alias.AliasedType) .OfType<INamedTypeReference>(); var typesToForward = contractAssembly.GetAllTypes().Where(t => TypeHelper.IsVisibleOutsideAssembly(t)) .OfType<INamespaceTypeDefinition>(); List<string> result = typeForwardsToForward.Concat(typesToForward) .Select(type => TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId)).ToList(); foreach(var type in typesToForward) { AddNestedTypeDocIds(result, type); } return result; } private static void AddNestedTypeDocIds(List<string> docIds, INamedTypeDefinition type) { foreach (var nestedType in type.NestedTypes) { if (TypeHelper.IsVisibleOutsideAssembly(nestedType)) docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId)); AddNestedTypeDocIds(docIds, nestedType); } } private static IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> GenerateTypeTable(IEnumerable<IAssembly> seedAssemblies) { var typeTable = new Dictionary<string, IReadOnlyList<INamedTypeDefinition>>(); foreach (var assembly in seedAssemblies) { foreach (var type in assembly.GetAllTypes().OfType<INamedTypeDefinition>()) { if (!TypeHelper.IsVisibleOutsideAssembly(type)) continue; AddTypeAndNestedTypesToTable(typeTable, type); } } return typeTable; } private static void AddTypeAndNestedTypesToTable(Dictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, INamedTypeDefinition type) { if (type != null) { IReadOnlyList<INamedTypeDefinition> seedTypes; string docId = TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId); if (!typeTable.TryGetValue(docId, out seedTypes)) { seedTypes = new List<INamedTypeDefinition>(1); typeTable.Add(docId, seedTypes); } if (!seedTypes.Contains(type)) ((List<INamedTypeDefinition>)seedTypes).Add(type); foreach (INestedTypeDefinition nestedType in type.NestedTypes) { if (TypeHelper.IsVisibleOutsideAssembly(nestedType)) AddTypeAndNestedTypesToTable(typeTable, nestedType); } } } private class FacadeGenerator { private readonly IMetadataHost _seedHost; private readonly IMetadataHost _contractHost; private readonly IReadOnlyDictionary<string, IEnumerable<string>> _docIdTable; private readonly IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> _typeTable; private readonly IReadOnlyDictionary<string, string> _seedTypePreferences; private readonly bool _clearBuildAndRevision; private readonly bool _buildDesignTimeFacades; private readonly Version _assemblyFileVersion; public FacadeGenerator( IMetadataHost seedHost, IMetadataHost contractHost, IReadOnlyDictionary<string, IEnumerable<string>> docIdTable, IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, IReadOnlyDictionary<string, string> seedTypePreferences, bool clearBuildAndRevision, bool buildDesignTimeFacades, Version assemblyFileVersion ) { _seedHost = seedHost; _contractHost = contractHost; _docIdTable = docIdTable; _typeTable = typeTable; _seedTypePreferences = seedTypePreferences; _clearBuildAndRevision = clearBuildAndRevision; _buildDesignTimeFacades = buildDesignTimeFacades; _assemblyFileVersion = assemblyFileVersion; } public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null, bool buildPartialReferenceFacade = false, bool forceAssemblyReferenceVersionsToZero = false) { Assembly assembly; if (overrideContractAssembly != null) { MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost); assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present } else { MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost); assembly = copier.Copy(contractAssembly); // if building a reference facade don't strip the contract if (!buildPartialReferenceFacade) { ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null); rewriter.Rewrite(assembly); } } if (forceAssemblyReferenceVersionsToZero) { foreach (AssemblyReference ar in assembly.AssemblyReferences) { ar.Version = new Version(0, 0, 0, 0); } } string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value; IEnumerable<string> docIds = _docIdTable[contractAssemblyName]; // Add all the type forwards bool error = false; Dictionary<string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef); IEnumerable<string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id)); Dictionary<string, INamedTypeReference> forwardedTypes = new Dictionary<string, INamedTypeReference>(); foreach (string docId in docIdsToForward) { IReadOnlyList<INamedTypeDefinition> seedTypes; if (!_typeTable.TryGetValue(docId, out seedTypes)) { if (!ignoreMissingTypes && !buildPartialReferenceFacade) { Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId); error = true; } continue; } INamedTypeDefinition seedType = GetSeedType(docId, seedTypes); if (seedType == null) { TraceDuplicateSeedTypeError(docId, seedTypes); error = true; continue; } if (buildPartialReferenceFacade) { // honor preferSeedType for keeping contract type string preferredSeedAssembly; bool keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) && contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase); if (keepType) { continue; } assembly.AllTypes.Remove(existingDocIds[docId]); forwardedTypes.Add(docId, seedType); } AddTypeForward(assembly, seedType); } if (buildPartialReferenceFacade) { if (forwardedTypes.Count == 0) { Trace.TraceError("Did not find any types in any of the seed assemblies."); return null; } else { // for any thing that's now a typeforward, make sure typerefs point to that rather than // the type previously inside the assembly. TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType => { INamedTypeReference newType = null; return forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType; }); var remainingTypes = assembly.AllTypes.Where(t => t.Name.Value != "<Module>"); if (!remainingTypes.Any()) { Trace.TraceInformation($"Removed all types from {contractAssembly.Name} thus will remove ReferenceAssemblyAttribute."); assembly.AssemblyAttributes.RemoveAll(ca => ca.FullName() == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute"); assembly.Flags &= ~ReferenceAssemblyFlag; } typeRefRewriter.Rewrite(assembly); } } if (error) { return null; } if (_assemblyFileVersion != null) { assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString())); assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString())); } if (_buildDesignTimeFacades) { assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly)); assembly.Flags |= ReferenceAssemblyFlag; } if (_clearBuildAndRevision) { assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0); } AddWin32VersionResource(contractAssembly.Location, assembly); return assembly; } private INamedTypeDefinition GetSeedType(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes) { Debug.Assert(seedTypes.Count != 0); // we should already have checked for non-existent types. if (seedTypes.Count == 1) { return seedTypes[0]; } string preferredSeedAssembly; if (_seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly)) { return seedTypes.SingleOrDefault(t => String.Equals(t.GetAssembly().Name.Value, preferredSeedAssembly, StringComparison.OrdinalIgnoreCase)); } return null; } private static void TraceDuplicateSeedTypeError(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes) { Trace.TraceError("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId); foreach (INamedTypeDefinition type in seedTypes) { Trace.TraceError(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value); } } private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType) { var alias = new NamespaceAliasForType(); alias.AliasedType = ConvertDefinitionToReferenceIfTypeIsNested(seedType, _seedHost); alias.IsPublic = true; if (assembly.ExportedTypes == null) assembly.ExportedTypes = new List<IAliasForType>(); // Make sure that the typeforward doesn't already exist in the ExportedTypes if (!assembly.ExportedTypes.Any(t => t.AliasedType.RefDocId() == alias.AliasedType.RefDocId())) assembly.ExportedTypes.Add(alias); else throw new FacadeGenerationException($"{seedType.FullName()} typeforward already exists"); } private void AddWin32VersionResource(string contractLocation, Assembly facade) { var versionInfo = FileVersionInfo.GetVersionInfo(contractLocation); var versionSerializer = new VersionResourceSerializer( true, versionInfo.Comments, versionInfo.CompanyName, versionInfo.FileDescription, _assemblyFileVersion == null ? versionInfo.FileVersion : _assemblyFileVersion.ToString(), versionInfo.InternalName, versionInfo.LegalCopyright, versionInfo.LegalTrademarks, versionInfo.OriginalFilename, versionInfo.ProductName, _assemblyFileVersion == null ? versionInfo.ProductVersion : _assemblyFileVersion.ToString(), facade.Version); using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream, Encoding.Unicode, true)) { versionSerializer.WriteVerResource(writer); var resource = new Win32Resource(); resource.Id = 1; resource.TypeId = 0x10; resource.Data = stream.ToArray().ToList(); facade.Win32Resources.Add(resource); } } // This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table // for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition // so we make an ITypeReference copy as a workaround. private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host) { var nestedTypeDef = typeDef as INestedTypeDefinition; if (nestedTypeDef == null) return typeDef; var typeRef = new NestedTypeReference(); typeRef.Copy(nestedTypeDef, host.InternFactory); return typeRef; } private ICustomAttribute CreateAttribute(string typeName, IAssembly seedCoreAssembly, string argument = null) { var type = seedCoreAssembly.GetAllTypes().FirstOrDefault(t => t.FullName() == typeName); if (type == null) { throw new FacadeGenerationException(String.Format("Cannot find {0} type in seed core assembly.", typeName)); } IEnumerable<IMethodDefinition> constructors = type.GetMembersNamed(_seedHost.NameTable.Ctor, false).OfType<IMethodDefinition>(); IMethodDefinition constructor = null; if (argument != null) { constructor = constructors.SingleOrDefault(m => m.ParameterCount == 1 && m.Parameters.First().Type.AreEquivalent("System.String")); } else { constructor = constructors.SingleOrDefault(m => m.ParameterCount == 0); } if (constructor == null) { throw new FacadeGenerationException(String.Format("Cannot find {0} constructor taking single string argument in seed core assembly.", typeName)); } var attribute = new CustomAttribute(); attribute.Constructor = constructor; if (argument != null) { var argumentExpression = new MetadataConstant(); argumentExpression.Type = _seedHost.PlatformType.SystemString; argumentExpression.Value = argument; attribute.Arguments = new List<IMetadataExpression>(1); attribute.Arguments.Add(argumentExpression); } return attribute; } } private class ReferenceAssemblyToFacadeRewriter : MetadataRewriter { private IMetadataHost _seedHost; private IMetadataHost _contractHost; private IAssemblyReference _seedCoreAssemblyReference; private bool _stripFileVersionAttributes; public ReferenceAssemblyToFacadeRewriter( IMetadataHost seedHost, IMetadataHost contractHost, IAssemblyReference seedCoreAssemblyReference, bool stripFileVersionAttributes) : base(seedHost) { _seedHost = seedHost; _contractHost = contractHost; _stripFileVersionAttributes = stripFileVersionAttributes; _seedCoreAssemblyReference = seedCoreAssemblyReference; } public override IAssemblyReference Rewrite(IAssemblyReference assemblyReference) { if (assemblyReference == null) return assemblyReference; if (assemblyReference.UnifiedAssemblyIdentity.Equals(_contractHost.CoreAssemblySymbolicIdentity) && !assemblyReference.ModuleIdentity.Equals(host.CoreAssemblySymbolicIdentity)) { assemblyReference = _seedCoreAssemblyReference; } return base.Rewrite(assemblyReference); } public override void RewriteChildren(RootUnitNamespace rootUnitNamespace) { var assemblyReference = rootUnitNamespace.Unit as IAssemblyReference; if (assemblyReference != null) rootUnitNamespace.Unit = Rewrite(assemblyReference).ResolvedUnit; base.RewriteChildren(rootUnitNamespace); } public override List<INamespaceMember> Rewrite(List<INamespaceMember> namespaceMembers) { // Ignore traversing or rewriting any namspace members. return base.Rewrite(new List<INamespaceMember>()); } public override void RewriteChildren(Assembly assembly) { // Clear all win32 resources. The version resource will get repopulated. assembly.Win32Resources = new List<IWin32Resource>(); // Remove all the references they will get repopulated while outputing. assembly.AssemblyReferences.Clear(); // Remove all the module references (aka native references) assembly.ModuleReferences = new List<IModuleReference>(); // Remove all file references (ex: *.nlp files in mscorlib) assembly.Files = new List<IFileReference>(); // Remove all security attributes (ex: permissionset in IL) assembly.SecurityAttributes = new List<ISecurityAttribute>(); // Reset the core assembly symbolic identity to the seed core assembly (e.g. mscorlib, corefx) // and not the contract core (e.g. System.Runtime). assembly.CoreAssemblySymbolicIdentity = _seedCoreAssemblyReference.AssemblyIdentity; // Add reference to seed core assembly up-front so that we keep the same order as the C# compiler. assembly.AssemblyReferences.Add(_seedCoreAssemblyReference); // Remove all type definitions except for the "<Module>" type. Remove all fields and methods from it. NamespaceTypeDefinition moduleType = assembly.AllTypes.SingleOrDefault(t => t.Name.Value == "<Module>") as NamespaceTypeDefinition; assembly.AllTypes.Clear(); if (moduleType != null) { moduleType.Fields?.Clear(); moduleType.Methods?.Clear(); assembly.AllTypes.Add(moduleType); } // Remove any preexisting typeforwards. assembly.ExportedTypes = new List<IAliasForType>(); // Remove any preexisting resources. assembly.Resources = new List<IResourceReference>(); // Clear the reference assembly flag from the contract. // For design-time facades, it will be added back later. assembly.Flags &= ~ReferenceAssemblyFlag; // This flag should not be set until the delay-signed assembly we emit is actually signed. assembly.StrongNameSigned = false; base.RewriteChildren(assembly); } public override List<ICustomAttribute> Rewrite(List<ICustomAttribute> customAttributes) { if (customAttributes == null) return customAttributes; List<ICustomAttribute> newCustomAttributes = new List<ICustomAttribute>(); // Remove all of them except for the ones that begin with Assembly // Also remove AssemblyFileVersion and AssemblyInformationVersion if stripFileVersionAttributes is set foreach (ICustomAttribute attribute in customAttributes) { ITypeReference attributeType = attribute.Type; if (attributeType is Dummy) continue; string typeName = TypeHelper.GetTypeName(attributeType, NameFormattingOptions.OmitContainingNamespace | NameFormattingOptions.OmitContainingType); if (!typeName.StartsWith("Assembly")) continue; // We need to remove the signature key attribute otherwise we will not be able to re-sign these binaries. if (typeName == "AssemblySignatureKeyAttribute") continue; if (_stripFileVersionAttributes && ((typeName == "AssemblyFileVersionAttribute" || typeName == "AssemblyInformationalVersionAttribute"))) continue; newCustomAttributes.Add(attribute); } return base.Rewrite(newCustomAttributes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { public static IntPtr GetMainWindowHandle(int processId) { MainWindowFinder finder = new MainWindowFinder(); return finder.FindMainWindow(processId); } } internal sealed class MainWindowFinder { private const int GW_OWNER = 4; private IntPtr _bestHandle; private int _processId; public IntPtr FindMainWindow(int processId) { _bestHandle = (IntPtr)0; _processId = processId; Interop.User32.EnumThreadWindowsCallback callback = new Interop.User32.EnumThreadWindowsCallback(EnumWindowsCallback); Interop.User32.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); return _bestHandle; } private bool IsMainWindow(IntPtr handle) { if (Interop.User32.GetWindow(handle, GW_OWNER) != (IntPtr)0 || !Interop.User32.IsWindowVisible(handle)) return false; return true; } private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) { int processId; Interop.User32.GetWindowThreadProcessId(handle, out processId); if (processId == _processId) { if (IsMainWindow(handle)) { _bestHandle = handle; return false; } } return true; } } internal static partial class NtProcessManager { private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (;;) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount); char[] chars = new char[1024]; for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } } IntPtr moduleHandle = moduleHandles[i]; Interop.Kernel32.NtModuleInfo ntModuleInfo; if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo)) { HandleError(); continue; } var module = new ProcessModule() { ModuleMemorySize = ntModuleInfo.SizeOfImage, EntryPointAddress = ntModuleInfo.EntryPoint, BaseAddress = ntModuleInfo.BaseOfDll }; int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.ModuleName = new string(chars, 0, length); length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? new string(chars, 4, length - 4) : new string(chars, 0, length); modules.Add(module); } return modules; } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } } internal static partial class NtProcessInfoHelper { // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; internal static ProcessInfo[] GetProcessInfos(Predicate<int> processIdFilter = null) { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject(), processIdFilter); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using bv.common; using bv.common.Core; using bv.common.db.Core; using DevExpress.Data.PivotGrid; using DevExpress.XtraPivotGrid; using DevExpress.XtraPivotGrid.Data; using eidss.avr.db.AvrEventArgs.DevExpressEventArgsWrappers; using eidss.avr.db.Interfaces; using eidss.model.Avr.Pivot; using eidss.model.AVR.SourceData; using eidss.model.Core; using eidss.model.Resources; using EIDSS; namespace eidss.avr.db.Common { public class CustomSummaryHandler { private delegate bool ParserDelegate<T>(string s, out T result); private readonly string m_Unsupported; private readonly IAvrBasePivotGridView m_AvrPivotGrid; private readonly bool m_HasPopulationStatistics; private bool m_IsLookupException; public CustomSummaryHandler(IAvrBasePivotGridView avrPivotGrid) { Utils.CheckNotNull(avrPivotGrid, "avrPivotGrid"); m_AvrPivotGrid = avrPivotGrid; DataView view = LookupCache.Get(LookupTables.PopulationStatistics); m_HasPopulationStatistics = view != null && view.Count > 0; m_Unsupported = EidssMessages.Get("strUnsupportedCustomAggregate", "Unsupported Aggregate Function"); } #region Process Summary public void OnCustomSummary(object sender, BasePivotGridCustomSummaryEventArgs e) { try { if (m_AvrPivotGrid.LayoutRestoring) { return; } if (!CheckDataIsAvrField(e)) { return; } PivotDrillDownDataSource ds = e.CreateDrillDownDataSource(); if (ProcessSumSummary(e, ds)) { return; } if (ProcessMinSummary(e, ds)) { return; } if (ProcessMaxSummary(e, ds)) { return; } if (ProcessDistinctCountSummary(e, ds)) { return; } if (ProcessStatSummary(e, ds)) { return; } if (ProcessPopulationSummary(e, ds)) { return; } if (ProcessPopulationGenderSummary(e, ds)) { return; } if (ProcessPopulationAgeGroupGenderSummary(e, ds)) { return; } e.CustomValue = m_Unsupported; } catch (Exception ex) { e.CustomValue = ex; Trace.WriteLine(ex); } } private static bool ProcessSumSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.Sum) { return false; } e.CustomValue = GetCountOrSum(e, ds); return true; } private static bool ProcessMinSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.Min) { return false; } if (e.IsWeb || e.SummaryValue.Min is PivotErrorValue) { if (ds.RowCount != 0) { object firstValue = GetFirstValue(e, ds); IEnumerable<IComparable> values = GetComparableValues(e, ds, firstValue); e.CustomValue = values.Min(); } } else { e.CustomValue = e.SummaryValue.Min; } return true; } private static bool ProcessMaxSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.Max) { return false; } if (e.IsWeb || e.SummaryValue.Max is PivotErrorValue) { //this is because e.SummaryValue is empty in web if (ds.RowCount != 0) { object firstValue = GetFirstValue(e, ds); IEnumerable<IComparable> values = GetComparableValues(e, ds, firstValue); e.CustomValue = values.Max(); } } else { e.CustomValue = e.SummaryValue.Max; } return true; } private static IEnumerable<IComparable> GetComparableValues (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds, object firstValue) { IEnumerable<IComparable> result = new BaseCollection<IComparable>(); if (firstValue is String) { result = GetComparableValues<String>(e, ds); } else if (firstValue is Int64) { result = GetComparableValues(e, ds, (string s, out Int64 r) => Int64.TryParse(s, out r)); } else if (firstValue is Int32) { result = GetComparableValues(e, ds, (string s, out Int32 r) => Int32.TryParse(s, out r)); } else if (firstValue is Int16) { result = GetComparableValues(e, ds, (string s, out Int16 r) => Int16.TryParse(s, out r)); } else if (firstValue is DateTime) { result = GetComparableValues(e, ds, (string s, out DateTime r) => DateTime.TryParse(s, out r)); } else if (firstValue is Decimal) { result = GetComparableValues(e, ds, (string s, out Decimal r) => Decimal.TryParse(s, out r)); } else if (firstValue is Double) { result = GetComparableValues(e, ds, (string s, out Double r) => Double.TryParse(s, out r)); } else if (firstValue is Single) { result = GetComparableValues(e, ds, (string s, out Single r) => Single.TryParse(s, out r)); } else if (firstValue is DayOfWeek) { result = GetComparableValues(e, ds, (string s, out DayOfWeek r) => Enum.TryParse(s, out r)); } else if (firstValue is Boolean) { result = GetComparableValues(e, ds, (string s, out Boolean r) => Boolean.TryParse(s, out r)); } else if (firstValue is UInt64) { result = GetComparableValues(e, ds, (string s, out UInt64 r) => UInt64.TryParse(s, out r)); } else if (firstValue is UInt32) { result = GetComparableValues(e, ds, (string s, out UInt32 r) => UInt32.TryParse(s, out r)); } else if (firstValue is UInt16) { result = GetComparableValues(e, ds, (string s, out UInt16 r) => UInt16.TryParse(s, out r)); } else if (firstValue is Byte) { result = GetComparableValues(e, ds, (string s, out Byte r) => Byte.TryParse(s, out r)); } else if (firstValue is SByte) { result = GetComparableValues(e, ds, (string s, out SByte r) => SByte.TryParse(s, out r)); } else if (firstValue is IComparable) { result = GetComparableValues<IComparable>(e, ds); } return result; } private static IEnumerable<IComparable> GetComparableValues<T> (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds, ParserDelegate<T> parser = null) { var values = new List<IComparable>(); for (int i = 0; i < ds.RowCount; i++) { object data = ds[i][e.DataField]; if (data != null) { if (data.GetType() == typeof (T)) { values.Add((IComparable) (T) data); } else if (parser != null) { T value; if (parser(Utils.Str(data), out value)) { values.Add((IComparable) value); } } } } return values; } private bool ProcessDistinctCountSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.DistinctCount) { return false; } long result = 0; if (ds.RowCount != 0) { if (m_AvrPivotGrid.SingleSearchObject) { result = GetCount(e, ds); } else { object firstValue = GetFirstValue(e, ds); result = GetDistinctCount(e, ds, firstValue); } } e.CustomValue = result; return true; } private static long GetDistinctCount(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds, object firstValue) { long result = 0; if (firstValue is String) { result = GetDistinctCount<String>(e, ds); } else if (firstValue is Int64) { result = GetDistinctCount(e, ds, (string s, out Int64 r) => Int64.TryParse(s, out r)); } else if (firstValue is Int32) { result = GetDistinctCount(e, ds, (string s, out Int32 r) => Int32.TryParse(s, out r)); } else if (firstValue is Int16) { result = GetDistinctCount(e, ds, (string s, out Int16 r) => Int16.TryParse(s, out r)); } else if (firstValue is DateTime) { result = GetDistinctCount(e, ds, (string s, out DateTime r) => DateTime.TryParse(s, out r)); } else if (firstValue is Decimal) { result = GetDistinctCount(e, ds, (string s, out Decimal r) => Decimal.TryParse(s, out r)); } else if (firstValue is Double) { result = GetDistinctCount(e, ds, (string s, out Double r) => Double.TryParse(s, out r)); } else if (firstValue is Single) { result = GetDistinctCount(e, ds, (string s, out Single r) => Single.TryParse(s, out r)); } else if (firstValue is DayOfWeek) { result = GetDistinctCount(e, ds, (string s, out DayOfWeek r) => Enum.TryParse(s, out r)); } else if (firstValue is Boolean) { result = GetDistinctCount(e, ds, (string s, out Boolean r) => Boolean.TryParse(s, out r)); } else if (firstValue is UInt64) { result = GetDistinctCount(e, ds, (string s, out UInt64 r) => UInt64.TryParse(s, out r)); } else if (firstValue is UInt32) { result = GetDistinctCount(e, ds, (string s, out UInt32 r) => UInt32.TryParse(s, out r)); } else if (firstValue is UInt16) { result = GetDistinctCount(e, ds, (string s, out UInt16 r) => UInt16.TryParse(s, out r)); } else if (firstValue is Byte) { result = GetDistinctCount(e, ds, (string s, out Byte r) => Byte.TryParse(s, out r)); } else if (firstValue is SByte) { result = GetDistinctCount(e, ds, (string s, out SByte r) => SByte.TryParse(s, out r)); } else if (firstValue is IComparable) { result = GetDistinctCount<IComparable>(e, ds); } return result; } private static long GetDistinctCount<T> (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds, ParserDelegate<T> parser = null) { var values = new HashSet<T>(); for (int i = 0; i < ds.RowCount; i++) { object data = ds[i][e.DataField]; if (data != null) { if (data.GetType() == typeof (T)) { AddValueIfNotContains(values, (T) data); } else if (parser != null) { T value; if (parser(Utils.Str(data), out value)) { AddValueIfNotContains(values, value); } } } } return values.Count; } private static long GetCount(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { int count = 0; if (!e.IsWeb) { count = e.SummaryValue.Count; } else { for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (!Utils.IsEmpty(row[e.DataField])) { count++; } } } return count; } private static void AddValueIfNotContains<T>(HashSet<T> values, T value) { if (!values.Contains(value)) { values.Add(value); } } #region Process Statistics Summary private bool ProcessStatSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if ((e.AggregateFunction != CustomSummaryType.Average) && (e.AggregateFunction != CustomSummaryType.StdDev) && (e.AggregateFunction != CustomSummaryType.Variance)) { return false; } if (ProcessNumericStatSummary(e, ds)) { return true; } if (ProcessDefaultStatSummary(e, ds)) { return true; } return false; } private static bool ProcessNumericStatSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (!e.IsDataFieldNumeric) { return false; } if ((e.AggregateFunction != CustomSummaryType.Average) && (e.AggregateFunction != CustomSummaryType.StdDev) && (e.AggregateFunction != CustomSummaryType.Variance)) { return false; } if (ds.RowCount == 0) { e.CustomValue = 0; } if (e.IsWeb || e.SummaryValue.Average is PivotErrorValue) { //this is because e.SummaryValue is empty in web List<object> objects = GetValues(e, ds); List<double> values = ConvertValuesToDouble(objects); e.CustomValue = CalculateStatCustomValue(values, e.AggregateFunction); return true; } switch (e.AggregateFunction) { case CustomSummaryType.Average: e.CustomValue = e.SummaryValue.Average; return true; case CustomSummaryType.StdDev: e.CustomValue = e.SummaryValue.StdDev ?? 0; return true; case CustomSummaryType.Variance: double deviation = ValueConverter.GetValueFrom(e.SummaryValue.StdDev); e.CustomValue = deviation * deviation; return true; } return true; } private bool ProcessDefaultStatSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if ((e.AggregateFunction != CustomSummaryType.Average) && (e.AggregateFunction != CustomSummaryType.StdDev) && (e.AggregateFunction != CustomSummaryType.Variance)) { return false; } if (e.IsDataFieldNumeric) { return false; } var keyFields = new List<IAvrPivotGridField>(); //index == 0 for grand total int colIndex = e.ColumnField == null ? 0 : e.ColumnField.AreaIndex + 1; for (int i = colIndex; i < m_AvrPivotGrid.ColumnAreaFields.Count; i++) { keyFields.Add(m_AvrPivotGrid.ColumnAreaFields[i]); } int rowIndex = e.RowField == null ? 0 : e.RowField.AreaIndex + 1; for (int i = rowIndex; i < m_AvrPivotGrid.RowAreaFields.Count; i++) { keyFields.Add(m_AvrPivotGrid.RowAreaFields[i]); } IEnumerable<long> values = GetStatCountOrDistinctCountValues(e, keyFields, ds); //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery var doubles = new List<double>(); foreach (long value in values) { doubles.Add(value); } // ReSharper restore LoopCanBeConvertedToQuery e.CustomValue = CalculateStatCustomValue(doubles, e.AggregateFunction); return true; } private IEnumerable<long> GetStatCountOrDistinctCountValues (BasePivotGridCustomSummaryEventArgs e, List<IAvrPivotGridField> keyFields, PivotDrillDownDataSource ds) { Utils.CheckNotNull(e, "e"); if (e.DataField == null) { throw new ArgumentException("e.DataField should not be NULL"); } Utils.CheckNotNull(keyFields, "keyFields"); Utils.CheckNotNull(ds, "ds"); if (keyFields.Count == 0) { return new[] {GetCountOrDistinctCount(e, ds)}; } return e.BasicCountFunctions == CustomSummaryType.DistinctCount ? GetStatDistinctCountValues(e.DataField, keyFields, ds) : GetStatCountValues(e.DataField, keyFields, ds); } private static IEnumerable<long> GetStatCountValues (PivotGridFieldBase dataField, List<IAvrPivotGridField> keyFields, PivotDrillDownDataSource ds) { var valuesDictionary = new Dictionary<string, long>(); foreach (PivotDrillDownDataRow row in ds) { string key = GetKeyFromFields(keyFields, row); if (!valuesDictionary.ContainsKey(key)) { valuesDictionary.Add(key, 0); } int value = (row[dataField] == null) ? 0 : 1; valuesDictionary[key] += value; } return valuesDictionary.Values; } private static IEnumerable<long> GetStatDistinctCountValues (PivotGridFieldBase dataField, List<IAvrPivotGridField> keyFields, PivotDrillDownDataSource ds) { var valuesDictionary = new Dictionary<string, HashSet<string>>(); foreach (PivotDrillDownDataRow row in ds) { string key = GetKeyFromFields(keyFields, row); if (!valuesDictionary.ContainsKey(key)) { valuesDictionary.Add(key, new HashSet<string>()); } HashSet<string> valuesSet = valuesDictionary[key]; string dataFieldValue = Utils.Str(row[dataField]); if (!string.IsNullOrEmpty(dataFieldValue) && !valuesSet.Contains(dataFieldValue)) { valuesSet.Add(dataFieldValue); } } return valuesDictionary.Values.Select(valuesSet => (long)valuesSet.Count); } private static string GetKeyFromFields(IList<IAvrPivotGridField> keyFields, PivotDrillDownDataRow row) { switch (keyFields.Count()) { case 1: return GetKeyFromField(keyFields[0],row); case 2: return string.Format("{0}-{1}", GetKeyFromField(keyFields[0], row), GetKeyFromField(keyFields[1], row)); case 3: return string.Format("{0}-{1}-{2}", GetKeyFromField(keyFields[0], row), GetKeyFromField(keyFields[1], row), GetKeyFromField(keyFields[2], row)); default: var keyBuilder = new StringBuilder(); foreach (IAvrPivotGridField keyField in keyFields) { keyBuilder.AppendFormat("{0}-", GetKeyFromField(keyField, row)); } return keyBuilder.ToString(); } } private static string GetKeyFromField(IAvrPivotGridField field, PivotDrillDownDataRow row) { object fieldValue = row[field.FieldName]; if (field.IsDateTimeField && fieldValue is DateTime) { var date = ((DateTime)fieldValue); switch (field.GroupInterval) { case PivotGroupInterval.DateYear: fieldValue = date.Year; break; case PivotGroupInterval.DateMonth: fieldValue =date.Month; break; case PivotGroupInterval.DateQuarter: fieldValue = date.ToQuarter(); break; // it doesn't matter which first day of week is set case PivotGroupInterval.DateDayOfWeek: fieldValue = date.DayOfWeek; break; case PivotGroupInterval.DateDayOfYear: fieldValue = date.DayOfYear; break; case PivotGroupInterval.DateDay: fieldValue = date.Day; break; case PivotGroupInterval.DateWeekOfYear: fieldValue = DatePeriodHelper.GetWeekOfYear(date); break; case PivotGroupInterval.DateWeekOfMonth: fieldValue = DatePeriodHelper.GetWeekOfMonth(date); break; default: fieldValue = date; break; } } return Utils.Str(fieldValue); } private static double CalculateStatCustomValue(ICollection<double> values, CustomSummaryType summaryType) { double sum = values.Sum(); double average = (values.Count == 0) ? 0 : sum / values.Count; double displayValue = 0; //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery switch (summaryType) { case CustomSummaryType.Average: displayValue = average; break; case CustomSummaryType.StdDev: case CustomSummaryType.Variance: double sumVariance = 0; foreach (double value in values) { double delta = (value - average); sumVariance += delta * delta; } double variance = (values.Count <= 1) ? 0 : sumVariance / (values.Count - 1); displayValue = (summaryType == CustomSummaryType.StdDev) ? Math.Sqrt(variance) : variance; break; } // ReSharper restore LoopCanBeConvertedToQuery return displayValue; } private static List<double> ConvertValuesToDouble(List<object> values) { var result = new List<double>(); if (values.Count == 0) { return result; } //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery if (values[0] is Int16) { foreach (object value in values) { result.Add((Int16) value); } } else if (values[0] is Int32) { foreach (object value in values) { result.Add((Int32) value); } } else if (values[0] is Int64) { foreach (object value in values) { result.Add((Int64) value); } } else if (values[0] is Decimal) { foreach (object value in values) { result.Add((Double) (Decimal) value); } } else if (values[0] is Single) { foreach (object value in values) { result.Add((Single) value); } } else if (values[0] is Double) { foreach (object value in values) { result.Add((Double) value); } } else if (values[0] is UInt16) { foreach (object value in values) { result.Add((UInt16) value); } } else if (values[0] is UInt32) { foreach (object value in values) { result.Add((UInt32) value); } } else if (values[0] is UInt64) { foreach (object value in values) { result.Add((UInt64) value); } } // ReSharper restore LoopCanBeConvertedToQuery return result; } #endregion #region Process population statistics summary private bool ProcessPopulationSummary(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (!e.AggregateFunction.IsAdmUnit()) { return false; } if (ds.RowCount == 0 || !m_HasPopulationStatistics) { e.CustomValue = null; return true; } long count = GetCountOrDistinctCount(e, ds); var avrField = (IAvrPivotGridField) e.DataField; DateTime? dateId = GetLastDate(avrField, ds); long statSum = 0; var admUnitList = new List<string>(); string unitFieldName = avrField.GetSelectedAdmFieldAlias(); // take whole statistic for the country if no adm unit selected if (string.IsNullOrEmpty(unitFieldName) || unitFieldName == AvrPivotGridFieldHelper.VirtualCountryFieldName) { string countryId = string.Format("{0} ({1})", EidssSiteContext.Instance.CountryName, EidssSiteContext.Instance.CountryHascCode); statSum = GetPopulation(LookupTables.PopulationStatistics, countryId, dateId); } else { foreach (PivotDrillDownDataRow row in ds) { string admUnitId = Utils.Str(row[unitFieldName]); if (!admUnitList.Contains(admUnitId)) { admUnitList.Add(admUnitId); } } // if adm unit selected, but some data has no adm unit, then return null which will be displayed as "N/A" if (admUnitList.Contains(string.Empty)) { e.CustomValue = null; return true; } foreach (string admUnitId in admUnitList) { long nCurrentPopulation = GetPopulation(LookupTables.PopulationStatistics, admUnitId, dateId); //Make sense to proceed only if Statistical information for the Administrative unit is present "N/A" otherwise if (nCurrentPopulation != 0) { statSum += nCurrentPopulation; } else { e.CustomValue = null; return true; } } } int denominator = (e.AggregateFunction == CustomSummaryType.Pop10000) ? 10000 : 100000; SetStatisticsResultIntoCustomValue(e, denominator * count, statSum); return true; } private bool ProcessPopulationGenderSummary(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.PopGender100000) { return false; } IAvrPivotGridField genderField = m_AvrPivotGrid.GenderField; if (ds.RowCount == 0 || genderField == null) { e.CustomValue = null; return true; } // in case gender field outside - get statistical information for first row only (for other rows it is the same) string gender = IsKeyFieldOutside(e, genderField) ? "*" : Utils.Str(ds[0][genderField.FieldName]); DateTime? dateId = GetLastDate((IAvrPivotGridField) e.DataField, ds); long statSum = GetPopulation(LookupTables.PopulationGenderStatistics, gender, dateId); long count = GetCountOrDistinctCount(e, ds); SetStatisticsResultIntoCustomValue(e, 100000 * count, statSum); return true; } private bool ProcessPopulationAgeGroupGenderSummary (BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (e.AggregateFunction != CustomSummaryType.PopAgeGroupGender10000 && e.AggregateFunction != CustomSummaryType.PopAgeGroupGender100000) { return false; } IAvrPivotGridField genderField = m_AvrPivotGrid.GenderField; IAvrPivotGridField ageGroupField = m_AvrPivotGrid.AgeGroupField; if (ds.RowCount == 0 || genderField == null || ageGroupField == null) { e.CustomValue = null; return true; } // in case gender field outside - get statistical information for first row only (for other rows it is the same) string gender = IsKeyFieldOutside(e, genderField) ? "*" : Utils.Str(ds[0][genderField.FieldName]); string ageGroup = IsKeyFieldOutside(e, ageGroupField) ? "*" : Utils.Str(ds[0][ageGroupField.FieldName]); string key = string.Format("{0}_{1}", ageGroup, gender); DateTime? dateId = GetLastDate((IAvrPivotGridField) e.DataField, ds); long statSum = GetPopulation(LookupTables.PopulationAgeGroupGenderStatistics, key, dateId); long count = GetCountOrDistinctCount(e, ds); int denominator = (e.AggregateFunction == CustomSummaryType.PopAgeGroupGender10000) ? 10000 : 100000; SetStatisticsResultIntoCustomValue(e, denominator * count, statSum); return true; } private static DateTime? GetLastDate(IAvrPivotGridField avrField, PivotDrillDownDataSource ds) { DateTime? result = null; string dateFieldName = avrField.GetSelectedDateFieldAlias(); if (!string.IsNullOrEmpty(dateFieldName)) { for (int i = 0; i < ds.RowCount; i++) { object dateObject = ds[i][dateFieldName]; if (dateObject is DateTime) { var date = (DateTime) dateObject; if (!result.HasValue || result.Value < date) { result = date; } } } } return result; } private long GetCountOrDistinctCount(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { long count; if (e.BasicCountFunctions == CustomSummaryType.DistinctCount && !m_AvrPivotGrid.SingleSearchObject) { object firstValue = GetFirstValue(e, ds); count = GetDistinctCount(e, ds, firstValue); } else { count = GetCount(e, ds); } return count; } private static bool IsKeyFieldOutside(BasePivotGridCustomSummaryEventArgs e, IAvrPivotGridField keyField) { switch (keyField.Area) { case PivotArea.RowArea: return e.RowField == null || e.RowField.AreaIndex < keyField.AreaIndex; case PivotArea.ColumnArea: return e.ColumnField == null || e.ColumnField.AreaIndex < keyField.AreaIndex; default: return false; } } private static void SetStatisticsResultIntoCustomValue(BasePivotGridCustomSummaryEventArgs e, double valueSum, long statSum) { e.CustomValue = statSum == 0 ? (object) null : valueSum / statSum; } private long GetPopulation(LookupTables tableId, string statKey, DateTime? statDate) { if (m_IsLookupException) { return 0; } try { string strPopulation = null; if (statDate.HasValue) { string key = string.Format("{0}__{1:yyyy}", statKey, statDate); strPopulation = LookupCache.GetLookupValue(key, tableId, "intValue"); } // if no date defined or if no statistics found for given year if (Utils.IsEmpty(strPopulation)) { string key = string.Format("{0}__*", statKey); strPopulation = LookupCache.GetLookupValue(key, tableId, "intValue"); } return (Utils.IsEmpty(strPopulation)) ? 0 : Convert.ToInt64(strPopulation); } catch (Exception) { m_IsLookupException = true; throw; } } #endregion #endregion #region Helper methods private static bool CheckDataIsAvrField(BasePivotGridCustomSummaryEventArgs e) { if (e.DataField is IAvrPivotGridField) { return true; } string message = EidssMessages.Get("msgPivotFieldTypeMistmatch", "Pivot Field {0} should implement IAvrPivotGridField"); e.CustomValue = string.Format(message, e.DataField.FieldName); return false; } private static object GetCountOrSum(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { if (ds.RowCount == 0) { return 0; } if (!e.IsWeb) { if (!e.IsDataFieldNumeric) { return e.SummaryValue.Count; } if (e.IsDataFieldNumeric && !(e.SummaryValue.Summary is PivotErrorValue)) { return e.SummaryValue.Summary; } } //this is because e.SummaryValue is empty in web List<object> values = GetValues(e, ds); if (values.Count == 0) { return 0; } if (!e.IsDataFieldNumeric) { return values.Count; } //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery if (values[0] is Int16) { Int32 sum = 0; foreach (object value in values) { sum += (Int16) value; } return sum; } if (values[0] is Int32) { Int64 sum = 0; foreach (object value in values) { sum += (Int32) value; } return sum; } if (values[0] is Int64) { Int64 sum = 0; foreach (object value in values) { sum += (Int64) value; } return sum; } if (values[0] is Decimal) { Decimal sum = 0; foreach (object value in values) { sum += (Decimal) value; } return sum; } if (values[0] is Single) { Single sum = 0; foreach (object value in values) { sum += (Single) value; } return sum; } if (values[0] is Double) { Double sum = 0; foreach (object value in values) { sum += (Double) value; } return sum; } if (values[0] is UInt16) { UInt32 sum = 0; foreach (object value in values) { sum += (UInt16) value; } return sum; } if (values[0] is UInt32) { UInt64 sum = 0; foreach (object value in values) { sum += (UInt32) value; } return sum; } if (values[0] is UInt64) { UInt64 sum = 0; foreach (object value in values) { sum += (UInt64) value; } return sum; } if (values[0] is Byte) { Int32 sum = 0; foreach (object value in values) { sum += (Byte) value; } return sum; } if (values[0] is SByte) { Int32 sum = 0; foreach (object value in values) { sum += (SByte) value; } return sum; } return 0; // ReSharper restore LoopCanBeConvertedToQuery } private static List<object> GetValues(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { var values = new List<object>(); for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (row[e.DataField] != null) { values.Add(row[e.DataField]); } } return values; } private static object GetFirstValue(BasePivotGridCustomSummaryEventArgs e, PivotDrillDownDataSource ds) { object firstValue = null; for (int i = 0; i < ds.RowCount; i++) { firstValue = ds[i][e.DataField]; if (firstValue != null) { break; } } return firstValue; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using F2F.ReactiveNavigation.ViewModel; using FakeItEasy; using FluentAssertions; using Microsoft.Reactive.Testing; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoFakeItEasy; using ReactiveUI; using ReactiveUI.Testing; using Xunit; using F2F.Testing.Xunit.FakeItEasy; using Ploeh.AutoFixture.Idioms; using System.Windows.Input; namespace F2F.ReactiveNavigation.UnitTests { public class ReactiveItemsViewModel_Test : AutoMockFeature { public class ThrowingItemsViewModel : ReactiveItemsViewModel<ReactiveViewModel> { private readonly Exception _throwThis; public ThrowingItemsViewModel(Exception throwThis) { _throwThis = throwThis; } protected internal override Task<ReactiveViewModel> CreateItem() { throw _throwThis; } } private class ConfigurableItemsViewModel : ReactiveItemsViewModel<ReactiveViewModel> { private readonly Subject<Unit> _createItemCallTracker; private readonly IFixture _fixture; private readonly Subject<bool> _canAddItem; public ConfigurableItemsViewModel(IFixture fixture, Subject<Unit> createItemCallTracker, Subject<bool> canAddItem) { _fixture = fixture; _createItemCallTracker = createItemCallTracker; _canAddItem = canAddItem; } internal protected override Task<ReactiveViewModel> CreateItem() { _createItemCallTracker.OnNext(Unit.Default); return Task.FromResult(_fixture.Create<ReactiveViewModel>()); } protected internal override IEnumerable<IObservable<bool>> CanAddItemObservables() { yield return _canAddItem; foreach(var o in base.CanAddItemObservables()) yield return o; } } [Fact] public void AddItem_ShouldUseCreateItemFactoryMethod() { new TestScheduler().With(scheduler => { var callTracker = new Subject<Unit>(); Fixture.Inject(callTracker); Fixture.Inject(Fixture); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); var trackedCalls = callTracker.CreateCollection(); sut.AddItem.Execute(); scheduler.Advance(); trackedCalls.Count.Should().Be(1); }); } [Fact] public void AddItem_WhenCalled_ShouldHaveItemsCountEqualToOne() { new TestScheduler().With(scheduler => { var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); sut.AddItem.Execute(); scheduler.Advance(); sut.Items.Count.Should().Be(1); }); } [Fact] public void AddItem_WhenCanAddItemObservableYieldsFalse_ShouldReturnFalseForCanExecute() { new TestScheduler().With(scheduler => { var canAddItem = new Subject<bool>(); Fixture.Inject(canAddItem); Fixture.Inject(Fixture); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); canAddItem.OnNext(false); ((ICommand)sut.AddItem).CanExecute(null).Should().BeFalse(); }); } [Fact] public void AddItem_WhenCanAddItemObservableYieldsFalse_ShouldAddItemRegardlessOfCanAddItemObservable() { new TestScheduler().With(scheduler => { var canAddItem = new Subject<bool>(); Fixture.Inject(canAddItem); Fixture.Inject(Fixture); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); canAddItem.OnNext(false); // yield false for CanAdd sut.AddItem.Execute(); scheduler.Advance(); sut.Items.Count.Should().Be(1); }); } [Fact] public void CanAddItem_WhenUnobservedExceptionIsThrown_ShouldThrowAtCallSite() { new TestScheduler().With(scheduler => { var canAddItem = new Subject<bool>(); Fixture.Inject(canAddItem); Fixture.Inject(Fixture); var ex = Fixture.Create<Exception>(); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); canAddItem.OnError(ex); sut.AddItem.Execute(); scheduler.Invoking(sched => sched.Advance()).ShouldThrow<Exception>().Which.InnerException.Should().Be(ex); }); } [Fact] public void CanAddItem_WhenObservedExceptionIsThrown_ShouldPushExceptionToThrownExceptionsObservable() { new TestScheduler().With(scheduler => { var canAddItem = new Subject<bool>(); Fixture.Inject(canAddItem); Fixture.Inject(Fixture); var ex = Fixture.Create<Exception>(); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); var observedExceptions = sut.ThrownExceptions.CreateCollection(); canAddItem.OnError(ex); sut.AddItem.Execute(); scheduler.Advance(); observedExceptions.Single().Should().Be(ex); }); } [Fact] public void WhenAdded_WhenAddingItem_ShouldPushAddedItem() { new TestScheduler().With(scheduler => { var ex = Fixture.Create<Exception>(); var sut = Fixture.Build<ConfigurableItemsViewModel>().OmitAutoProperties().Create(); sut.InitializeAsync().Schedule(scheduler); bool addedItemWasPushed = false; using (sut.WhenAdded().Do(_ => addedItemWasPushed = true).Subscribe()) { sut.AddItem.Execute(); scheduler.Advance(); } addedItemWasPushed.Should().BeTrue(); }); } // The following 2 tests effectively test ReactiveCommand's exception policy. We don't need to test that! // I keep the tests here for a marker to think about piping the command's exceptions to the ThrownExceptionSource of the view model. //[Fact] //public void AddItem_WhenUnobservedExceptionIsThrown_ShouldThrowAtCallSite() //{ // new TestScheduler().With(scheduler => // { // var ex = Fixture.Create<Exception>(); // Fixture.Inject(ex); // var sut = Fixture.Create<ThrowingItemsViewModel>(); // sut.InitializeAsync().Schedule(scheduler); // sut.AddItem.Execute(null); // scheduler.Invoking(sched => sched.Advance()).ShouldThrow<Exception>().Which.InnerException.Should().Be(ex); // }); //} //[Fact] //public void AddItem_WhenObservedExceptionIsThrown_ShouldPushExceptionTo() //{ // new TestScheduler().With(scheduler => // { // var ex = Fixture.Create<Exception>(); // Fixture.Inject(ex); // var sut = Fixture.Create<ThrowingItemsViewModel>(); // sut.InitializeAsync().Schedule(scheduler); // var observedExceptions = sut.AddItem.ThrownExceptions.CreateCollection(); // sut.AddItem.Execute(null); // scheduler.Advance(); // observedExceptions.Single().Should().Be(ex); // }); //} } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Management.ApplicationPresentationScriptBinding", Namespace="urn:iControl")] public partial class ManagementApplicationPresentationScript : iControlInterface { public ManagementApplicationPresentationScript() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_checksum //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void add_checksum( string [] scripts ) { this.Invoke("add_checksum", new object [] { scripts}); } public System.IAsyncResult Beginadd_checksum(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_checksum", new object[] { scripts}, callback, asyncState); } public void Endadd_checksum(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_signature //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void add_signature( string [] scripts, string [] signing_keys, string [] public_certs ) { this.Invoke("add_signature", new object [] { scripts, signing_keys, public_certs}); } public System.IAsyncResult Beginadd_signature(string [] scripts,string [] signing_keys,string [] public_certs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_signature", new object[] { scripts, signing_keys, public_certs}, callback, asyncState); } public void Endadd_signature(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // clear_verification //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void clear_verification( string [] scripts ) { this.Invoke("clear_verification", new object [] { scripts}); } public System.IAsyncResult Beginclear_verification(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("clear_verification", new object[] { scripts}, callback, asyncState); } public void Endclear_verification(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void create( string [] scripts, string [] definitions ) { this.Invoke("create", new object [] { scripts, definitions}); } public System.IAsyncResult Begincreate(string [] scripts,string [] definitions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { scripts, definitions}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_application_presentation_scripts //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void delete_all_application_presentation_scripts( ) { this.Invoke("delete_all_application_presentation_scripts", new object [0]); } public System.IAsyncResult Begindelete_all_application_presentation_scripts(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_application_presentation_scripts", new object[0], callback, asyncState); } public void Enddelete_all_application_presentation_scripts(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_application_presentation_script //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void delete_application_presentation_script( string [] scripts ) { this.Invoke("delete_application_presentation_script", new object [] { scripts}); } public System.IAsyncResult Begindelete_application_presentation_script(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_application_presentation_script", new object[] { scripts}, callback, asyncState); } public void Enddelete_application_presentation_script(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] scripts ) { object [] results = this.Invoke("get_description", new object [] { scripts}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { scripts}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_ignore_verification_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_ignore_verification_state( string [] scripts ) { object [] results = this.Invoke("get_ignore_verification_state", new object [] { scripts}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_ignore_verification_state(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ignore_verification_state", new object[] { scripts}, callback, asyncState); } public CommonEnabledState [] Endget_ignore_verification_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_script //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_script( string [] scripts ) { object [] results = this.Invoke("get_script", new object [] { scripts}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_script(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_script", new object[] { scripts}, callback, asyncState); } public string [] Endget_script(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_verification_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonVerificationStatus [] get_verification_status( string [] scripts ) { object [] results = this.Invoke("get_verification_status", new object [] { scripts}); return ((CommonVerificationStatus [])(results[0])); } public System.IAsyncResult Beginget_verification_status(string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_verification_status", new object[] { scripts}, callback, asyncState); } public CommonVerificationStatus [] Endget_verification_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonVerificationStatus [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void set_description( string [] scripts, string [] descriptions ) { this.Invoke("set_description", new object [] { scripts, descriptions}); } public System.IAsyncResult Beginset_description(string [] scripts,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { scripts, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ignore_verification_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void set_ignore_verification_state( string [] scripts, CommonEnabledState [] states ) { this.Invoke("set_ignore_verification_state", new object [] { scripts, states}); } public System.IAsyncResult Beginset_ignore_verification_state(string [] scripts,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ignore_verification_state", new object[] { scripts, states}, callback, asyncState); } public void Endset_ignore_verification_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_script //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ApplicationPresentationScript", RequestNamespace="urn:iControl:Management/ApplicationPresentationScript", ResponseNamespace="urn:iControl:Management/ApplicationPresentationScript")] public void set_script( string [] scripts, string [] definitions ) { this.Invoke("set_script", new object [] { scripts, definitions}); } public System.IAsyncResult Beginset_script(string [] scripts,string [] definitions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_script", new object[] { scripts, definitions}, callback, asyncState); } public void Endset_script(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ConfigurationResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Conversations.V1 { public class ConfigurationResource : Resource { private static Request BuildFetchRequest(FetchConfigurationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Configuration", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch the global configuration of conversations on your account /// </summary> /// <param name="options"> Fetch Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Fetch(FetchConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch the global configuration of conversations on your account /// </summary> /// <param name="options"> Fetch Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> FetchAsync(FetchConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch the global configuration of conversations on your account /// </summary> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Fetch(ITwilioRestClient client = null) { var options = new FetchConfigurationOptions(); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch the global configuration of conversations on your account /// </summary> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> FetchAsync(ITwilioRestClient client = null) { var options = new FetchConfigurationOptions(); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateConfigurationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Conversations, "/v1/Configuration", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update the global configuration of conversations on your account /// </summary> /// <param name="options"> Update Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Update(UpdateConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update the global configuration of conversations on your account /// </summary> /// <param name="options"> Update Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> UpdateAsync(UpdateConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update the global configuration of conversations on your account /// </summary> /// <param name="defaultChatServiceSid"> The SID of the default Conversation Service that every new conversation will /// be associated with. </param> /// <param name="defaultMessagingServiceSid"> The SID of the default Messaging Service that every new conversation will /// be associated with. </param> /// <param name="defaultInactiveTimer"> Default ISO8601 duration when conversation will be switched to `inactive` /// state. </param> /// <param name="defaultClosedTimer"> Default ISO8601 duration when conversation will be switched to `closed` state. /// </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Update(string defaultChatServiceSid = null, string defaultMessagingServiceSid = null, string defaultInactiveTimer = null, string defaultClosedTimer = null, ITwilioRestClient client = null) { var options = new UpdateConfigurationOptions(){DefaultChatServiceSid = defaultChatServiceSid, DefaultMessagingServiceSid = defaultMessagingServiceSid, DefaultInactiveTimer = defaultInactiveTimer, DefaultClosedTimer = defaultClosedTimer}; return Update(options, client); } #if !NET35 /// <summary> /// Update the global configuration of conversations on your account /// </summary> /// <param name="defaultChatServiceSid"> The SID of the default Conversation Service that every new conversation will /// be associated with. </param> /// <param name="defaultMessagingServiceSid"> The SID of the default Messaging Service that every new conversation will /// be associated with. </param> /// <param name="defaultInactiveTimer"> Default ISO8601 duration when conversation will be switched to `inactive` /// state. </param> /// <param name="defaultClosedTimer"> Default ISO8601 duration when conversation will be switched to `closed` state. /// </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> UpdateAsync(string defaultChatServiceSid = null, string defaultMessagingServiceSid = null, string defaultInactiveTimer = null, string defaultClosedTimer = null, ITwilioRestClient client = null) { var options = new UpdateConfigurationOptions(){DefaultChatServiceSid = defaultChatServiceSid, DefaultMessagingServiceSid = defaultMessagingServiceSid, DefaultInactiveTimer = defaultInactiveTimer, DefaultClosedTimer = defaultClosedTimer}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ConfigurationResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ConfigurationResource object represented by the provided JSON </returns> public static ConfigurationResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ConfigurationResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account responsible for this configuration. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the default Conversation Service that every new conversation is associated with. /// </summary> [JsonProperty("default_chat_service_sid")] public string DefaultChatServiceSid { get; private set; } /// <summary> /// The SID of the default Messaging Service that every new conversation is associated with. /// </summary> [JsonProperty("default_messaging_service_sid")] public string DefaultMessagingServiceSid { get; private set; } /// <summary> /// Default ISO8601 duration when conversation will be switched to `inactive` state. /// </summary> [JsonProperty("default_inactive_timer")] public string DefaultInactiveTimer { get; private set; } /// <summary> /// Default ISO8601 duration when conversation will be switched to `closed` state. /// </summary> [JsonProperty("default_closed_timer")] public string DefaultClosedTimer { get; private set; } /// <summary> /// An absolute URL for this global configuration. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// Absolute URLs to access the webhook and default service configurations. /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private ConfigurationResource() { } } }
// // outline -- support for rendering in monop // Some code stolen from updater.cs in monodoc. // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // // (C) 2004 Ben Maurer // // // 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.Reflection; using System.Collections; using System.CodeDom.Compiler; using System.IO; using System.Text; namespace Mono.CSharp { public class Outline { bool declared_only; bool show_private; bool filter_obsolete; IndentedTextWriter o; Type t; public Outline (Type t, TextWriter output, bool declared_only, bool show_private, bool filter_obsolete) { this.t = t; this.o = new IndentedTextWriter (output, "\t"); this.declared_only = declared_only; this.show_private = show_private; this.filter_obsolete = filter_obsolete; } public void OutlineType () { bool first; OutlineAttributes (); o.Write (GetTypeVisibility (t)); if (t.IsClass && !t.IsSubclassOf (typeof (System.MulticastDelegate))) { if (t.IsSealed) o.Write (t.IsAbstract ? " static" : " sealed"); else if (t.IsAbstract) o.Write (" abstract"); } o.Write (" "); o.Write (GetTypeKind (t)); o.Write (" "); Type [] interfaces = (Type []) Comparer.Sort (TypeGetInterfaces (t, declared_only)); Type parent = t.BaseType; if (t.IsSubclassOf (typeof (System.MulticastDelegate))) { MethodInfo method; method = t.GetMethod ("Invoke"); o.Write (FormatType (method.ReturnType)); o.Write (" "); o.Write (GetTypeName (t)); o.Write (" ("); OutlineParams (method.GetParameters ()); o.Write (")"); #if NET_2_0 WriteGenericConstraints (t.GetGenericArguments ()); #endif o.WriteLine (";"); return; } o.Write (GetTypeName (t)); if (((parent != null && parent != typeof (object) && parent != typeof (ValueType)) || interfaces.Length != 0) && ! t.IsEnum) { first = true; o.Write (" : "); if (parent != null && parent != typeof (object) && parent != typeof (ValueType)) { o.Write (FormatType (parent)); first = false; } foreach (Type intf in interfaces) { if (!first) o.Write (", "); first = false; o.Write (FormatType (intf)); } } if (t.IsEnum) { Type underlyingType = System.Enum.GetUnderlyingType (t); if (underlyingType != typeof (int)) o.Write (" : {0}", FormatType (underlyingType)); } #if NET_2_0 WriteGenericConstraints (t.GetGenericArguments ()); #endif o.WriteLine (" {"); o.Indent++; if (t.IsEnum) { bool is_first = true; foreach (FieldInfo fi in t.GetFields (BindingFlags.Public | BindingFlags.Static)) { if (! is_first) o.WriteLine (","); is_first = false; o.Write (fi.Name); } o.WriteLine (); o.Indent--; o.WriteLine ("}"); return; } first = true; foreach (ConstructorInfo ci in t.GetConstructors (DefaultFlags)) { if (! ShowMember (ci)) continue; if (first) o.WriteLine (); first = false; OutlineConstructor (ci); o.WriteLine (); } first = true; foreach (MethodInfo m in Comparer.Sort (t.GetMethods (DefaultFlags))) { if (! ShowMember (m)) continue; if ((m.Attributes & MethodAttributes.SpecialName) != 0) continue; if (first) o.WriteLine (); first = false; OutlineMethod (m); o.WriteLine (); } first = true; foreach (MethodInfo m in t.GetMethods (DefaultFlags)) { if (! ShowMember (m)) continue; if ((m.Attributes & MethodAttributes.SpecialName) == 0) continue; if (!(m.Name.StartsWith ("op_"))) continue; if (first) o.WriteLine (); first = false; OutlineOperator (m); o.WriteLine (); } first = true; foreach (PropertyInfo pi in Comparer.Sort (t.GetProperties (DefaultFlags))) { if (! ((pi.CanRead && ShowMember (pi.GetGetMethod (true))) || (pi.CanWrite && ShowMember (pi.GetSetMethod (true))))) continue; if (first) o.WriteLine (); first = false; OutlineProperty (pi); o.WriteLine (); } first = true; foreach (FieldInfo fi in t.GetFields (DefaultFlags)) { if (! ShowMember (fi)) continue; if (first) o.WriteLine (); first = false; OutlineField (fi); o.WriteLine (); } first = true; foreach (EventInfo ei in Comparer.Sort (t.GetEvents (DefaultFlags))) { if (! ShowMember (ei.GetAddMethod (true))) continue; if (first) o.WriteLine (); first = false; OutlineEvent (ei); o.WriteLine (); } first = true; foreach (Type ntype in Comparer.Sort (t.GetNestedTypes (DefaultFlags))) { if (! ShowMember (ntype)) continue; if (first) o.WriteLine (); first = false; new Outline (ntype, o, declared_only, show_private, filter_obsolete).OutlineType (); } o.Indent--; o.WriteLine ("}"); } BindingFlags DefaultFlags { get { BindingFlags f = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; if (declared_only) f |= BindingFlags.DeclaredOnly; return f; } } // FIXME: add other interesting attributes? void OutlineAttributes () { //if (t.IsSerializable) // o.WriteLine ("[Serializable]"); if (t.IsDefined (typeof (System.FlagsAttribute), true)) o.WriteLine ("[Flags]"); if (t.IsDefined (typeof (System.ObsoleteAttribute), true)) o.WriteLine ("[Obsolete]"); } void OutlineEvent (EventInfo ei) { MethodBase accessor = ei.GetAddMethod (true); o.Write (GetMethodVisibility (accessor)); o.Write ("event "); o.Write (FormatType (ei.EventHandlerType)); o.Write (" "); o.Write (ei.Name); o.Write (";"); } void OutlineConstructor (ConstructorInfo ci) { o.Write (GetMethodVisibility (ci)); o.Write (RemoveGenericArity (t.Name)); o.Write (" ("); OutlineParams (ci.GetParameters ()); o.Write (");"); } void OutlineProperty (PropertyInfo pi) { ParameterInfo [] idxp = pi.GetIndexParameters (); MethodBase g = pi.GetGetMethod (true); MethodBase s = pi.GetSetMethod (true); MethodBase accessor = g != null ? g : s; if (pi.CanRead && pi.CanWrite) { // Get the more accessible accessor if ((g.Attributes & MethodAttributes.MemberAccessMask) != (s.Attributes & MethodAttributes.MemberAccessMask)) { if (g.IsPublic) accessor = g; else if (s.IsPublic) accessor = s; else if (g.IsFamilyOrAssembly) accessor = g; else if (s.IsFamilyOrAssembly) accessor = s; else if (g.IsAssembly || g.IsFamily) accessor = g; else if (s.IsAssembly || s.IsFamily) accessor = s; } } o.Write (GetMethodVisibility (accessor)); o.Write (GetMethodModifiers (accessor)); o.Write (FormatType (pi.PropertyType)); o.Write (" "); if (idxp.Length == 0) o.Write (pi.Name); else { o.Write ("this ["); OutlineParams (idxp); o.Write ("]"); } o.WriteLine (" {"); o.Indent ++; if (g != null && ShowMember (g)) { if ((g.Attributes & MethodAttributes.MemberAccessMask) != (accessor.Attributes & MethodAttributes.MemberAccessMask)) o.Write (GetMethodVisibility (g)); o.WriteLine ("get;"); } if (s != null && ShowMember (s)) { if ((s.Attributes & MethodAttributes.MemberAccessMask) != (accessor.Attributes & MethodAttributes.MemberAccessMask)) o.Write (GetMethodVisibility (s)); o.WriteLine ("set;"); } o.Indent --; o.Write ("}"); } void OutlineMethod (MethodInfo mi) { if (MethodIsExplicitIfaceImpl (mi)) { o.Write (FormatType (mi.ReturnType)); o.Write (" "); // MSFT has no way to get the method that we are overriding // from the interface. this would allow us to pretty print // the type name (and be more correct if there compiler // were to do some strange naming thing). } else { o.Write (GetMethodVisibility (mi)); o.Write (GetMethodModifiers (mi)); o.Write (FormatType (mi.ReturnType)); o.Write (" "); } o.Write (mi.Name); #if NET_2_0 o.Write (FormatGenericParams (mi.GetGenericArguments ())); #endif o.Write (" ("); OutlineParams (mi.GetParameters ()); o.Write (")"); #if NET_2_0 WriteGenericConstraints (mi.GetGenericArguments ()); #endif o.Write (";"); } void OutlineOperator (MethodInfo mi) { o.Write (GetMethodVisibility (mi)); o.Write (GetMethodModifiers (mi)); if (mi.Name == "op_Explicit" || mi.Name == "op_Implicit") { o.Write (mi.Name.Substring (3).ToLower ()); o.Write (" operator "); o.Write (FormatType (mi.ReturnType)); } else { o.Write (FormatType (mi.ReturnType)); o.Write (" operator "); o.Write (OperatorFromName (mi.Name)); } o.Write (" ("); OutlineParams (mi.GetParameters ()); o.Write (");"); } void OutlineParams (ParameterInfo [] pi) { int i = 0; foreach (ParameterInfo p in pi) { if (p.ParameterType.IsByRef) { o.Write (p.IsOut ? "out " : "ref "); o.Write (FormatType (p.ParameterType.GetElementType ())); } else if (p.IsDefined (typeof (ParamArrayAttribute), false)) { o.Write ("params "); o.Write (FormatType (p.ParameterType)); } else { o.Write (FormatType (p.ParameterType)); } o.Write (" "); o.Write (p.Name); if (i + 1 < pi.Length) o.Write (", "); i++; } } void OutlineField (FieldInfo fi) { if (fi.IsPublic) o.Write ("public "); if (fi.IsFamily) o.Write ("protected "); if (fi.IsPrivate) o.Write ("private "); if (fi.IsAssembly) o.Write ("internal "); if (fi.IsLiteral) o.Write ("const "); else if (fi.IsStatic) o.Write ("static "); if (fi.IsInitOnly) o.Write ("readonly "); o.Write (FormatType (fi.FieldType)); o.Write (" "); o.Write (fi.Name); if (fi.IsLiteral) { object v = fi.GetValue (this); // TODO: Escape values here o.Write (" = "); if (v is char) o.Write ("'{0}'", v); else if (v is string) o.Write ("\"{0}\"", v); else o.Write (fi.GetValue (this)); } o.Write (";"); } static string GetMethodVisibility (MethodBase m) { // itnerfaces have no modifiers here if (m.DeclaringType.IsInterface) return ""; if (m.IsPublic) return "public "; if (m.IsFamily) return "protected "; if (m.IsPrivate) return "private "; if (m.IsAssembly) return "internal "; return null; } static string GetMethodModifiers (MethodBase method) { if (method.IsStatic) return "static "; if (method.IsFinal) { // This will happen if you have // class X : IA { // public void A () {} // static void Main () {} // } // interface IA { // void A (); // } // // A needs to be virtual (the CLR requires // methods implementing an iface be virtual), // but can not be inherited. It also can not // be inherited. In C# this is represented // with no special modifiers if (method.IsVirtual) return null; return "sealed "; } // all interface methods are "virtual" but we don't say that in c# if (method.IsVirtual && !method.DeclaringType.IsInterface) { if (method.IsAbstract) return "abstract "; return ((method.Attributes & MethodAttributes.NewSlot) != 0) ? "virtual " : "override "; } return null; } static string GetTypeKind (Type t) { if (t.IsEnum) return "enum"; if (t.IsClass) { if (t.IsSubclassOf (typeof (System.MulticastDelegate))) return "delegate"; else return "class"; } if (t.IsInterface) return "interface"; if (t.IsValueType) return "struct"; return "class"; } static string GetTypeVisibility (Type t) { switch (t.Attributes & TypeAttributes.VisibilityMask){ case TypeAttributes.Public: case TypeAttributes.NestedPublic: return "public"; case TypeAttributes.NestedFamily: case TypeAttributes.NestedFamANDAssem: case TypeAttributes.NestedFamORAssem: return "protected"; default: return "internal"; } } #if NET_2_0 string FormatGenericParams (Type [] args) { StringBuilder sb = new StringBuilder (); if (args.Length == 0) return ""; sb.Append ("<"); for (int i = 0; i < args.Length; i++) { if (i > 0) sb.Append (","); sb.Append (FormatType (args [i])); } sb.Append (">"); return sb.ToString (); } #endif // TODO: fine tune this so that our output is less verbose. We need to figure // out a way to do this while not making things confusing. string FormatType (Type t) { if (t == null) return ""; string type = GetFullName (t); if (type == null) return t.ToString (); if (!type.StartsWith ("System.")) { if (t.Namespace == this.t.Namespace) return t.Name; return type; } if (t.HasElementType) { Type et = t.GetElementType (); if (t.IsArray) return FormatType (et) + " []"; if (t.IsPointer) return FormatType (et) + " *"; if (t.IsByRef) return "ref " + FormatType (et); } switch (type) { case "System.Byte": return "byte"; case "System.SByte": return "sbyte"; case "System.Int16": return "short"; case "System.Int32": return "int"; case "System.Int64": return "long"; case "System.UInt16": return "ushort"; case "System.UInt32": return "uint"; case "System.UInt64": return "ulong"; case "System.Single": return "float"; case "System.Double": return "double"; case "System.Decimal": return "decimal"; case "System.Boolean": return "bool"; case "System.Char": return "char"; case "System.String": return "string"; case "System.Object": return "object"; case "System.Void": return "void"; } if (type.LastIndexOf(".") == 6) return type.Substring(7); // // If the namespace of the type is the namespace of what // we are printing (or is a member of one if its children // don't print it. This basically means that in C# we would // automatically get the namespace imported by virtue of the // namespace {} block. // if (this.t.Namespace.StartsWith (t.Namespace + ".") || t.Namespace == this.t.Namespace) return type.Substring (t.Namespace.Length + 1); return type; } public static string RemoveGenericArity (string name) { int start = 0; StringBuilder sb = new StringBuilder (); while (start < name.Length) { int pos = name.IndexOf ('`', start); if (pos < 0) { sb.Append (name.Substring (start)); break; } sb.Append (name.Substring (start, pos-start)); pos++; while ((pos < name.Length) && Char.IsNumber (name [pos])) pos++; start = pos; } return sb.ToString (); } string GetTypeName (Type t) { StringBuilder sb = new StringBuilder (); GetTypeName (sb, t); return sb.ToString (); } void GetTypeName (StringBuilder sb, Type t) { sb.Append (RemoveGenericArity (t.Name)); #if NET_2_0 sb.Append (FormatGenericParams (t.GetGenericArguments ())); #endif } string GetFullName (Type t) { StringBuilder sb = new StringBuilder (); GetFullName_recursed (sb, t, false); return sb.ToString (); } void GetFullName_recursed (StringBuilder sb, Type t, bool recursed) { #if NET_2_0 if (t.IsGenericParameter) { sb.Append (t.Name); return; } #endif if (t.DeclaringType != null) { GetFullName_recursed (sb, t.DeclaringType, true); sb.Append ("."); } if (!recursed) { string ns = t.Namespace; if ((ns != null) && (ns != "")) { sb.Append (ns); sb.Append ("."); } } GetTypeName (sb, t); } #if NET_2_0 void WriteGenericConstraints (Type [] args) { foreach (Type t in args) { bool first = true; Type[] ifaces = TypeGetInterfaces (t, true); GenericParameterAttributes attrs = t.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; GenericParameterAttributes [] interesting = { GenericParameterAttributes.ReferenceTypeConstraint, GenericParameterAttributes.NotNullableValueTypeConstraint, GenericParameterAttributes.DefaultConstructorConstraint }; if (t.BaseType != typeof (object) || ifaces.Length != 0 || attrs != 0) { o.Write (" where "); o.Write (FormatType (t)); o.Write (" : "); } if (t.BaseType != typeof (object)) { o.Write (FormatType (t.BaseType)); first = false; } foreach (Type iface in ifaces) { if (!first) o.Write (", "); first = false; o.Write (FormatType (iface)); } foreach (GenericParameterAttributes a in interesting) { if ((attrs & a) == 0) continue; if (!first) o.Write (", "); first = false; switch (a) { case GenericParameterAttributes.ReferenceTypeConstraint: o.Write ("class"); break; case GenericParameterAttributes.NotNullableValueTypeConstraint: o.Write ("struct"); break; case GenericParameterAttributes.DefaultConstructorConstraint: o.Write ("new ()"); break; } } } } #endif string OperatorFromName (string name) { switch (name) { case "op_UnaryPlus": return "+"; case "op_UnaryNegation": return "-"; case "op_LogicalNot": return "!"; case "op_OnesComplement": return "~"; case "op_Increment": return "++"; case "op_Decrement": return "--"; case "op_True": return "true"; case "op_False": return "false"; case "op_Addition": return "+"; case "op_Subtraction": return "-"; case "op_Multiply": return "*"; case "op_Division": return "/"; case "op_Modulus": return "%"; case "op_BitwiseAnd": return "&"; case "op_BitwiseOr": return "|"; case "op_ExclusiveOr": return "^"; case "op_LeftShift": return "<<"; case "op_RightShift": return ">>"; case "op_Equality": return "=="; case "op_Inequality": return "!="; case "op_GreaterThan": return ">"; case "op_LessThan": return "<"; case "op_GreaterThanOrEqual": return ">="; case "op_LessThanOrEqual": return "<="; default: return name; } } bool MethodIsExplicitIfaceImpl (MethodBase mb) { if (!(mb.IsFinal && mb.IsVirtual && mb.IsPrivate)) return false; // UGH msft has no way to get the info about what method is // getting overriden. Another reason to use cecil :-) // //MethodInfo mi = mb as MethodInfo; //if (mi == null) // return false; // //Console.WriteLine (mi.GetBaseDefinition ().DeclaringType); //return mi.GetBaseDefinition ().DeclaringType.IsInterface; // So, we guess that virtual final private methods only come // from ifaces :-) return true; } bool ShowMember (MemberInfo mi) { if (mi.MemberType == MemberTypes.Constructor && ((MethodBase) mi).IsStatic) return false; if (show_private) return true; if (filter_obsolete && mi.IsDefined (typeof (ObsoleteAttribute), false)) return false; switch (mi.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: MethodBase mb = mi as MethodBase; if (mb.IsFamily || mb.IsPublic || mb.IsFamilyOrAssembly) return true; if (MethodIsExplicitIfaceImpl (mb)) return true; return false; case MemberTypes.Field: FieldInfo fi = mi as FieldInfo; if (fi.IsFamily || fi.IsPublic || fi.IsFamilyOrAssembly) return true; return false; case MemberTypes.NestedType: case MemberTypes.TypeInfo: Type t = mi as Type; switch (t.Attributes & TypeAttributes.VisibilityMask){ case TypeAttributes.Public: case TypeAttributes.NestedPublic: case TypeAttributes.NestedFamily: case TypeAttributes.NestedFamORAssem: return true; } return false; } // What am I !!! return true; } static Type [] TypeGetInterfaces (Type t, bool declonly) { if (t.IsGenericParameter) return new Type [0]; Type [] ifaces = t.GetInterfaces (); if (! declonly) return ifaces; // Handle Object. Also, optimize for no interfaces if (t.BaseType == null || ifaces.Length == 0) return ifaces; System.Collections.Generic.List<Type> ar = new System.Collections.Generic.List<Type> (); foreach (Type i in ifaces) if (! i.IsAssignableFrom (t.BaseType)) ar.Add (i); return ar.ToArray (); } } public class Comparer : IComparer { delegate int ComparerFunc (object a, object b); ComparerFunc cmp; Comparer (ComparerFunc f) { this.cmp = f; } public int Compare (object a, object b) { return cmp (a, b); } static int CompareType (object a, object b) { Type type1 = (Type) a; Type type2 = (Type) b; if (type1.IsSubclassOf (typeof (System.MulticastDelegate)) != type2.IsSubclassOf (typeof (System.MulticastDelegate))) return (type1.IsSubclassOf (typeof (System.MulticastDelegate)))? -1:1; return string.Compare (type1.Name, type2.Name); } // static Comparer TypeComparer = new Comparer (new ComparerFunc (CompareType)); // static Type [] Sort (Type [] types) // { // Array.Sort (types, TypeComparer); // return types; // } static int CompareMemberInfo (object a, object b) { return string.Compare (((MemberInfo) a).Name, ((MemberInfo) b).Name); } static Comparer MemberInfoComparer = new Comparer (new ComparerFunc (CompareMemberInfo)); public static MemberInfo [] Sort (MemberInfo [] inf) { Array.Sort (inf, MemberInfoComparer); return inf; } static int CompareMethodBase (object a, object b) { MethodBase aa = (MethodBase) a, bb = (MethodBase) b; if (aa.IsStatic == bb.IsStatic) { int c = CompareMemberInfo (a, b); if (c != 0) return c; ParameterInfo [] ap, bp; // // Sort overloads by the names of their types // put methods with fewer params first. // ap = aa.GetParameters (); bp = bb.GetParameters (); int n = System.Math.Min (ap.Length, bp.Length); for (int i = 0; i < n; i ++) if ((c = CompareType (ap [i].ParameterType, bp [i].ParameterType)) != 0) return c; return ap.Length.CompareTo (bp.Length); } if (aa.IsStatic) return -1; return 1; } static Comparer MethodBaseComparer = new Comparer (new ComparerFunc (CompareMethodBase)); public static MethodBase [] Sort (MethodBase [] inf) { Array.Sort (inf, MethodBaseComparer); return inf; } static int ComparePropertyInfo (object a, object b) { PropertyInfo aa = (PropertyInfo) a, bb = (PropertyInfo) b; bool astatic = (aa.CanRead ? aa.GetGetMethod (true) : aa.GetSetMethod (true)).IsStatic; bool bstatic = (bb.CanRead ? bb.GetGetMethod (true) : bb.GetSetMethod (true)).IsStatic; if (astatic == bstatic) return CompareMemberInfo (a, b); if (astatic) return -1; return 1; } static Comparer PropertyInfoComparer = new Comparer (new ComparerFunc (ComparePropertyInfo)); public static PropertyInfo [] Sort (PropertyInfo [] inf) { Array.Sort (inf, PropertyInfoComparer); return inf; } static int CompareEventInfo (object a, object b) { EventInfo aa = (EventInfo) a, bb = (EventInfo) b; bool astatic = aa.GetAddMethod (true).IsStatic; bool bstatic = bb.GetAddMethod (true).IsStatic; if (astatic == bstatic) return CompareMemberInfo (a, b); if (astatic) return -1; return 1; } static Comparer EventInfoComparer = new Comparer (new ComparerFunc (CompareEventInfo)); public static EventInfo [] Sort (EventInfo [] inf) { Array.Sort (inf, EventInfoComparer); return inf; } } }
using System; using System.Numerics; namespace OpenKh.Engine { public class Camera { private bool _isEventMode; private float _fov; private float _aspectRatio; private Vector3 _cameraPosition; private Vector3 _cameraLookAt; private Vector3 _cameraLookAtX; private Vector3 _cameraLookAtY; private Vector3 _cameraLookAtZ; private Vector3 _cameraUp; private Matrix4x4 _projection; private Matrix4x4 _world; private bool _isProjectionInvalidated; private bool _isWorldInvalidated; private Vector3 _cameraYpr; public bool IsEventMode { get => _isEventMode; set { if (_isEventMode == value) return; _isEventMode = value; InvalidateProjection(); } } public float FieldOfView { get => _fov; set { if (_fov == value) return; _fov = value; InvalidateProjection(); } } public float AspectRatio { get => _aspectRatio; set { if (_aspectRatio == value) return; _aspectRatio = value; InvalidateProjection(); } } public Vector3 CameraPosition { get => _cameraPosition; set { _cameraPosition = value; CameraLookAt = CameraPosition + CameraLookAtX; InvalidateWorld(); } } public Vector3 CameraLookAt { get => _cameraLookAt; set { _cameraLookAt = value; InvalidateWorld(); } } public Vector3 CameraLookAtX { get => _cameraLookAtX; set { _cameraLookAtX = value; CameraLookAt = CameraPosition + CameraLookAtX; InvalidateWorld(); } } public Vector3 CameraLookAtY { get => _cameraLookAtY; set { _cameraLookAtY = value; InvalidateWorld(); } } public Vector3 CameraLookAtZ { get => _cameraLookAtZ; set { _cameraLookAtZ = value; InvalidateWorld(); } } public Vector3 CameraUp { get => _cameraUp; set { _cameraUp = value; InvalidateWorld(); } } public Vector3 CameraRotationYawPitchRoll { get => _cameraYpr; set { _cameraYpr = value; var matrix = Matrix4x4.CreateFromYawPitchRoll( (float)(value.X * Math.PI / 180.0), (float)(value.Y * Math.PI / 180.0), (float)(value.Z * Math.PI / 180.0)); CameraLookAtX = Vector3.Transform(new Vector3(1, 0, 0), matrix); CameraLookAtY = Vector3.Transform(new Vector3(0, 0, 1), matrix); CameraLookAtZ = Vector3.Transform(new Vector3(0, 1, 0), matrix); } } public Matrix4x4 Projection { get { if (_isProjectionInvalidated) CalculateProjection(); return _projection; } } public Matrix4x4 World { get { if (_isWorldInvalidated) CalculateWorld(); return _world; } } public Camera() { FieldOfView = 1.5f; AspectRatio = 640f / 480f; CameraUp = new Vector3(0, 1, 0); CameraRotationYawPitchRoll = new Vector3(-90, 0, 10); } private void InvalidateProjection() => _isProjectionInvalidated = true; private void ValidateProjection() => _isProjectionInvalidated = false; private void InvalidateWorld() => _isWorldInvalidated = true; private void ValidateWorld() => _isWorldInvalidated = false; private void CalculateProjection() { const float NearClipPlane = 1f; const float FarClipPlane = 4000000f; if (!_isEventMode) { const double ReferenceWidth = 640f; const double ReferenceHeight = 480f; var srcz = ReferenceWidth / 2.0 / Math.Tan(_fov / 2.0); var actualAspectRatio = 1.0 / _aspectRatio / (ReferenceHeight / ReferenceWidth); var width = ReferenceWidth / (srcz * actualAspectRatio); var height = ReferenceHeight / srcz; _projection = Matrix4x4.CreatePerspective((float)width, (float)height, NearClipPlane, FarClipPlane); } else _projection = Matrix4x4.CreatePerspectiveFieldOfView(_fov, _aspectRatio, NearClipPlane, FarClipPlane); ValidateProjection(); } private void CalculateWorld() { _world = Matrix4x4.CreateLookAt( new Vector3(-CameraPosition.X, CameraPosition.Y, CameraPosition.Z), new Vector3(-CameraLookAt.X, CameraLookAt.Y, CameraLookAt.Z), CameraUp); ValidateWorld(); } } }
//------------------------------------------------------------------------------ // <copyright file="XsltFunctions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ using System.IO; using System.Text; using System.Reflection; using System.Diagnostics; using System.ComponentModel; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Xml.Schema; using System.Xml.XPath; using System.Xml.Xsl.Xslt; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System.Xml.Xsl.Runtime { using Res = System.Xml.Utils.Res; [EditorBrowsable(EditorBrowsableState.Never)] public static class XsltFunctions { private static readonly CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo; //------------------------------------------------ // Xslt/XPath functions //------------------------------------------------ public static bool StartsWith(string s1, string s2) { //return collation.IsPrefix(s1, s2); return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0; } public static bool Contains(string s1, string s2) { //return collation.IndexOf(s1, s2) >= 0; return compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0; } public static string SubstringBefore(string s1, string s2) { if (s2.Length == 0) { return s2; } //int idx = collation.IndexOf(s1, s2); int idx = compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 1) ? string.Empty : s1.Substring(0, idx); } public static string SubstringAfter(string s1, string s2) { if (s2.Length == 0) { return s1; } //int idx = collation.IndexOf(s1, s2); int idx = compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal); return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length); } public static string Substring(string value, double startIndex) { startIndex = Round(startIndex); if (startIndex <= 0) { return value; } else if (startIndex <= value.Length) { return value.Substring((int)startIndex - 1); } else { Debug.Assert(value.Length < startIndex || Double.IsNaN(startIndex)); return string.Empty; } } public static string Substring(string value, double startIndex, double length) { startIndex = Round(startIndex) - 1; // start index if (startIndex >= value.Length) { return string.Empty; } double endIndex = startIndex + Round(length); // end index startIndex = (startIndex <= 0) ? 0 : startIndex; if (startIndex < endIndex) { if (endIndex > value.Length) { endIndex = value.Length; } Debug.Assert(0 <= startIndex && startIndex <= endIndex && endIndex <= value.Length); return value.Substring((int)startIndex, (int)(endIndex - startIndex)); } else { Debug.Assert(endIndex <= startIndex || Double.IsNaN(endIndex)); return string.Empty; } } public static string NormalizeSpace(string value) { XmlCharType xmlCharType = XmlCharType.Instance; StringBuilder sb = null; int idx, idxStart = 0, idxSpace = 0; for (idx = 0; idx < value.Length; idx++) { if (xmlCharType.IsWhiteSpace(value[idx])) { if (idx == idxStart) { // Previous character was a whitespace character, so discard this character idxStart++; } else if (value[idx] != ' ' || idxSpace == idx) { // Space was previous character or this is a non-space character if (sb == null) sb = new StringBuilder(value.Length); else sb.Append(' '); // Copy non-space characters into string builder if (idxSpace == idx) sb.Append(value, idxStart, idx - idxStart - 1); else sb.Append(value, idxStart, idx - idxStart); idxStart = idx + 1; } else { // Single whitespace character doesn't cause normalization, but mark its position idxSpace = idx + 1; } } } if (sb == null) { // Check for string that is entirely composed of whitespace if (idxStart == idx) return string.Empty; // If string does not end with a space, then it must already be normalized if (idxStart == 0 && idxSpace != idx) return value; sb = new StringBuilder(value.Length); } else if (idx != idxStart) { sb.Append(' '); } // Copy non-space characters into string builder if (idxSpace == idx) sb.Append(value, idxStart, idx - idxStart - 1); else sb.Append(value, idxStart, idx - idxStart); return sb.ToString(); } public static string Translate(string arg, string mapString, string transString) { if (mapString.Length == 0) { return arg; } StringBuilder sb = new StringBuilder(arg.Length); for (int i = 0; i < arg.Length; i++) { int index = mapString.IndexOf(arg[i]); if (index < 0) { // Keep the character sb.Append(arg[i]); } else if (index < transString.Length) { // Replace the character sb.Append(transString[index]); } else { // Remove the character } } return sb.ToString(); } public static bool Lang(string value, XPathNavigator context) { string lang = context.XmlLang; if (!lang.StartsWith(value, StringComparison.OrdinalIgnoreCase)) { return false; } return (lang.Length == value.Length || lang[value.Length] == '-'); } // Round value using XPath rounding rules (round towards positive infinity). // Values between -0.5 and -0.0 are rounded to -0.0 (negative zero). public static double Round(double value) { double temp = Math.Round(value); return (value - temp == 0.5) ? temp + 1 : temp; } // Spec: http://www.w3.org/TR/xslt.html#function-system-property public static XPathItem SystemProperty(XmlQualifiedName name) { if (name.Namespace == XmlReservedNs.NsXslt) { // "xsl:version" must return 1.0 as a number, see http://www.w3.org/TR/xslt20/#incompatility-without-schema switch (name.Name) { case "version" : return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), 1.0); case "vendor" : return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), "Microsoft"); case "vendor-url": return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), "http://www.microsoft.com"); } } else if (name.Namespace == XmlReservedNs.NsMsxsl && name.Name == "version") { // msxsl:version return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), typeof(XsltLibrary).Assembly.ImageRuntimeVersion); } // If the property name is not recognized, return the empty string return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), string.Empty); } //------------------------------------------------ // Navigator functions //------------------------------------------------ public static string BaseUri(XPathNavigator navigator) { return navigator.BaseURI; } public static string OuterXml(XPathNavigator navigator) { RtfNavigator rtf = navigator as RtfNavigator; if (rtf == null) { return navigator.OuterXml; } StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.CheckCharacters = false; XmlWriter xw = XmlWriter.Create(sb, settings); rtf.CopyToWriter(xw); xw.Close(); return sb.ToString(); } //------------------------------------------------ // EXslt Functions //------------------------------------------------ public static string EXslObjectType(IList<XPathItem> value) { if (value.Count != 1) { XsltLibrary.CheckXsltValue(value); return "node-set"; } XPathItem item = value[0]; if (item is RtfNavigator) { return "RTF"; } else if (item.IsNode) { Debug.Assert(item is XPathNavigator); return "node-set"; } object o = item.TypedValue; if (o is string) { return "string"; } else if (o is double) { return "number"; } else if (o is bool) { return "boolean"; } else { Debug.Fail("Unexpected type: " + o.GetType().ToString()); return "external"; } } //------------------------------------------------ // Msxml Extension Functions //------------------------------------------------ public static double MSNumber(IList<XPathItem> value) { XsltLibrary.CheckXsltValue(value); if (value.Count == 0) { return Double.NaN; } XPathItem item = value[0]; string stringValue; if (item.IsNode) { stringValue = item.Value; } else { Type itemType = item.ValueType; if (itemType == XsltConvert.StringType) { stringValue = item.Value; } else if (itemType == XsltConvert.DoubleType) { return item.ValueAsDouble; } else { Debug.Assert(itemType == XsltConvert.BooleanType, "Unexpected type of atomic value " + itemType.ToString()); return item.ValueAsBoolean ? 1d : 0d; } } Debug.Assert(stringValue != null); double d; if (XmlConvert.TryToDouble(stringValue, out d) != null) { d = double.NaN; } return d; } // CharSet.Auto is needed to work on Windows 98 and Windows Me [DllImport("kernel32.dll", CharSet=CharSet.Auto, BestFitMapping=false)] // SxS: Time formatting does not expose any system resource hence Resource Exposure scope is None. [ResourceExposure(ResourceScope.None)] static extern int GetDateFormat(int locale, uint dwFlags, ref SystemTime sysTime, string format, StringBuilder sb, int sbSize); [DllImport("kernel32.dll", CharSet=CharSet.Auto, BestFitMapping=false)] // SxS: Time formatting does not expose any system resource hence Resource Exposure scope is None. [ResourceExposure(ResourceScope.None)] static extern int GetTimeFormat(int locale, uint dwFlags, ref SystemTime sysTime, string format, StringBuilder sb, int sbSize); [StructLayout(LayoutKind.Sequential)] private struct SystemTime { [MarshalAs(UnmanagedType.U2)] public ushort Year; [MarshalAs(UnmanagedType.U2)] public ushort Month; [MarshalAs(UnmanagedType.U2)] public ushort DayOfWeek; [MarshalAs(UnmanagedType.U2)] public ushort Day; [MarshalAs(UnmanagedType.U2)] public ushort Hour; [MarshalAs(UnmanagedType.U2)] public ushort Minute; [MarshalAs(UnmanagedType.U2)] public ushort Second; [MarshalAs(UnmanagedType.U2)] public ushort Milliseconds; public SystemTime(DateTime dateTime) { this.Year = (ushort)dateTime.Year; this.Month = (ushort)dateTime.Month; this.DayOfWeek = (ushort)dateTime.DayOfWeek; this.Day = (ushort)dateTime.Day; this.Hour = (ushort)dateTime.Hour; this.Minute = (ushort)dateTime.Minute; this.Second = (ushort)dateTime.Second; this.Milliseconds = (ushort)dateTime.Millisecond; } } // string ms:format-date(string datetime[, string format[, string language]]) // string ms:format-time(string datetime[, string format[, string language]]) // // Format xsd:dateTime as a date/time string for a given language using a given format string. // * Datetime contains a lexical representation of xsd:dateTime. If datetime is not valid, the // empty string is returned. // * Format specifies a format string in the same way as for GetDateFormat/GetTimeFormat system // functions. If format is the empty string or not passed, the default date/time format for the // given culture is used. // * Language specifies a culture used for formatting. If language is the empty string or not // passed, the current culture is used. If language is not recognized, a runtime error happens. public static string MSFormatDateTime(string dateTime, string format, string lang, bool isDate) { try { int locale = GetCultureInfo(lang).LCID; XsdDateTime xdt; if (! XsdDateTime.TryParse(dateTime, XsdDateTimeFlags.AllXsd | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrTimeNoTz, out xdt)) { return string.Empty; } SystemTime st = new SystemTime(xdt.ToZulu()); StringBuilder sb = new StringBuilder(format.Length + 16); // If format is the empty string or not specified, use the default format for the given locale if (format.Length == 0) { format = null; } if (isDate) { int res = GetDateFormat(locale, 0, ref st, format, sb, sb.Capacity); if (res == 0) { res = GetDateFormat(locale, 0, ref st, format, sb, 0); if (res != 0) { sb = new StringBuilder(res); res = GetDateFormat(locale, 0, ref st, format, sb, sb.Capacity); } } } else { int res = GetTimeFormat(locale, 0, ref st, format, sb, sb.Capacity); if (res == 0) { res = GetTimeFormat(locale, 0, ref st, format, sb, 0); if (res != 0) { sb = new StringBuilder(res); res = GetTimeFormat(locale, 0, ref st, format, sb, sb.Capacity); } } } return sb.ToString(); } catch (ArgumentException) { // Operations with DateTime can throw this exception eventualy return string.Empty; } } public static double MSStringCompare(string s1, string s2, string lang, string options) { CultureInfo cultinfo = GetCultureInfo(lang); CompareOptions opts = CompareOptions.None; bool upperFirst = false; for (int idx = 0; idx < options.Length; idx++) { switch (options[idx]) { case 'i': opts = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth; break; case 'u': upperFirst = true; break; default: upperFirst = true; opts = CompareOptions.IgnoreCase; break; } } if (upperFirst) { if (opts != CompareOptions.None) { throw new XslTransformException(Res.Xslt_InvalidCompareOption, options); } opts = CompareOptions.IgnoreCase; } int result = cultinfo.CompareInfo.Compare(s1, s2, opts); if (upperFirst && result == 0) { result = -cultinfo.CompareInfo.Compare(s1, s2, CompareOptions.None); } return result; } public static string MSUtc(string dateTime) { XsdDateTime xdt; DateTime dt; try { if (! XsdDateTime.TryParse(dateTime, XsdDateTimeFlags.AllXsd | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrTimeNoTz, out xdt)) { return string.Empty; } dt = xdt.ToZulu(); } catch (ArgumentException) { // Operations with DateTime can throw this exception eventualy return string.Empty; } char[] text = "----------T00:00:00.000".ToCharArray(); // "YYYY-MM-DDTHH:NN:SS.III" // 0 1 2 // 01234567890123456789012 switch (xdt.TypeCode) { case XmlTypeCode.DateTime: PrintDate(text, dt); PrintTime(text, dt); break; case XmlTypeCode.Time: PrintTime(text, dt); break; case XmlTypeCode.Date: PrintDate(text, dt); break; case XmlTypeCode.GYearMonth: PrintYear( text, dt.Year); ShortToCharArray(text, 5, dt.Month); break; case XmlTypeCode.GYear: PrintYear(text, dt.Year); break; case XmlTypeCode.GMonthDay: ShortToCharArray(text, 5, dt.Month); ShortToCharArray(text, 8, dt.Day ); break; case XmlTypeCode.GDay: ShortToCharArray(text, 8, dt.Day ); break; case XmlTypeCode.GMonth: ShortToCharArray(text, 5, dt.Month); break; } return new String(text); } public static string MSLocalName(string name) { int colonOffset; int len = ValidateNames.ParseQName(name, 0, out colonOffset); if (len != name.Length) { return string.Empty; } if (colonOffset == 0) { return name; } else { return name.Substring(colonOffset + 1); } } public static string MSNamespaceUri(string name, XPathNavigator currentNode) { int colonOffset; int len = ValidateNames.ParseQName(name, 0, out colonOffset); if (len != name.Length) { return string.Empty; } string prefix = name.Substring(0, colonOffset); if (prefix == "xmlns") { return string.Empty; } string ns = currentNode.LookupNamespace(prefix); if (ns != null) { return ns; } if (prefix == "xml") { return XmlReservedNs.NsXml; } return string.Empty; } //------------------------------------------------ // Helper Functions //------------------------------------------------ private static CultureInfo GetCultureInfo(string lang) { Debug.Assert(lang != null); if (lang.Length == 0) { return CultureInfo.CurrentCulture; } else { try { return new CultureInfo(lang); } catch (System.ArgumentException) { throw new XslTransformException(Res.Xslt_InvalidLanguage, lang); } } } private static void PrintDate(char[] text, DateTime dt) { PrintYear(text, dt.Year); ShortToCharArray(text, 5, dt.Month); ShortToCharArray(text, 8, dt.Day ); } private static void PrintTime(char[] text, DateTime dt) { ShortToCharArray(text, 11, dt.Hour ); ShortToCharArray(text, 14, dt.Minute); ShortToCharArray(text, 17, dt.Second); PrintMsec(text, dt.Millisecond); } private static void PrintYear(char[] text, int value) { text[0] = (char) ((value / 1000) % 10 + '0'); text[1] = (char) ((value / 100 ) % 10 + '0'); text[2] = (char) ((value / 10 ) % 10 + '0'); text[3] = (char) ((value / 1 ) % 10 + '0'); } private static void PrintMsec(char[] text, int value) { if (value == 0) { return; } text[20] = (char) ((value / 100) % 10 + '0'); text[21] = (char) ((value / 10 ) % 10 + '0'); text[22] = (char) ((value / 1 ) % 10 + '0'); } private static void ShortToCharArray(char[] text, int start, int value) { text[start ] = (char)(value / 10 + '0'); text[start + 1] = (char)(value % 10 + '0'); } } }
// 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.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Rules for the Hijri calendar: // - The Hijri calendar is a strictly Lunar calendar. // - Days begin at sunset. // - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date // 227015 (Friday, July 16, 622 C.E. - Julian). // - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th // years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11). // - There are 12 months which contain alternately 30 and 29 days. // - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days // in a leap year. // - Common years have 354 days. Leap years have 355 days. // - There are 10,631 days in a 30-year cycle. // - The Islamic months are: // 1. Muharram (30 days) 7. Rajab (30 days) // 2. Safar (29 days) 8. Sha'ban (29 days) // 3. Rabi I (30 days) 9. Ramadan (30 days) // 4. Rabi II (29 days) 10. Shawwal (29 days) // 5. Jumada I (30 days) 11. Dhu al-Qada (30 days) // 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30} // // NOTENOTE // The calculation of the HijriCalendar is based on the absolute date. And the // absolute date means the number of days from January 1st, 1 A.D. // Therefore, we do not support the days before the January 1st, 1 A.D. // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0622/07/18 9999/12/31 ** Hijri 0001/01/01 9666/04/03 */ [Serializable] public partial class HijriCalendar : Calendar { public static readonly int HijriEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int MinAdvancedHijri = -2; internal const int MaxAdvancedHijri = 2; internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 }; private int _hijriAdvance = Int32.MinValue; // DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3). internal const int MaxCalendarYear = 9666; internal const int MaxCalendarMonth = 4; internal const int MaxCalendarDay = 3; // Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18) // This is the minimal Gregorian date that we support in the HijriCalendar. internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18); internal static readonly DateTime calendarMaxValue = DateTime.MaxValue; public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (calendarMaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.LunarCalendar; } } public HijriCalendar() { } internal override CalendarId ID { get { return CalendarId.HIJRI; } } protected override int DaysInYearBeforeMinSupportedYear { get { // the year before the 1st year of the cycle would have been the 30th year // of the previous cycle which is not a leap year. Common years have 354 days. return 354; } } /*=================================GetAbsoluteDateHijri========================== **Action: Gets the Absolute date for the given Hijri date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: **Arguments: **Exceptions: ============================================================================*/ private long GetAbsoluteDateHijri(int y, int m, int d) { return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment); } /*=================================DaysUpToHijriYear========================== **Action: Gets the total number of days (absolute date) up to the given Hijri Year. ** The absolute date means the number of days from January 1st, 1 A.D. **Returns: Gets the total number of days (absolute date) up to the given Hijri Year. **Arguments: HijriYear year value in Hijri calendar. **Exceptions: None **Notes: ============================================================================*/ private long DaysUpToHijriYear(int HijriYear) { long NumDays; // number of absolute days int NumYear30; // number of years up to current 30 year cycle int NumYearsLeft; // number of years into 30 year cycle // // Compute the number of years up to the current 30 year cycle. // NumYear30 = ((HijriYear - 1) / 30) * 30; // // Compute the number of years left. This is the number of years // into the 30 year cycle for the given year. // NumYearsLeft = HijriYear - NumYear30 - 1; // // Compute the number of absolute days up to the given year. // NumDays = ((NumYear30 * 10631L) / 30L) + 227013L; while (NumYearsLeft > 0) { // Common year is 354 days, and leap year is 355 days. NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0); NumYearsLeft--; } // // Return the number of absolute days. // return (NumDays); } public int HijriAdjustment { get { if (_hijriAdvance == Int32.MinValue) { // Never been set before. Use the system value from registry. _hijriAdvance = GetHijriDateAdjustment(); } return (_hijriAdvance); } set { // NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good. if (value < MinAdvancedHijri || value > MaxAdvancedHijri) { throw new ArgumentOutOfRangeException( "HijriAdjustment", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinAdvancedHijri, MaxAdvancedHijri)); } Contract.EndContractBlock(); VerifyWritable(); _hijriAdvance = value; } } internal static void CheckTicksRange(long ticks) { if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, calendarMaxValue)); } } internal static void CheckEraRange(int era) { if (era != CurrentEra && era != HijriEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1 || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { if (month > MaxCalendarMonth) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarMonth)); } } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } } /*=================================GetDatePart========================== **Action: Returns a given date part of this <i>DateTime</i>. This method is used ** to compute the year, day-of-year, month, or day part. **Returns: **Arguments: **Exceptions: ArgumentException if part is incorrect. **Notes: ** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks. ** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year. ** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1). ** From here, we can get the correct Hijri year. ============================================================================*/ internal virtual int GetDatePart(long ticks, int part) { int HijriYear; // Hijri year int HijriMonth; // Hijri month int HijriDay; // Hijri day long NumDays; // The calculation buffer in number of days. CheckTicksRange(ticks); // // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D. // 1/1/0001 is absolute date 1. // NumDays = ticks / GregorianCalendar.TicksPerDay + 1; // // See how much we need to backup or advance // NumDays += HijriAdjustment; // // Calculate the appromixate Hijri Year from this magic formula. // HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1; long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year. if (NumDays < daysToHijriYear) { daysToHijriYear -= daysOfHijriYear; HijriYear--; } else if (NumDays == daysToHijriYear) { HijriYear--; daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra); } else { if (NumDays > daysToHijriYear + daysOfHijriYear) { daysToHijriYear += daysOfHijriYear; HijriYear++; } } if (part == DatePartYear) { return (HijriYear); } // // Calculate the Hijri Month. // HijriMonth = 1; NumDays -= daysToHijriYear; if (part == DatePartDayOfYear) { return ((int)NumDays); } while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1])) { HijriMonth++; } HijriMonth--; if (part == DatePartMonth) { return (HijriMonth); } // // Calculate the Hijri Day. // HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]); if (part == DatePartDay) { return (HijriDay); } // Incorrect part value. throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); // Get the date in Hijri calendar. int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if (month == 12) { // For the 12th month, leap year has 30 days, and common year has 29 days. return (IsLeapYear(year, CurrentEra) ? 30 : 29); } // Other months contain 30 and 29 days alternatively. The 1st month has 30 days. return (((month % 2) == 1) ? 30 : 29); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); // Common years have 354 days. Leap years have 355 days. return (IsLeapYear(year, CurrentEra) ? 355 : 354); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return (HijriEra); } public override int[] Eras { get { return (new int[] { HijriEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and MaxCalendarYear. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { // The year/month/era value checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } return (IsLeapYear(year, era) && month == 12 && day == 30); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); return ((((year * 11) + 14) % 30) < 11); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { // The year/month/era checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } long lDate = GetAbsoluteDateHijri(year, month, day); if (lDate >= 0) { return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } else { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(value), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } return (year); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; using System.Reflection; using System.IO; using System.Text.RegularExpressions; namespace Revit.SDK.Samples.NewRebar.CS { /// <summary> /// This is the main form for user to operate the Rebar creation. /// </summary> public partial class NewRebarForm : System.Windows.Forms.Form { ///// <summary> ///// Revit Application object. ///// </summary> //Autodesk.Revit.ApplicationServices.Application m_rvtApp; /// <summary> /// Revit Document object. /// </summary> Document m_rvtDoc; /// <summary> /// All RebarBarTypes of Revit current document. /// </summary> List<RebarBarType> m_rebarBarTypes = new List<RebarBarType>(); /// <summary> /// All RebarShape of Revit current document. /// </summary> List<RebarShape> m_rebarShapes = new List<RebarShape>(); /// <summary> /// Control binding source, provides data source for RebarBarType list box. /// </summary> BindingSource m_barTypesBinding = new BindingSource(); /// <summary> /// Control binding source, provides data source for RebarShapes list box. /// </summary> BindingSource m_shapesBinding = new BindingSource(); /// <summary> /// Default constructor. /// </summary> public NewRebarForm() { InitializeComponent(); } /// <summary> /// Constructor, initialize fields of RebarBarTypes and RebarShapes. /// </summary> /// <param name="rvtApp"></param> public NewRebarForm(Autodesk.Revit.DB.Document rvtDoc) :this() { m_rvtDoc = rvtDoc; foreach (RebarBarType barType in m_rvtDoc.RebarBarTypes) { m_rebarBarTypes.Add(barType); } foreach (RebarShape shape in m_rvtDoc.RebarShapes) { m_rebarShapes.Add(shape); } } /// <summary> /// Return RebarBarType from selection of barTypesComboBox. /// </summary> public RebarBarType RebarBarType { get { return barTypesComboBox.SelectedItem as RebarBarType; } } /// <summary> /// Return RebarShape from selection of shapesComboBox. /// </summary> public RebarShape RebarShape { get { return shapesComboBox.SelectedItem as RebarShape; } } /// <summary> /// OK Button, return DialogResult.OK and close this form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void okButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Cancel Button, return DialogResult.Cancel and close this form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } /// <summary> /// Present a dialog to customize a RebarShape. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void createShapeButton_Click(object sender, EventArgs e) { // Make sure the name is not null or empty. if(string.IsNullOrEmpty(nameTextBox.Text.Trim())) { MessageBox.Show("Please give a name to create a rebar shape."); return; } // Make sure the input name is started with letter and // just contains letters, numbers and underlines. Regex regex = new Regex("^[a-zA-Z]\\w+$"); if(!regex.IsMatch(nameTextBox.Text.Trim())) { MessageBox.Show("Please input the name starting with letter and just containing letters, numbers and underlines. String is " + nameTextBox.Text.ToString()); nameTextBox.Focus(); return; } // Create a RebarShapeDefinition. RebarShapeDef shapeDef = null; if (byArcradioButton.Checked) { // Create arc shape. RebarShapeDefinitionByArc arcShapeDefinition = null; RebarShapeDefinitionByArcType arcType = (RebarShapeDefinitionByArcType)Enum.Parse(typeof(RebarShapeDefinitionByArcType), arcTypecomboBox.Text); if (arcType != RebarShapeDefinitionByArcType.Spiral) { arcShapeDefinition = new RebarShapeDefinitionByArc(m_rvtDoc, arcType); } else { // Set default value for Spiral-Shape definition. arcShapeDefinition = new RebarShapeDefinitionByArc(m_rvtDoc, 10.0, 3.0, 0, 0); } shapeDef = new RebarShapeDefByArc(arcShapeDefinition); } else if (bySegmentsradioButton.Checked) { // Create straight segments shape. int segmentCount = 0; if (int.TryParse(segmentCountTextBox.Text, out segmentCount) && segmentCount > 0) { shapeDef = new RebarShapeDefBySegment(new RebarShapeDefinitionBySegments(m_rvtDoc, segmentCount)); } else { MessageBox.Show("Please input a valid positive integer as segments count."); return; } } int startHookAngle = 0; int endHookAngle = 0; RebarHookOrientation startHookOrientation = RebarHookOrientation.Left; RebarHookOrientation endHookOrientation = RebarHookOrientation.Left; bool doCreate = false; using (NewRebarShapeForm form = new NewRebarShapeForm(m_rvtDoc, shapeDef)) { // Present a form to customize the shape. if (DialogResult.OK == form.ShowDialog()) { doCreate = true; if (form.NeedSetHooks) { // Set hooks for rebar shape. startHookAngle = form.StartHookAngle; endHookAngle = form.EndHookAngle; startHookOrientation = form.StartHookOrientation; endHookOrientation = form.EndHookOrientation; } } } if (doCreate) { // Create the RebarShape. RebarShape createdRebarShape = RebarShape.Create(m_rvtDoc, shapeDef.RebarshapeDefinition, null, RebarStyle.Standard, StirrupTieAttachmentType.InteriorFace, startHookAngle, startHookOrientation, endHookAngle, endHookOrientation, 0); createdRebarShape.Name = nameTextBox.Text.Trim(); // Add the created shape to the candidate list. m_rebarShapes.Add(createdRebarShape); m_shapesBinding.ResetBindings(false); shapesComboBox.SelectedItem = createdRebarShape; } } /// <summary> /// Update the status of some controls. /// </summary> private void UpdateUIStatus() { segmentCountTextBox.Enabled = bySegmentsradioButton.Checked; arcTypecomboBox.Enabled = byArcradioButton.Checked; } /// <summary> /// byArcradioButton check status change event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void byArcradioButton_CheckedChanged(object sender, EventArgs e) { UpdateUIStatus(); } /// <summary> /// bySegmentsradioButton check status change event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bySegmentsradioButton_CheckedChanged(object sender, EventArgs e) { UpdateUIStatus(); } /// <summary> /// Load event, Initialize controls data source. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewRebarForm_Load(object sender, EventArgs e) { m_barTypesBinding.DataSource = m_rebarBarTypes; m_shapesBinding.DataSource = m_rebarShapes; arcTypecomboBox.DropDownStyle = ComboBoxStyle.DropDownList; arcTypecomboBox.DataSource = Enum.GetNames(typeof(RebarShapeDefinitionByArcType)); shapesComboBox.Sorted = true; barTypesComboBox.Sorted = true; shapesComboBox.DataSource = m_shapesBinding; shapesComboBox.DisplayMember = "Name"; barTypesComboBox.DataSource = m_barTypesBinding; barTypesComboBox.DisplayMember = "Name"; } } }
using Microsoft.Practices.ServiceLocation; using Prism.Common; using Prism.Properties; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Windows; namespace Prism.Regions { /// <summary> /// Provides navigation for regions. /// </summary> public class RegionNavigationService : IRegionNavigationService { private readonly IServiceLocator serviceLocator; private readonly IRegionNavigationContentLoader regionNavigationContentLoader; private IRegionNavigationJournal journal; private NavigationContext currentNavigationContext; /// <summary> /// Initializes a new instance of the <see cref="RegionNavigationService"/> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="regionNavigationContentLoader">The navigation target handler.</param> /// <param name="journal">The journal.</param> public RegionNavigationService(IServiceLocator serviceLocator, IRegionNavigationContentLoader regionNavigationContentLoader, IRegionNavigationJournal journal) { if (serviceLocator == null) throw new ArgumentNullException(nameof(serviceLocator)); if (regionNavigationContentLoader == null) throw new ArgumentNullException(nameof(regionNavigationContentLoader)); if (journal == null) throw new ArgumentNullException(nameof(journal)); this.serviceLocator = serviceLocator; this.regionNavigationContentLoader = regionNavigationContentLoader; this.journal = journal; this.journal.NavigationTarget = this; } /// <summary> /// Gets or sets the region. /// </summary> /// <value>The region.</value> public IRegion Region { get; set; } /// <summary> /// Gets the journal. /// </summary> /// <value>The journal.</value> public IRegionNavigationJournal Journal { get { return this.journal; } } /// <summary> /// Raised when the region is about to be navigated to content. /// </summary> public event EventHandler<RegionNavigationEventArgs> Navigating; private void RaiseNavigating(NavigationContext navigationContext) { if (this.Navigating != null) { this.Navigating(this, new RegionNavigationEventArgs(navigationContext)); } } /// <summary> /// Raised when the region is navigated to content. /// </summary> public event EventHandler<RegionNavigationEventArgs> Navigated; private void RaiseNavigated(NavigationContext navigationContext) { if (this.Navigated != null) { this.Navigated(this, new RegionNavigationEventArgs(navigationContext)); } } /// <summary> /// Raised when a navigation request fails. /// </summary> public event EventHandler<RegionNavigationFailedEventArgs> NavigationFailed; private void RaiseNavigationFailed(NavigationContext navigationContext, Exception error) { if (this.NavigationFailed != null) { this.NavigationFailed(this, new RegionNavigationFailedEventArgs(navigationContext, error)); } } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is marshalled to callback")] public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback) { this.RequestNavigate(target, navigationCallback, null); } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> /// <param name="navigationParameters">The navigation parameters specific to the navigation request.</param> public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { if (navigationCallback == null) throw new ArgumentNullException(nameof(navigationCallback)); try { this.DoNavigate(target, navigationCallback, navigationParameters); } catch (Exception e) { this.NotifyNavigationFailed(new NavigationContext(this, target), navigationCallback, e); } } private void DoNavigate(Uri source, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { if (source == null) throw new ArgumentNullException(nameof(source)); if (this.Region == null) throw new InvalidOperationException(Resources.NavigationServiceHasNoRegion); this.currentNavigationContext = new NavigationContext(this, source, navigationParameters); // starts querying the active views RequestCanNavigateFromOnCurrentlyActiveView( this.currentNavigationContext, navigationCallback, this.Region.ActiveViews.ToArray(), 0); } private void RequestCanNavigateFromOnCurrentlyActiveView( NavigationContext navigationContext, Action<NavigationResult> navigationCallback, object[] activeViews, int currentViewIndex) { if (currentViewIndex < activeViews.Length) { var vetoingView = activeViews[currentViewIndex] as IConfirmNavigationRequest; if (vetoingView != null) { // the current active view implements IConfirmNavigationRequest, request confirmation // providing a callback to resume the navigation request vetoingView.ConfirmNavigationRequest( navigationContext, canNavigate => { if (this.currentNavigationContext == navigationContext && canNavigate) { RequestCanNavigateFromOnCurrentlyActiveViewModel( navigationContext, navigationCallback, activeViews, currentViewIndex); } else { this.NotifyNavigationFailed(navigationContext, navigationCallback, null); } }); } else { RequestCanNavigateFromOnCurrentlyActiveViewModel( navigationContext, navigationCallback, activeViews, currentViewIndex); } } else { ExecuteNavigation(navigationContext, activeViews, navigationCallback); } } private void RequestCanNavigateFromOnCurrentlyActiveViewModel( NavigationContext navigationContext, Action<NavigationResult> navigationCallback, object[] activeViews, int currentViewIndex) { var frameworkElement = activeViews[currentViewIndex] as FrameworkElement; if (frameworkElement != null) { var vetoingViewModel = frameworkElement.DataContext as IConfirmNavigationRequest; if (vetoingViewModel != null) { // the data model for the current active view implements IConfirmNavigationRequest, request confirmation // providing a callback to resume the navigation request vetoingViewModel.ConfirmNavigationRequest( navigationContext, canNavigate => { if (this.currentNavigationContext == navigationContext && canNavigate) { RequestCanNavigateFromOnCurrentlyActiveView( navigationContext, navigationCallback, activeViews, currentViewIndex + 1); } else { this.NotifyNavigationFailed(navigationContext, navigationCallback, null); } }); return; } } RequestCanNavigateFromOnCurrentlyActiveView( navigationContext, navigationCallback, activeViews, currentViewIndex + 1); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is marshalled to callback")] private void ExecuteNavigation(NavigationContext navigationContext, object[] activeViews, Action<NavigationResult> navigationCallback) { try { NotifyActiveViewsNavigatingFrom(navigationContext, activeViews); object view = this.regionNavigationContentLoader.LoadContent(this.Region, navigationContext); // Raise the navigating event just before activing the view. this.RaiseNavigating(navigationContext); this.Region.Activate(view); // Update the navigation journal before notifying others of navigaton IRegionNavigationJournalEntry journalEntry = this.serviceLocator.GetInstance<IRegionNavigationJournalEntry>(); journalEntry.Uri = navigationContext.Uri; journalEntry.Parameters = navigationContext.Parameters; this.journal.RecordNavigation(journalEntry); // The view can be informed of navigation Action<INavigationAware> action = (n) => n.OnNavigatedTo(navigationContext); MvvmHelpers.ViewAndViewModelAction(view, action); navigationCallback(new NavigationResult(navigationContext, true)); // Raise the navigated event when navigation is completed. this.RaiseNavigated(navigationContext); } catch (Exception e) { this.NotifyNavigationFailed(navigationContext, navigationCallback, e); } } private void NotifyNavigationFailed(NavigationContext navigationContext, Action<NavigationResult> navigationCallback, Exception e) { var navigationResult = e != null ? new NavigationResult(navigationContext, e) : new NavigationResult(navigationContext, false); navigationCallback(navigationResult); this.RaiseNavigationFailed(navigationContext, e); } private static void NotifyActiveViewsNavigatingFrom(NavigationContext navigationContext, object[] activeViews) { InvokeOnNavigationAwareElements(activeViews, (n) => n.OnNavigatedFrom(navigationContext)); } private static void InvokeOnNavigationAwareElements(IEnumerable<object> items, Action<INavigationAware> invocation) { foreach (var item in items) { MvvmHelpers.ViewAndViewModelAction(item, invocation); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.GrainDirectory; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { internal class AdaptiveDirectoryCacheMaintainer : TaskSchedulerAgent { private static readonly TimeSpan SLEEP_TIME_BETWEEN_REFRESHES = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(1); // this should be something like minTTL/4 private readonly AdaptiveGrainDirectoryCache cache; private readonly LocalGrainDirectory router; private readonly IInternalGrainFactory grainFactory; private long lastNumAccesses; // for stats private long lastNumHits; // for stats internal AdaptiveDirectoryCacheMaintainer( LocalGrainDirectory router, AdaptiveGrainDirectoryCache cache, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory) : base(loggerFactory) { this.grainFactory = grainFactory; this.router = router; this.cache = cache; lastNumAccesses = 0; lastNumHits = 0; OnFault = FaultBehavior.RestartOnFault; } protected override async Task Run() { while (router.Running) { // Run through all cache entries and do the following: // 1. If the entry is not expired, skip it // 2. If the entry is expired and was not accessed in the last time interval -- throw it away // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list // At the end of the process, fetch batch requests for entries that need to be refreshed // Upon receiving refreshing answers, if the entry was not changed, double its expiration timer. // If it was changed, update the cache and reset the expiration timer. // this dictionary holds a map between a silo address and the list of grains that need to be refreshed var fetchInBatchList = new Dictionary<SiloAddress, List<GrainId>>(); // get the list of cached grains // for debug only int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0; // run through all cache entries var enumerator = cache.GetStoredEntries(); while (enumerator.MoveNext()) { var pair = enumerator.Current; GrainId grain = pair.Key; var entry = pair.Value; SiloAddress owner = router.CalculateGrainDirectoryPartition(grain); if (owner == null) // Null means there's no other silo and we're shutting down, so skip this entry { continue; } if (owner.Equals(router.MyAddress)) { // we found our owned entry in the cache -- it is not supposed to happen unless there were // changes in the membership Log.Warn(ErrorCode.Runtime_Error_100185, "Grain {grain} owned by {owner} was found in the cache of {owner}", grain, owner, owner); cache.Remove(grain); cnt1++; // for debug } else { if (entry == null) { // 0. If the entry was deleted in parallel, presumably due to cleanup after silo death cache.Remove(grain); // for debug cnt3++; } else if (!entry.IsExpired()) { // 1. If the entry is not expired, skip it cnt2++; // for debug } else if (entry.NumAccesses == 0) { // 2. If the entry is expired and was not accessed in the last time interval -- throw it away cache.Remove(grain); // for debug cnt3++; } else { // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list if (!fetchInBatchList.TryGetValue(owner, out var list)) { fetchInBatchList[owner] = list = new List<GrainId>(); } list.Add(grain); // And reset the entry's access count for next time entry.NumAccesses = 0; cnt4++; // for debug } } } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} self-owned (and removed) {1}, kept {2}, removed {3} and tries to refresh {4} grains", router.MyAddress, cnt1, cnt2, cnt3, cnt4); // send batch requests SendBatchCacheRefreshRequests(fetchInBatchList); ProduceStats(); // recheck every X seconds (Consider making it a configurable parameter) await Task.Delay(SLEEP_TIME_BETWEEN_REFRESHES); } } private void SendBatchCacheRefreshRequests(Dictionary<SiloAddress, List<GrainId>> refreshRequests) { foreach (var kv in refreshRequests) { var cachedGrainAndETagList = BuildGrainAndETagList(kv.Value); var silo = kv.Key; router.CacheValidationsSent.Increment(); // Send all of the items in one large request var validator = this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryCacheValidatorType, silo); router.Scheduler.QueueTask(async () => { var response = await validator.LookUpMany(cachedGrainAndETagList); ProcessCacheRefreshResponse(silo, response); }, router.CacheValidator).Ignore(); if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} is sending request to silo {1} with {2} entries", router.MyAddress, silo, cachedGrainAndETagList.Count); } } private void ProcessCacheRefreshResponse( SiloAddress silo, List<AddressAndTag> refreshResponse) { if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} received ProcessCacheRefreshResponse. #Response entries {1}.", router.MyAddress, refreshResponse.Count); int cnt1 = 0, cnt2 = 0, cnt3 = 0; // pass through returned results and update the cache if needed foreach (var tuple in refreshResponse) { if (tuple.Address is { IsComplete: true }) { // the server returned an updated entry cache.AddOrUpdate(tuple.Address, tuple.VersionTag); cnt1++; } else if (tuple.VersionTag == -1) { // The server indicates that it does not own the grain anymore. // It could be that by now, the cache has been already updated and contains an entry received from another server (i.e., current owner for the grain). // For simplicity, we do not care about this corner case and simply remove the cache entry. cache.Remove(tuple.Address.Grain); cnt2++; } else { // The server returned only a (not -1) generation number, indicating that we hold the most // updated copy of the grain's activations list. // Validate that the generation number in the request and the response are equal // Contract.Assert(tuple.Item2 == refreshRequest.Find(o => o.Item1 == tuple.Item1).Item2); // refresh the entry in the cache cache.MarkAsFresh(tuple.Address.Grain); cnt3++; } } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} processed refresh response from {1} with {2} updated, {3} removed, {4} unchanged grains", router.MyAddress, silo, cnt1, cnt2, cnt3); } /// <summary> /// Gets the list of grains (all owned by the same silo) and produces a new list /// of tuples, where each tuple holds the grain and its generation counter currently stored in the cache /// </summary> /// <param name="grains">List of grains owned by the same silo</param> /// <returns>List of grains in input along with their generation counters stored in the cache </returns> private List<(GrainId, int)> BuildGrainAndETagList(List<GrainId> grains) { var grainAndETagList = new List<(GrainId, int)>(); foreach (GrainId grain in grains) { // NOTE: should this be done with TryGet? Won't Get invoke the LRU getter function? AdaptiveGrainDirectoryCache.GrainDirectoryCacheEntry entry = cache.Get(grain); if (entry != null) { grainAndETagList.Add((grain, entry.ETag)); } else { // this may happen only if the LRU cache is full and decided to drop this grain // while we try to refresh it Log.Warn(ErrorCode.Runtime_Error_100199, "Grain {0} disappeared from the cache during maintenance", grain); } } return grainAndETagList; } private void ProduceStats() { // We do not want to synchronize the access on numAccess and numHits in cache to avoid performance issues. // Thus we take the current reading of these fields and calculate the stats. We might miss an access or two, // but it should not be matter. long curNumAccesses = cache.NumAccesses; long curNumHits = cache.NumHits; long numAccesses = curNumAccesses - lastNumAccesses; long numHits = curNumHits - lastNumHits; if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("#accesses: {0}, hit-ratio: {1}%", numAccesses, (numHits / Math.Max(numAccesses, 0.00001)) * 100); lastNumAccesses = curNumAccesses; lastNumHits = curNumHits; } } }
using System; using Avalonia.Collections; using Avalonia.Media; #nullable enable namespace Avalonia.Controls.Shapes { /// <summary> /// Provides a base class for shape elements, such as <see cref="Ellipse"/>, <see cref="Polygon"/> and <see cref="Rectangle"/>. /// </summary> public abstract class Shape : Control { /// <summary> /// Defines the <see cref="Fill"/> property. /// </summary> public static readonly StyledProperty<IBrush?> FillProperty = AvaloniaProperty.Register<Shape, IBrush?>(nameof(Fill)); /// <summary> /// Defines the <see cref="Stretch"/> property. /// </summary> public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register<Shape, Stretch>(nameof(Stretch)); /// <summary> /// Defines the <see cref="Stroke"/> property. /// </summary> public static readonly StyledProperty<IBrush?> StrokeProperty = AvaloniaProperty.Register<Shape, IBrush?>(nameof(Stroke)); /// <summary> /// Defines the <see cref="StrokeDashArray"/> property. /// </summary> public static readonly StyledProperty<AvaloniaList<double>?> StrokeDashArrayProperty = AvaloniaProperty.Register<Shape, AvaloniaList<double>?>(nameof(StrokeDashArray)); /// <summary> /// Defines the <see cref="StrokeDashOffset"/> property. /// </summary> public static readonly StyledProperty<double> StrokeDashOffsetProperty = AvaloniaProperty.Register<Shape, double>(nameof(StrokeDashOffset)); /// <summary> /// Defines the <see cref="StrokeThickness"/> property. /// </summary> public static readonly StyledProperty<double> StrokeThicknessProperty = AvaloniaProperty.Register<Shape, double>(nameof(StrokeThickness)); /// <summary> /// Defines the <see cref="StrokeLineCap"/> property. /// </summary> public static readonly StyledProperty<PenLineCap> StrokeLineCapProperty = AvaloniaProperty.Register<Shape, PenLineCap>(nameof(StrokeLineCap), PenLineCap.Flat); /// <summary> /// Defines the <see cref="StrokeJoin"/> property. /// </summary> public static readonly StyledProperty<PenLineJoin> StrokeJoinProperty = AvaloniaProperty.Register<Shape, PenLineJoin>(nameof(StrokeJoin), PenLineJoin.Miter); private Matrix _transform = Matrix.Identity; private Geometry? _definingGeometry; private Geometry? _renderedGeometry; static Shape() { AffectsMeasure<Shape>(StretchProperty, StrokeThicknessProperty); AffectsRender<Shape>(FillProperty, StrokeProperty, StrokeDashArrayProperty, StrokeDashOffsetProperty, StrokeThicknessProperty, StrokeLineCapProperty, StrokeJoinProperty); } /// <summary> /// Gets a value that represents the <see cref="Geometry"/> of the shape. /// </summary> public Geometry? DefiningGeometry { get { if (_definingGeometry == null) { _definingGeometry = CreateDefiningGeometry(); } return _definingGeometry; } } /// <summary> /// Gets a value that represents the final rendered <see cref="Geometry"/> of the shape. /// </summary> public Geometry? RenderedGeometry { get { if (_renderedGeometry == null && DefiningGeometry != null) { if (_transform == Matrix.Identity) { _renderedGeometry = DefiningGeometry; } else { _renderedGeometry = DefiningGeometry.Clone(); if (_renderedGeometry.Transform == null || _renderedGeometry.Transform.Value == Matrix.Identity) { _renderedGeometry.Transform = new MatrixTransform(_transform); } else { _renderedGeometry.Transform = new MatrixTransform( _renderedGeometry.Transform.Value * _transform); } } } return _renderedGeometry; } } /// <summary> /// Gets or sets the <see cref="IBrush"/> that specifies how the shape's interior is painted. /// </summary> public IBrush? Fill { get { return GetValue(FillProperty); } set { SetValue(FillProperty, value); } } /// <summary> /// Gets or sets a <see cref="Stretch"/> enumeration value that describes how the shape fills its allocated space. /// </summary> public Stretch Stretch { get { return GetValue(StretchProperty); } set { SetValue(StretchProperty, value); } } /// <summary> /// Gets or sets the <see cref="IBrush"/> that specifies how the shape's outline is painted. /// </summary> public IBrush? Stroke { get { return GetValue(StrokeProperty); } set { SetValue(StrokeProperty, value); } } /// <summary> /// Gets or sets a collection of <see cref="double"/> values that indicate the pattern of dashes and gaps that is used to outline shapes. /// </summary> public AvaloniaList<double>? StrokeDashArray { get { return GetValue(StrokeDashArrayProperty); } set { SetValue(StrokeDashArrayProperty, value); } } /// <summary> /// Gets or sets a value that specifies the distance within the dash pattern where a dash begins. /// </summary> public double StrokeDashOffset { get { return GetValue(StrokeDashOffsetProperty); } set { SetValue(StrokeDashOffsetProperty, value); } } /// <summary> /// Gets or sets the width of the shape outline. /// </summary> public double StrokeThickness { get { return GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } /// <summary> /// Gets or sets a <see cref="PenLineCap"/> enumeration value that describes the shape at the ends of a line. /// </summary> public PenLineCap StrokeLineCap { get { return GetValue(StrokeLineCapProperty); } set { SetValue(StrokeLineCapProperty, value); } } /// <summary> /// Gets or sets a <see cref="PenLineJoin"/> enumeration value that specifies the type of join that is used at the vertices of a Shape. /// </summary> public PenLineJoin StrokeJoin { get { return GetValue(StrokeJoinProperty); } set { SetValue(StrokeJoinProperty, value); } } public override void Render(DrawingContext context) { var geometry = RenderedGeometry; if (geometry != null) { var pen = new Pen(Stroke, StrokeThickness, new DashStyle(StrokeDashArray, StrokeDashOffset), StrokeLineCap, StrokeJoin); context.DrawGeometry(Fill, pen, geometry); } } /// <summary> /// Marks a property as affecting the shape's geometry. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// After a call to this method in a control's static constructor, any change to the /// property will cause <see cref="InvalidateGeometry"/> to be called on the element. /// </remarks> protected static void AffectsGeometry<TShape>(params AvaloniaProperty[] properties) where TShape : Shape { foreach (var property in properties) { property.Changed.Subscribe(e => { if (e.Sender is TShape shape) { AffectsGeometryInvalidate(shape, e); } }); } } /// <summary> /// Creates the shape's defining geometry. /// </summary> /// <returns>Defining <see cref="Geometry"/> of the shape.</returns> protected abstract Geometry? CreateDefiningGeometry(); /// <summary> /// Invalidates the geometry of this shape. /// </summary> protected void InvalidateGeometry() { _renderedGeometry = null; _definingGeometry = null; InvalidateMeasure(); } protected override Size MeasureOverride(Size availableSize) { if (DefiningGeometry is null) { return default; } return CalculateSizeAndTransform(availableSize, DefiningGeometry.Bounds, Stretch).size; } protected override Size ArrangeOverride(Size finalSize) { if (DefiningGeometry != null) { // This should probably use GetRenderBounds(strokeThickness) but then the calculations // will multiply the stroke thickness as well, which isn't correct. var (_, transform) = CalculateSizeAndTransform(finalSize, DefiningGeometry.Bounds, Stretch); if (_transform != transform) { _transform = transform; _renderedGeometry = null; } return finalSize; } return Size.Empty; } internal static (Size size, Matrix transform) CalculateSizeAndTransform(Size availableSize, Rect shapeBounds, Stretch Stretch) { Size shapeSize = new Size(shapeBounds.Right, shapeBounds.Bottom); Matrix translate = Matrix.Identity; double desiredX = availableSize.Width; double desiredY = availableSize.Height; double sx = 0.0; double sy = 0.0; if (Stretch != Stretch.None) { shapeSize = shapeBounds.Size; translate = Matrix.CreateTranslation(-(Vector)shapeBounds.Position); } if (double.IsInfinity(availableSize.Width)) { desiredX = shapeSize.Width; } if (double.IsInfinity(availableSize.Height)) { desiredY = shapeSize.Height; } if (shapeBounds.Width > 0) { sx = desiredX / shapeSize.Width; } if (shapeBounds.Height > 0) { sy = desiredY / shapeSize.Height; } if (double.IsInfinity(availableSize.Width)) { sx = sy; } if (double.IsInfinity(availableSize.Height)) { sy = sx; } switch (Stretch) { case Stretch.Uniform: sx = sy = Math.Min(sx, sy); break; case Stretch.UniformToFill: sx = sy = Math.Max(sx, sy); break; case Stretch.Fill: if (double.IsInfinity(availableSize.Width)) { sx = 1.0; } if (double.IsInfinity(availableSize.Height)) { sy = 1.0; } break; default: sx = sy = 1; break; } var transform = translate * Matrix.CreateScale(sx, sy); var size = new Size(shapeSize.Width * sx, shapeSize.Height * sy); return (size, transform); } private static void AffectsGeometryInvalidate(Shape control, AvaloniaPropertyChangedEventArgs e) { // If the geometry is invalidated when Bounds changes, only invalidate when the Size // portion changes. if (e.Property == BoundsProperty) { var oldBounds = (Rect)e.OldValue!; var newBounds = (Rect)e.NewValue!; if (oldBounds.Size == newBounds.Size) { return; } } control.InvalidateGeometry(); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TaskContinuation.cs // // // Implementation of task continuations, TaskContinuation, and its descendants. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Security; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; using System.Threading; using Internal.Runtime.Augments; using AsyncStatus = Internal.Runtime.Augments.AsyncStatus; using CausalityRelation = Internal.Runtime.Augments.CausalityRelation; using CausalitySource = Internal.Runtime.Augments.CausalitySource; using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel; using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task,...>) internal sealed class ContinuationTaskFromTask : Task { private Task m_antecedent; public ContinuationTaskFromTask( Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Contract.Requires(action is Action<Task> || action is Action<Task, object>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Contract.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Contract.Assert(m_action != null); var action = m_action as Action<Task>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task m_antecedent; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Contract.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Contract.Assert(m_action != null); var func = m_action as Func<Task, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult> m_antecedent; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Contract.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Contract.Assert(m_action != null); var action = m_action as Action<Task<TAntecedentResult>>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task<TAntecedentResult>, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult> m_antecedent; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Contract.Requires(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Contract.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Contract.Assert(m_action != null); var func = m_action as Func<Task<TAntecedentResult>, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); } } // For performance reasons, we don't just have a single way of representing // a continuation object. Rather, we have a hierarchy of types: // - TaskContinuation: abstract base that provides a virtual Run method // - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration // - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default // - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler // - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx /// <summary>Represents a continuation.</summary> internal abstract class TaskContinuation { /// <summary>Inlines or schedules the continuation.</summary> /// <param name="completedTask">The antecedent task that has completed.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal abstract void Run(Task completedTask, bool bCanInlineContinuationTask); /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary> /// <param name="task">The task to run</param> /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Contract.Requires(task != null); Contract.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it // that may try to execute it. if (needsProtection) { if (!task.MarkStarted()) return; // task has been previously started or canceled. Stop processing. } else { task.m_stateFlags |= Task.TASK_STATE_STARTED; } // Try to inline it but queue if we can't try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.QueueTask(task); } } catch (Exception e) { // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted. // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, // because it would already have been handled in Task.Execute() //if (!(e is ThreadAbortException && // (task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0)) // this ensures TAEs from QueueTask will be wrapped in TSE { TaskSchedulerException tse = new TaskSchedulerException(e); task.AddException(tse); task.Finish(false); } // Don't re-throw. } } // // This helper routine is targeted by the debugger. // [DependencyReductionRoot] internal abstract Delegate[] GetDelegateContinuationsForDebugger(); } /// <summary>Provides the standard implementation of a task continuation.</summary> internal class StandardTaskContinuation : TaskContinuation { /// <summary>The unstarted continuation task.</summary> internal readonly Task m_task; /// <summary>The options to use with the continuation task.</summary> internal readonly TaskContinuationOptions m_options; /// <summary>The task scheduler with which to run the continuation task.</summary> private readonly TaskScheduler m_taskScheduler; /// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Contract.Requires(task != null, "TaskContinuation ctor: task is null"); Contract.Requires(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, m_task, "Task.ContinueWith: " + task.m_action, 0); DebuggerSupport.AddToActiveTasks(m_task); } /// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool bCanInlineContinuationTask) { Contract.Assert(completedTask != null); Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsRanToCompletion ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. Task continuationTask = m_task; if (isRightKind) { if (!continuationTask.IsCanceled && DebuggerSupport.LoggingOn) { // Log now that we are sure that this continuation is being ran DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (bCanInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } // Otherwise, the final state of this task does not match the desired // continuation activation criteria; cancel it to denote this. else continuationTask.InternalCancel(false); } internal override Delegate[] GetDelegateContinuationsForDebugger() { if (m_task.m_action == null) { return m_task.GetDelegateContinuationsForDebugger(); } return new Delegate[] { m_task.m_action as Delegate }; } } /// <summary>Task continuation for awaiting with a current synchronization context.</summary> internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical /// <summary>Cached delegate for PostAction</summary> private static ContextCallback s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="stackMark">The captured stack mark.</param> internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Contract.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); } // Otherwise, Post the action back to the SynchronizationContext. else { RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } // Any exceptions will be handled by RunCallback. } /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> private static void PostAction(object state) { var c = (SynchronizationContextAwaitTaskContinuation)state; c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method } /// <summary>Gets a cached delegate for the PostAction method.</summary> /// <returns> /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() { ContextCallback callback = s_postActionCallback; if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate return callback; } } /// <summary>Task continuation for awaiting with a task scheduler.</summary> internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>The scheduler on which to run the action.</summary> private readonly TaskScheduler m_scheduler; /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary> /// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="stackMark">The captured stack mark.</param> internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Contract.Assert(scheduler != null); m_scheduler = scheduler; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're targeting the default scheduler, we can use the faster path provided by the base class. if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); } else { // We permit inlining if the caller allows us to, and // either we're on a thread pool thread (in which case we're fine running arbitrary code) // or we're already on the target scheduler (in which case we'll just ask the scheduler // whether it's ok to run here). We include the IsThreadPoolThread check here, whereas // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed // to in AwaitTaskContinuation.Run where it restricts what's allowed. bool inlineIfPossible = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || ThreadPool.IsThreadPoolThread); // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. var task = CreateTask(state => { try { ((Action)state)(); } catch (Exception exc) { ThrowAsyncIfNecessary(exc); } }, m_action, m_scheduler); if (inlineIfPossible) { InlineIfPossibleOrElseQueue(task, needsProtection: false); } else { // We need to run asynchronously, so just schedule the task. try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted } } } } /// <summary>Base task continuation class used for await continuations.</summary> internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { /// <summary>The ExecutionContext with which to run the continuation.</summary> private readonly ExecutionContext m_capturedContext; /// <summary>The action to invoke.</summary> protected readonly Action m_action; /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Contract.Requires(action != null); m_action = action; if (flowExecutionContext) m_capturedContext = ExecutionContext.Capture(); } /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary> /// <param name="action">The action to run. Must not be null.</param> /// <param name="state">The state to pass to the action. Must not be null.</param> /// <param name="scheduler">The scheduler to target.</param> /// <returns>The created task.</returns> protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler) { Contract.Requires(action != null); Contract.Requires(scheduler != null); return new Task( action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler); } /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal override void Run(Task ignored, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it // and if we're in a "valid location" for it. See the comments on // IsValidLocationForInlining for more about what's valid. For performance // reasons we would like to always inline, but we don't in some cases to avoid // running arbitrary amounts of work in suspected "bad locations", like UI threads. if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction } else { // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false); } } /// <summary> /// Gets whether the current thread is an appropriate location to inline a continuation's execution. /// </summary> /// <remarks> /// Returns whether SynchronizationContext is null and we're in the default scheduler. /// If the await had a SynchronizationContext/TaskScheduler where it began and the /// default/ConfigureAwait(true) was used, then we won't be on this path. If, however, /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were /// naturally null/Default, then we might end up here. If we do, we need to make sure /// that we don't execute continuations in a place that isn't set up to handle them, e.g. /// running arbitrary amounts of code on the UI thread. It would be "correct", but very /// expensive, to always run the continuations asynchronously, incurring lots of context /// switches and allocations and locks and the like. As such, we employ the heuristic /// that if the current thread has a non-null SynchronizationContext or a non-default /// scheduler, then we better not run arbitrary continuations here. /// </remarks> internal static bool IsValidLocationForInlining { get { // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. var ctx = SynchronizationContext.Current; if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. var sched = TaskScheduler.InternalCurrent; return sched == null || sched == TaskScheduler.Default; } } /// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary> void IThreadPoolWorkItem.ExecuteWorkItem() { // inline the fast path if (m_capturedContext == null) m_action(); else ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action); } ///// <summary> ///// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. ///// </summary> //void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> private static ContextCallback s_invokeActionCallback; /// <summary>Runs an action provided as an object parameter.</summary> /// <param name="state">The Action to invoke.</param> private static void InvokeAction(object state) { ((Action)state)(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() { ContextCallback callback = s_invokeActionCallback; if (callback == null) { s_invokeActionCallback = callback = InvokeAction; } // lazily initialize SecurityCritical delegate return callback; } /// <summary>Runs the callback synchronously with the provided state.</summary> /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { Contract.Requires(callback != null); Contract.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information var prevCurrentTask = currentTask; var prevSyncCtx = SynchronizationContext.CurrentExplicit; try { if (prevCurrentTask != null) currentTask = null; callback(state); } catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs { ThrowAsyncIfNecessary(exc); } finally { // Restore the current task information if (prevCurrentTask != null) currentTask = prevCurrentTask; // Restore the SynchronizationContext SynchronizationContext.SetSynchronizationContext(prevSyncCtx); } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the action to run asynchronously. /// </param> /// <param name="currentTask"> /// A reference to the t_currentTask thread static value. /// This is passed by-ref rather than accessed in the method in order to avoid /// unnecessary thread-static writes. /// </param> /// <remarks> /// No ExecutionContext work is performed used. This method is only used in the /// case where a raw Action continuation delegate was stored into the Task, which /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask) { Contract.Assert(currentTask == Task.t_currentTask); // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action); return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution Task prevCurrentTask = currentTask; try { if (prevCurrentTask != null) currentTask = null; action(); } catch (Exception exception) { ThrowAsyncIfNecessary(exception); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> internal static void UnsafeScheduleAction(Action action) { ThreadPool.UnsafeQueueCustomWorkItem( new AwaitTaskContinuation(action, flowExecutionContext: false), forceGlobal: false); } /// <summary>Throws the exception asynchronously on the ThreadPool.</summary> /// <param name="exc">The exception to throw.</param> protected static void ThrowAsyncIfNecessary(Exception exc) { // Awaits should never experience an exception (other than an TAE or ADUE), // unless a malicious user is explicitly passing a throwing action into the TaskAwaiter. // We don't want to allow the exception to propagate on this stack, as it'll emerge in random places, // and we can't fail fast, as that would allow for elevation of privilege. Instead, since this // would have executed on the thread pool otherwise, let it propagate there. //if (!(exc is ThreadAbortException || exc is AppDomainUnloadedException)) { RuntimeAugments.ReportUnhandledException(exc); } } internal override Delegate[] GetDelegateContinuationsForDebugger() { Contract.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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.IO; using NUnit.Framework; using Realms; using Realms.Exceptions; using ExplicitAttribute = NUnit.Framework.ExplicitAttribute; namespace Tests.Database { [TestFixture, Preserve(AllMembers = true)] public class ConfigurationTests { private static void ReliesOnEncryption() { #if ENCRYPTION_DISABLED Assert.Ignore("This test relies on encryption which is not enabled in this build"); #endif } [Test] public void DefaultConfigurationShouldHaveValidPath() { // Arrange var config = RealmConfiguration.DefaultConfiguration; // Assert Assert.That(Path.IsPathRooted(config.DatabasePath)); } [Test] public void CanSetConfigurationPartialPath() { // Arrange var config = RealmConfiguration.DefaultConfiguration.ConfigWithPath("jan" + Path.DirectorySeparatorChar + "docs" + Path.DirectorySeparatorChar); // Assert Assert.That(Path.IsPathRooted(config.DatabasePath)); Assert.That(config.DatabasePath, Does.EndWith(Path.Combine("jan", "docs", "default.realm"))); } [Test] public void PathIsCanonicalised() { // Arrange var config = RealmConfiguration.DefaultConfiguration.ConfigWithPath(Path.Combine("..", "Documents", "fred.realm")); // Assert Assert.That(Path.IsPathRooted(config.DatabasePath)); Assert.That(config.DatabasePath, Does.EndWith(Path.Combine("Documents", "fred.realm"))); Assert.IsFalse(config.DatabasePath.Contains("..")); // our use of relative up and down again was normalised out } [Test] public void CanOverrideConfigurationFilename() { // Arrange var config = new RealmConfiguration(); var config2 = config.ConfigWithPath("fred.realm"); // Assert Assert.That(config2.DatabasePath, Does.EndWith("fred.realm")); } [Test] public void CanSetDefaultConfiguration() { // Arrange var config = new RealmConfiguration(); RealmConfiguration.DefaultConfiguration = config.ConfigWithPath("fred.realm"); // Assert Assert.That(RealmConfiguration.DefaultConfiguration.DatabasePath, Does.EndWith("fred.realm")); } [Test] public void EncryptionKeyMustBe64Bytes() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("EncryptionKeyMustBe64Bytes.realm"); var smallKey = new byte[] { 1, 2, 3 }; var bigKey = new byte[656]; // Assert Assert.Throws<FormatException>(() => config.EncryptionKey = smallKey); Assert.Throws<FormatException>(() => config.EncryptionKey = bigKey); } [Test] public void ValidEncryptionKeyAccepted() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("ValidEncryptionKeyAcceoted.realm"); var goldilocksKey = new byte[64]; // Assert Assert.DoesNotThrow(() => config.EncryptionKey = goldilocksKey); Assert.DoesNotThrow(() => config.EncryptionKey = null); } [Test] public void UnableToOpenWithNoKey() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("UnableToOpenWithNoKey.realm"); Realm.DeleteRealm(config); // ensure guarded from prev tests var emptyKey = new byte[64]; config.EncryptionKey = emptyKey; using (Realm.GetInstance(config)) { } config.EncryptionKey = null; // Assert Assert.Throws<RealmFileAccessErrorException>(() => { using (Realm.GetInstance(config)) { } }); } [Test] public void UnableToOpenWithKeyIfNotEncrypted() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("UnableToOpenWithKeyIfNotEncrypted.realm"); Realm.DeleteRealm(config); // ensure guarded from prev tests var openedWithoutKey = Realm.GetInstance(config); openedWithoutKey.Dispose(); var emptyKey = new byte[64]; config.EncryptionKey = emptyKey; // Assert Assert.Throws<RealmFileAccessErrorException>(() => { using (Realm.GetInstance(config)) { } }); } [Test] public void UnableToOpenWithDifferentKey() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("UnableToOpenWithDifferentKey.realm"); Realm.DeleteRealm(config); // ensure guarded from prev tests var emptyKey = new byte[64]; config.EncryptionKey = emptyKey; var openedWithKey = Realm.GetInstance(config); openedWithKey.Dispose(); config.EncryptionKey[0] = 42; // Assert Assert.Throws<RealmFileAccessErrorException>(() => { using (Realm.GetInstance(config)) { } }); } [Test] public void AbleToReopenEncryptedWithSameKey() { ReliesOnEncryption(); // Arrange var config = new RealmConfiguration("AbleToReopenEncryptedWithSameKey.realm"); Realm.DeleteRealm(config); // ensure guarded from prev tests var answerKey = new byte[64]; answerKey[0] = 42; config.EncryptionKey = answerKey; var openedWithKey = Realm.GetInstance(config); openedWithKey.Dispose(); var config2 = new RealmConfiguration("AbleToReopenEncryptedWithSameKey.realm"); var answerKey2 = new byte[64]; answerKey2[0] = 42; config2.EncryptionKey = answerKey2; // Assert Assert.DoesNotThrow(() => { using (Realm.GetInstance(config2)) { } }); } [Test] public void ReadOnlyFilesMustExist() { // Arrange var config = new RealmConfiguration("FileNotThere.realm") { IsReadOnly = true }; // Assert Assert.Throws<RealmFileNotFoundException>(() => { Realm.GetInstance(config); }); } [Test, Explicit("Currently, a RealmMismatchedConfigException is thrown. Registered as #580")] public void ReadOnlyRealmsWillNotAutoMigrate() { // Arrange var config = new RealmConfiguration("WillBeReadonly.realm"); Realm.DeleteRealm(config); // ensure start clean config.IsReadOnly = true; config.SchemaVersion = 42; TestHelpers.CopyBundledDatabaseToDocuments( "ForMigrationsToCopyAndMigrate.realm", "WillBeReadonly.realm"); // Assert Assert.Throws<RealmMigrationNeededException>(() => { Realm.GetInstance(config); }); } [Test] public void ReadOnlyRealmsArentWritable() { // Arrange var config = new RealmConfiguration("WillBeReadonly.realm"); Realm.DeleteRealm(config); // ensure start clean config.SchemaVersion = 0; // must set version before file can be opened readOnly using (var openToCreate = Realm.GetInstance(config)) { openToCreate.Write(() => { openToCreate.Add(new Person()); }); } config.IsReadOnly = true; using (var openedReadonly = Realm.GetInstance(config)) { // Assert Assert.Throws<RealmInvalidTransactionException>(() => { openedReadonly.Write(() => { openedReadonly.Add(new Person()); }); }); } } } }