context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Namespace: System.Web.UI.Util * Class: UrlUtils * * Author: Gaurav Vaish * Maintainer: gvaish@iitk.ac.in * Status: ??% * * (C) Gaurav Vaish (2001) */ using System; using System.Collections; using System.Text; using System.Web.SessionState; namespace System.Web.Util { internal class UrlUtils { /* * I could not find these functions in the class System.Uri * Besides, an instance of Uri will not be formed until and unless the address is of * the form protocol://[user:pass]host[:port]/[fullpath] * ie, a protocol, and that too without any blanks before, * is a must which may not be the case here. * Important: Escaped URL is assumed here. nothing like .aspx?path=/something * It should be .aspx?path=%2Fsomething */ public static string GetProtocol(string url) { //Taking code from Java Class java.net.URL if(url!=null) { if(url.Length>0) { int i, start = 0, limit; limit = url.Length; char c; bool aRef = false; while( (limit > 0) && (url[limit-1] <= ' ')) { limit --; } while( (start < limit) && (url[start] <= ' ')) { start++; } if(RegionMatches(true, url, start, "url:", 0, 4)) { start += 4; } if(start < url.Length && url[start]=='#') { aRef = true; } for(i = start; !aRef && (i < limit) && ((c=url[i]) != '/'); i++) { if(c==':') { return url.Substring(start, i - start); } } } } return String.Empty; } public static bool IsRelativeUrl(string url) { if (url.IndexOf(':') == -1) return !IsRooted(url); return false; } public static bool IsRootUrl(string url) { if(url!=null) { if(url.Length>0) { return IsValidProtocol(GetProtocol(url).ToLower()); } } return true; } public static bool IsRooted(string path) { if(path!=null && path.Length > 0) { return (path[0]=='/' || path[0]=='\\'); } return true; } public static void FailIfPhysicalPath(string path) { if(path!= null && path.Length > 1) { if(path[1]==':' || path.StartsWith(@"\\")) throw new HttpException(HttpRuntime.FormatResourceString("Physical_path_not_allowed", path)); } } public static string Combine (string basePath, string relPath) { if (relPath == null) throw new ArgumentNullException ("relPath"); int rlength = relPath.Length; if (rlength == 0) return ""; FailIfPhysicalPath (relPath); relPath = relPath.Replace ("\\", "/"); if (IsRooted (relPath)) return Reduce (relPath); char first = relPath [0]; if (rlength < 3 || first == '~' || first == '/' || first == '\\') { if (basePath == null || (basePath.Length == 1 && basePath [0] == '/')) basePath = String.Empty; string slash = (first == '/') ? "" : "/"; if (first == '~') { if (rlength == 1) { relPath = ""; } else if (rlength > 1 && relPath [1] == '/') { relPath = relPath.Substring (2); slash = "/"; } string appvpath = HttpRuntime.AppDomainAppVirtualPath; if (appvpath.EndsWith ("/")) slash = ""; return Reduce (appvpath + slash + relPath); } return Reduce (basePath + slash + relPath); } if (basePath == null || basePath == "" || basePath [0] == '~') basePath = HttpRuntime.AppDomainAppVirtualPath; if (basePath.Length <= 1) basePath = String.Empty; return Reduce (basePath + "/" + relPath); } public static bool IsValidProtocol(string protocol) { if(protocol.Length < 1) return false; char c = protocol[0]; if(!Char.IsLetter(c)) { return false; } for(int i=1; i < protocol.Length; i++) { c = protocol[i]; if(!Char.IsLetterOrDigit(c) && c!='.' && c!='+' && c!='-') { return false; } } return true; } /* * MakeRelative("http://www.foo.com/bar1/bar2/file","http://www.foo.com/bar1") * will return "bar2/file" * while MakeRelative("http://www.foo.com/bar1/...","http://www.anotherfoo.com") * return 'null' and so does the call * MakeRelative("http://www.foo.com/bar1/bar2","http://www.foo.com/bar") */ public static string MakeRelative(string fullUrl, string relativeTo) { if (fullUrl == relativeTo) return String.Empty; if (fullUrl.IndexOf (relativeTo) != 0) return null; string leftOver = fullUrl.Substring (relativeTo.Length); if (leftOver.Length > 0 && leftOver [0] == '/') leftOver = leftOver.Substring (1); leftOver = Reduce (leftOver); if (leftOver.Length > 0 && leftOver [0] == '/') leftOver = leftOver.Substring (1); return leftOver; } /* * Check JavaDocs for java.lang.String#RegionMatches(bool, int, String, int, int) * Could not find anything similar in the System.String class */ public static bool RegionMatches(bool ignoreCase, string source, int start, string match, int offset, int len) { if(source!=null || match!=null) { if(source.Length>0 && match.Length>0) { char[] ta = source.ToCharArray(); char[] pa = match.ToCharArray(); if((offset < 0) || (start < 0) || (start > (source.Length - len)) || (offset > (match.Length - len))) { return false; } while(len-- > 0) { char c1 = ta[start++]; char c2 = pa[offset++]; if(c1==c2) continue; if(ignoreCase) { if(Char.ToUpper(c1)==Char.ToUpper(c2)) continue; // Check for Gregorian Calendar where the above may not hold good if(Char.ToLower(c1)==Char.ToLower(c2)) continue; } return false; } return true; } } return false; } static char [] path_sep = {'\\', '/'}; public static string Reduce (string path) { string [] parts = path.Split (path_sep); int end = parts.Length; int dest = 0; for (int i = 0; i < end; i++) { string current = parts [i]; if (current == "." ) continue; if (current == "..") { if (dest == 0) { if (i == 1) // see bug 52599 continue; throw new HttpException ("Invalid path."); } dest --; continue; } parts [dest++] = current; } if (dest == 0) return "/"; return String.Join ("/", parts, 0, dest); } public static string GetDirectory(string url) { if(url==null) { return null; } if(url.Length==0) { return String.Empty; } url = url.Replace('\\','/'); string baseDir = ""; int last = url.LastIndexOf ('/'); if (last > 0) baseDir = url.Substring(0, url.LastIndexOf('/')); if(baseDir.Length==0) { baseDir = "/"; } return baseDir; } static string GetFile (string url) { if (url == null) return null; if (url.Length == 0) return String.Empty; url = url.Replace ('\\', '/'); int last = url.LastIndexOf ('/') + 1; if (last != 0) { url = url.Substring (last); } return url; } // appRoot + SessionID + vpath public static string InsertSessionId (string id, string path) { string dir = GetDirectory (path); if (!dir.EndsWith ("/")) dir += "/"; string appvpath = HttpRuntime.AppDomainAppVirtualPath; if (!appvpath.EndsWith ("/")) appvpath += "/"; if (path.StartsWith (appvpath)) path = path.Substring (appvpath.Length); if (path [0] == '/') path = path.Length > 1 ? path.Substring (1) : ""; return Reduce (appvpath + "(" + id + ")/" + path); } public static string GetSessionId (string path) { string appvpath = HttpRuntime.AppDomainAppVirtualPath; if (path.Length <= appvpath.Length) return null; path = path.Substring (appvpath.Length); if (path.Length == 0 || path [0] != '/') path = '/' + path; int len = path.Length; if ((len < SessionId.IdLength + 3) || (path [1] != '(') || (path [SessionId.IdLength + 2] != ')')) return null; return path.Substring (2, SessionId.IdLength); } public static string RemoveSessionId (string base_path, string file_path) { // Caller did a GetSessionId first int idx = base_path.IndexOf ("/("); string dir = base_path.Substring (0, idx + 1); if (!dir.EndsWith ("/")) dir += "/"; idx = base_path.IndexOf (")/"); if (idx != -1 && base_path.Length > idx + 2) { string dir2 = base_path.Substring (idx + 2); if (!dir2.EndsWith ("/")) dir2 += "/"; dir += dir2; } return Reduce (dir + GetFile (file_path)); } public static string ResolveVirtualPathFromAppAbsolute (string path) { if (path [0] != '~') return path; if (path.Length == 1) return HttpRuntime.AppDomainAppVirtualPath; if (path [1] == '/' || path [1] == '\\') { string appPath = HttpRuntime.AppDomainAppVirtualPath; if (appPath.Length > 1) return appPath + "/" + path.Substring (2); return "/" + path.Substring (2); } return path; } public static string ResolvePhysicalPathFromAppAbsolute (string path) { if (path [0] != '~') return path; if (path.Length == 1) return HttpRuntime.AppDomainAppPath; if (path [1] == '/' || path [1] == '\\') { string appPath = HttpRuntime.AppDomainAppPath; if (appPath.Length > 1) return appPath + "/" + path.Substring (2); return "/" + path.Substring (2); } return path; } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } private static bool GetDefaultIsAsync(SafeFileHandle handle) => handle.IsAsync ?? DefaultIsAsync; /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share, string originalPath) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } if (_mode == FileMode.Append) { // Jump to the end of the file if opened as Append. _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } else if (mode == FileMode.Create || mode == FileMode.Truncate) { // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated // if opened successfully. if (Interop.Sys.FTruncate(_fileHandle, 0) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error != Interop.Error.EBADF && errorInfo.Error != Interop.Error.EINVAL) { // We know the file descriptor is valid and we know the size argument to FTruncate is correct, // so if EBADF or EINVAL is returned, it means we're dealing with a special file that can't be // truncated. Ignore the error in such cases; in all others, throw. throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. case FileMode.Truncate: // We truncate the file after getting the lock break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: case FileMode.Create: // We truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.GetValueOrDefault(); } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (Exception e) when (IsIoRelatedException(e) && !disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } public override ValueTask DisposeAsync() { // On Unix, we don't have any special support for async I/O, simply queueing writes // rather than doing them synchronously. As such, if we're "using async I/O" and we // have something to flush, queue the call to Dispose, so that we end up queueing whatever // write work happens to flush the buffer. Otherwise, just delegate to the base implementation, // which will synchronously invoke Dispose. We don't need to factor in the current type // as we're using the virtual Dispose either way, and therefore factoring in whatever // override may already exist on a derived type. if (_useAsyncIO && _writePos > 0) { return new ValueTask(Task.Factory.StartNew(s => ((FileStream)s).Dispose(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); } return base.DisposeAsync(); } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer)) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="destination">The buffer to write the data into.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult) { Debug.Assert(_useAsyncIO); if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= destination.Length) { try { PrepareForReading(); new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span); _readPos += destination.Length; synchronousResult = destination.Length; return null; } catch (Exception exc) { synchronousResult = 0; return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. synchronousResult = 0; _asyncState.Memory = destination; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { Memory<byte> memory = thisRef._asyncState.Memory; thisRef._asyncState.Memory = default(Memory<byte>); return thisRef.ReadSpan(memory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(GetBuffer().AsSpan(_writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(GetBuffer().AsSpan(_writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &MemoryMarshal.GetReference(source)) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="source">The buffer to write data from.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private ValueTask WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); if (cancellationToken.IsCancellationRequested) return new ValueTask(Task.FromCanceled(cancellationToken)); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { try { PrepareForWriting(); source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length)); _writePos += source.Length; return default; } catch (Exception exc) { return new ValueTask(Task.FromException(exc)); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.ReadOnlyMemory = source; return new ValueTask(waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory; thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>); thisRef.WriteSpan(readOnlyMemory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default)); } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { internal ReadOnlyMemory<byte> ReadOnlyMemory; internal Memory<byte> Memory; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IO.Swagger.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string userAgent = "Swagger-Codegen/1.0.0/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap.Add(key, value); } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 2015-11-01\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
// 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. /*============================================================ ** ** Class: ResourceWriter ** ** ** ** Purpose: Default way to write strings to a CLR resource ** file. ** ** ===========================================================*/ using System.IO; using System.Text; using System.Collections.Generic; using System.Diagnostics; namespace System.Resources #if RESOURCES_EXTENSIONS .Extensions #endif { // Generates a binary .resources file in the system default format // from name and value pairs. Create one with a unique file name, // call AddResource() at least once, then call Generate() to write // the .resources file to disk, then call Dispose() to close the file. // // The resources generally aren't written out in the same order // they were added. // // See the RuntimeResourceSet overview for details on the system // default file format. // public sealed partial class #if RESOURCES_EXTENSIONS PreserializedResourceWriter #else ResourceWriter #endif : IResourceWriter { // An initial size for our internal sorted list, to avoid extra resizes. private const int AverageNameSize = 20 * 2; // chars in little endian Unicode private const int AverageValueSize = 40; internal const string ResourceReaderFullyQualifiedName = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; private const string ResSetTypeName = "System.Resources.RuntimeResourceSet"; private const int ResSetVersion = 2; private SortedDictionary<string, object> _resourceList; private Stream _output; private Dictionary<string, object> _caseInsensitiveDups; private Dictionary<string, PrecannedResource> _preserializedData; public #if RESOURCES_EXTENSIONS PreserializedResourceWriter(string fileName) #else ResourceWriter(string fileName) #endif { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); _output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); _resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default); _caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } public #if RESOURCES_EXTENSIONS PreserializedResourceWriter(Stream stream) #else ResourceWriter(Stream stream) #endif { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); _output = stream; _resourceList = new SortedDictionary<string, object>(FastResourceComparer.Default); _caseInsensitiveDups = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } // Adds a string resource to the list of resources to be written to a file. // They aren't written until Generate() is called. // public void AddResource(string name, string value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, value); } // Adds a resource of type Object to the list of resources to be // written to a file. They aren't written until Generate() is called. // public void AddResource(string name, object value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); // needed for binary compat if (value != null && value is Stream) { AddResourceInternal(name, (Stream)value, false); } else { // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, value); } } // Adds a resource of type Stream to the list of resources to be // written to a file. They aren't written until Generate() is called. // closeAfterWrite parameter indicates whether to close the stream when done. // public void AddResource(string name, Stream value, bool closeAfterWrite = false) { if (name == null) throw new ArgumentNullException(nameof(name)); if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); AddResourceInternal(name, value, closeAfterWrite); } private void AddResourceInternal(string name, Stream value, bool closeAfterWrite) { if (value == null) { // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, value); } else { // make sure the Stream is seekable if (!value.CanSeek) throw new ArgumentException(SR.NotSupported_UnseekableStream); // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, new StreamWrapper(value, closeAfterWrite)); } } // Adds a named byte array as a resource to the list of resources to // be written to a file. They aren't written until Generate() is called. // public void AddResource(string name, byte[] value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); _resourceList.Add(name, value); } private void AddResourceData(string name, string typeName, object data) { if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); // Check for duplicate resources whose names vary only by case. _caseInsensitiveDups.Add(name, null); if (_preserializedData == null) _preserializedData = new Dictionary<string, PrecannedResource>(FastResourceComparer.Default); _preserializedData.Add(name, new PrecannedResource(typeName, data)); } // For cases where users can't create an instance of the deserialized // type in memory, and need to pass us serialized blobs instead. // LocStudio's managed code parser will do this in some cases. private class PrecannedResource { internal readonly string TypeName; internal readonly object Data; internal PrecannedResource(string typeName, object data) { TypeName = typeName; Data = data; } } private class StreamWrapper { internal readonly Stream Stream; internal readonly bool CloseAfterWrite; internal StreamWrapper(Stream s, bool closeAfterWrite) { Stream = s; CloseAfterWrite = closeAfterWrite; } } public void Close() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { if (_resourceList != null) { Generate(); } if (_output != null) { _output.Dispose(); } } _output = null; _caseInsensitiveDups = null; } public void Dispose() { Dispose(true); } // After calling AddResource, Generate() writes out all resources to the // output stream in the system default format. // If an exception occurs during object serialization or during IO, // the .resources file is closed and deleted, since it is most likely // invalid. public void Generate() { if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8); List<string> typeNames = new List<string>(); // Write out the ResourceManager header // Write out magic number bw.Write(ResourceManager.MagicNumber); // Write out ResourceManager header version number bw.Write(ResourceManager.HeaderVersionNumber); MemoryStream resMgrHeaderBlob = new MemoryStream(240); BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob); // Write out class name of IResourceReader capable of handling // this file. resMgrHeaderPart.Write(ResourceReaderTypeName); // Write out class name of the ResourceSet class best suited to // handling this file. // This needs to be the same even with multi-targeting. It's the // full name -- not the assembly qualified name. resMgrHeaderPart.Write(ResourceSetTypeName); resMgrHeaderPart.Flush(); // Write number of bytes to skip over to get past ResMgr header bw.Write((int)resMgrHeaderBlob.Length); // Write the rest of the ResMgr header Debug.Assert(resMgrHeaderBlob.Length > 0, "ResourceWriter: Expected non empty header"); resMgrHeaderBlob.Seek(0, SeekOrigin.Begin); resMgrHeaderBlob.CopyTo(bw.BaseStream, (int)resMgrHeaderBlob.Length); // End ResourceManager header // Write out the RuntimeResourceSet header // Version number bw.Write(ResSetVersion); // number of resources int numResources = _resourceList.Count; if (_preserializedData != null) numResources += _preserializedData.Count; bw.Write(numResources); // Store values in temporary streams to write at end of file. int[] nameHashes = new int[numResources]; int[] namePositions = new int[numResources]; int curNameNumber = 0; MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize); BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode); Stream dataSection = new MemoryStream(); // Either a FileStream or a MemoryStream using (dataSection) { BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8); if (_preserializedData != null) { foreach (KeyValuePair<string, PrecannedResource> entry in _preserializedData) { _resourceList.Add(entry.Key, entry.Value); } } // Write resource name and position to the file, and the value // to our temporary buffer. Save Type as well. foreach (var item in _resourceList) { nameHashes[curNameNumber] = FastResourceComparer.HashFunction(item.Key); namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current); names.Write(item.Key); // key names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value. object value = item.Value; ResourceTypeCode typeCode = FindTypeCode(value, typeNames); // Write out type code Write7BitEncodedInt(data, (int)typeCode); var userProvidedResource = value as PrecannedResource; if (userProvidedResource != null) { WriteData(data, userProvidedResource.Data); } else { WriteValue(typeCode, value, data); } } // At this point, the ResourceManager header has been written. // Finish RuntimeResourceSet header // The reader expects a list of user defined type names // following the size of the list, write 0 for this // writer implementation bw.Write(typeNames.Count); foreach (var typeName in typeNames) { bw.Write(typeName); } // Write out the name-related items for lookup. // Note that the hash array and the namePositions array must // be sorted in parallel. Array.Sort(nameHashes, namePositions); // Prepare to write sorted name hashes (alignment fixup) // Note: For 64-bit machines, these MUST be aligned on 8 byte // boundaries! Pointers on IA64 must be aligned! And we'll // run faster on X86 machines too. bw.Flush(); int alignBytes = ((int)bw.BaseStream.Position) & 7; if (alignBytes > 0) { for (int i = 0; i < 8 - alignBytes; i++) bw.Write("PAD"[i % 3]); } // Write out sorted name hashes. // Align to 8 bytes. Debug.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!"); foreach (int hash in nameHashes) { bw.Write(hash); } // Write relative positions of all the names in the file. // Note: this data is 4 byte aligned, occurring immediately // after the 8 byte aligned name hashes (whose length may // potentially be odd). Debug.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!"); foreach (int pos in namePositions) { bw.Write(pos); } // Flush all BinaryWriters to their underlying streams. bw.Flush(); names.Flush(); data.Flush(); // Write offset to data section int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length); startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header bw.Write(startOfDataSection); // Write name section. if (nameSection.Length > 0) { nameSection.Seek(0, SeekOrigin.Begin); nameSection.CopyTo(bw.BaseStream, (int)nameSection.Length); } names.Dispose(); // Write data section. Debug.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!"); dataSection.Position = 0; dataSection.CopyTo(bw.BaseStream); data.Dispose(); } // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose bw.Flush(); // Indicate we've called Generate _resourceList = null; } private static void Write7BitEncodedInt(BinaryWriter store, int value) { Debug.Assert(store != null); // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint)value; // support negative numbers while (v >= 0x80) { store.Write((byte)(v | 0x80)); v >>= 7; } store.Write((byte)v); } // Finds the ResourceTypeCode for a type, or adds this type to the // types list. private ResourceTypeCode FindTypeCode(object value, List<string> types) { if (value == null) return ResourceTypeCode.Null; Type type = value.GetType(); if (type == typeof(string)) return ResourceTypeCode.String; else if (type == typeof(int)) return ResourceTypeCode.Int32; else if (type == typeof(bool)) return ResourceTypeCode.Boolean; else if (type == typeof(char)) return ResourceTypeCode.Char; else if (type == typeof(byte)) return ResourceTypeCode.Byte; else if (type == typeof(sbyte)) return ResourceTypeCode.SByte; else if (type == typeof(short)) return ResourceTypeCode.Int16; else if (type == typeof(long)) return ResourceTypeCode.Int64; else if (type == typeof(ushort)) return ResourceTypeCode.UInt16; else if (type == typeof(uint)) return ResourceTypeCode.UInt32; else if (type == typeof(ulong)) return ResourceTypeCode.UInt64; else if (type == typeof(float)) return ResourceTypeCode.Single; else if (type == typeof(double)) return ResourceTypeCode.Double; else if (type == typeof(decimal)) return ResourceTypeCode.Decimal; else if (type == typeof(DateTime)) return ResourceTypeCode.DateTime; else if (type == typeof(TimeSpan)) return ResourceTypeCode.TimeSpan; else if (type == typeof(byte[])) return ResourceTypeCode.ByteArray; else if (type == typeof(StreamWrapper)) return ResourceTypeCode.Stream; // This is a user type, or a precanned resource. Find type // table index. If not there, add new element. string typeName; if (type == typeof(PrecannedResource)) { typeName = ((PrecannedResource)value).TypeName; if (typeName.StartsWith("ResourceTypeCode.", StringComparison.Ordinal)) { typeName = typeName.Substring(17); // Remove through '.' ResourceTypeCode typeCode = (ResourceTypeCode)Enum.Parse(typeof(ResourceTypeCode), typeName); return typeCode; } } else { // not a preserialized resource throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources); } int typeIndex = types.IndexOf(typeName); if (typeIndex == -1) { typeIndex = types.Count; types.Add(typeName); } return (ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes); } private void WriteValue(ResourceTypeCode typeCode, object value, BinaryWriter writer) { Debug.Assert(writer != null); switch (typeCode) { case ResourceTypeCode.Null: break; case ResourceTypeCode.String: writer.Write((string)value); break; case ResourceTypeCode.Boolean: writer.Write((bool)value); break; case ResourceTypeCode.Char: writer.Write((ushort)(char)value); break; case ResourceTypeCode.Byte: writer.Write((byte)value); break; case ResourceTypeCode.SByte: writer.Write((sbyte)value); break; case ResourceTypeCode.Int16: writer.Write((short)value); break; case ResourceTypeCode.UInt16: writer.Write((ushort)value); break; case ResourceTypeCode.Int32: writer.Write((int)value); break; case ResourceTypeCode.UInt32: writer.Write((uint)value); break; case ResourceTypeCode.Int64: writer.Write((long)value); break; case ResourceTypeCode.UInt64: writer.Write((ulong)value); break; case ResourceTypeCode.Single: writer.Write((float)value); break; case ResourceTypeCode.Double: writer.Write((double)value); break; case ResourceTypeCode.Decimal: writer.Write((decimal)value); break; case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. long data = ((DateTime)value).ToBinary(); writer.Write(data); break; case ResourceTypeCode.TimeSpan: writer.Write(((TimeSpan)value).Ticks); break; // Special Types case ResourceTypeCode.ByteArray: { byte[] bytes = (byte[])value; writer.Write(bytes.Length); writer.Write(bytes, 0, bytes.Length); break; } case ResourceTypeCode.Stream: { StreamWrapper sw = (StreamWrapper)value; if (sw.Stream.GetType() == typeof(MemoryStream)) { MemoryStream ms = (MemoryStream)sw.Stream; if (ms.Length > int.MaxValue) throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength); byte[] arr = ms.ToArray(); writer.Write(arr.Length); writer.Write(arr, 0, arr.Length); } else { Stream s = sw.Stream; // we've already verified that the Stream is seekable if (s.Length > int.MaxValue) throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength); s.Position = 0; writer.Write((int)s.Length); byte[] buffer = new byte[4096]; int read = 0; while ((read = s.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer, 0, read); } if (sw.CloseAfterWrite) { s.Close(); } } break; } default: Debug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, $"ResourceReader: Unsupported ResourceTypeCode in .resources file! {typeCode}"); throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources); } } } }
// Commons.GetOptions // // Copyright (c) 2002-2015 Rafael 'Monoman' Teixeira, Managed Commons Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using static System.Console; using static Commons.Translation.TranslationService; namespace Commons.GetOptions { public enum WhatToDoNext { AbandonProgram, GoAhead } internal enum OptionProcessingResult { NotThisOption, OptionAlone, OptionConsumedParameter } internal class OptionDetails : IComparable { public string AlternateForm; public bool BooleanOption; public bool DontSplitOnCommas; public bool Hidden; public string LongForm; public int MaxOccurs; public MemberInfo MemberInfo; public bool NeedsParameter; public OptionDetails NextAlternate = null; public int Occurs;// negative means there is no limit public object OptionBundle; public Type ParameterType; public string paramName = null; public OptionsParsingMode ParsingMode; public bool SecondLevelHelp; public string ShortDescription; public char ShortForm; public ArrayList Values; public bool VBCStyleBoolean; static OptionDetails() { RegisterTranslator(new Translator()); } public OptionDetails( MemberInfo memberInfo, OptionAttribute option, object optionBundle, OptionsParsingMode parsingMode, bool dontSplitOnCommas ) { ShortForm = option.ShortForm; ParsingMode = parsingMode; DontSplitOnCommas = dontSplitOnCommas; if (string.IsNullOrWhiteSpace(option.Name)) LongForm = (ShortForm == default(char)) ? memberInfo.Name : string.Empty; else LongForm = option.Name; AlternateForm = option.AlternateForm; ShortDescription = ExtractParamName(option.TranslatedDescription); Occurs = 0; OptionBundle = optionBundle; BooleanOption = false; MemberInfo = memberInfo; NeedsParameter = false; Values = null; MaxOccurs = 1; VBCStyleBoolean = option.VBCStyleBoolean; SecondLevelHelp = option.SecondLevelHelp; Hidden = false; // TODO: check other attributes ParameterType = TypeOfMember(memberInfo); var NonDefaultMessage = string.Format("MaxOccurs set to non default value ({0}) for a [{1}] option", option.MaxOccurs, MemberInfo); if (ParameterType != null) { if (ParameterType.FullName != "System.Boolean") { if (LongForm.IndexOf(':') >= 0) throw new InvalidOperationException(string.Format("Options with an embedded colon (':') in their visible name must be boolean!!! [{0} isn't]", MemberInfo)); NeedsParameter = true; if (option.MaxOccurs != 1) { if (ParameterType.IsArray) { Values = new ArrayList(); MaxOccurs = option.MaxOccurs; } else { if (MemberInfo is MethodInfo || MemberInfo is PropertyInfo) MaxOccurs = option.MaxOccurs; else throw new InvalidOperationException(NonDefaultMessage); } } } else { BooleanOption = true; if (option.MaxOccurs != 1) { if (MemberInfo is MethodInfo || MemberInfo is PropertyInfo) MaxOccurs = option.MaxOccurs; else throw new InvalidOperationException(NonDefaultMessage); } } } } public string DefaultForm { get { string shortPrefix = "-"; string longPrefix = "--"; if (ParsingMode == OptionsParsingMode.Windows) { shortPrefix = "/"; longPrefix = "/"; } return ShortForm != default(char) ? shortPrefix + ShortForm : longPrefix + LongForm; } } public string ParamName => paramName; public static void LinkAlternatesInsideList(List<OptionDetails> list) { var baseForms = new Hashtable(list.Count); foreach (OptionDetails option in list) { if (option.LongForm != null && option.LongForm.Trim().Length > 0) { string[] parts = option.LongForm.Split(':'); if (parts.Length < 2) { baseForms.Add(option.LongForm, option); } else { var baseForm = (OptionDetails)baseForms[parts[0]]; if (baseForm != null) { // simple linked list option.NextAlternate = baseForm.NextAlternate; baseForm.NextAlternate = option; } } } } } int IComparable.CompareTo(object other) => string.Compare(Key, ((OptionDetails)other).Key, StringComparison.Ordinal); public OptionProcessingResult ProcessArgument(string arg, string nextArg) { if (IsAlternate(arg + ":" + nextArg)) return OptionProcessingResult.NotThisOption; if (IsThisOption(arg)) { if (!NeedsParameter) { if (VBCStyleBoolean && arg.EndsWith("-", StringComparison.Ordinal)) DoIt(false); else DoIt(true); return OptionProcessingResult.OptionAlone; } DoIt(nextArg); return OptionProcessingResult.OptionConsumedParameter; } if (IsThisOption(arg + ":" + nextArg)) { DoIt(true); return OptionProcessingResult.OptionConsumedParameter; } return OptionProcessingResult.NotThisOption; } public override string ToString() { if (optionHelp == null) { string shortPrefix; string longPrefix; bool hasLongForm = (LongForm != null && LongForm != string.Empty); if (ParsingMode == OptionsParsingMode.Windows) { shortPrefix = "/"; longPrefix = "/"; } else { shortPrefix = "-"; longPrefix = "--"; } optionHelp = " "; optionHelp += (ShortForm != default(char)) ? shortPrefix + ShortForm + " " : " "; optionHelp += hasLongForm ? longPrefix + LongForm : ""; if (NeedsParameter) { if (hasLongForm) optionHelp += ":"; optionHelp += ParamName; } else if (BooleanOption && VBCStyleBoolean) { optionHelp += "[+|-]"; } optionHelp += "\t"; if (AlternateForm != string.Empty && AlternateForm != null) optionHelp += _("Also ") + shortPrefix + AlternateForm + (NeedsParameter ? (":" + ParamName) : "") + ". "; optionHelp += ShortDescription; } return optionHelp; } public void TransferValues() { if (Values != null) { if (MemberInfo is FieldInfo) { ((FieldInfo)MemberInfo).SetValue(OptionBundle, Values.ToArray(ParameterType.GetElementType())); return; } if (MemberInfo is PropertyInfo) { ((PropertyInfo)MemberInfo).SetValue(OptionBundle, Values.ToArray(ParameterType.GetElementType()), null); return; } if ((WhatToDoNext)((MethodInfo)MemberInfo).Invoke(OptionBundle, new object[] { Values.ToArray(ParameterType.GetElementType()) }) == WhatToDoNext.AbandonProgram) System.Environment.Exit(1); } } internal string Key => (ShortForm == default(char)) ? LongForm : ShortForm + " " + LongForm; private string optionHelp = null; bool AddingOneMoreExceedsMaxOccurs => HowManyBeforeExceedingMaxOccurs(1) < 1; static System.Type TypeOfMember(MemberInfo memberInfo) { if ((memberInfo.MemberType == MemberTypes.Field && memberInfo is FieldInfo)) return ((FieldInfo)memberInfo).FieldType; if ((memberInfo.MemberType == MemberTypes.Property && memberInfo is PropertyInfo)) return ((PropertyInfo)memberInfo).PropertyType; if ((memberInfo.MemberType == MemberTypes.Method && memberInfo is MethodInfo)) { if (((MethodInfo)memberInfo).ReturnType.FullName != typeof(WhatToDoNext).FullName) throw new NotSupportedException("Option method must return '" + typeof(WhatToDoNext).FullName + "'"); ParameterInfo[] parameters = ((MethodInfo)memberInfo).GetParameters(); return (parameters == null) || (parameters.Length == 0) ? null : parameters[0].ParameterType; } throw new NotSupportedException("'" + memberInfo.MemberType + "' memberType is not supported"); } void DoIt(bool setValue) { if (AddingOneMoreExceedsMaxOccurs) return; if (MemberInfo is FieldInfo) { ((FieldInfo)MemberInfo).SetValue(OptionBundle, setValue); return; } if (MemberInfo is PropertyInfo) { ((PropertyInfo)MemberInfo).SetValue(OptionBundle, setValue, null); return; } if ((WhatToDoNext)((MethodInfo)MemberInfo).Invoke(OptionBundle, null) == WhatToDoNext.AbandonProgram) System.Environment.Exit(1); } void DoIt(string parameterValue) { if (parameterValue == null) parameterValue = ""; string[] parameterValues; if (DontSplitOnCommas || MaxOccurs == 1) parameterValues = new string[] { parameterValue }; else parameterValues = parameterValue.Split(','); int waitingToBeProcessed = HowManyBeforeExceedingMaxOccurs(parameterValues.Length); foreach (string parameter in parameterValues) { if (waitingToBeProcessed-- <= 0) break; object convertedParameter = null; if (Values != null && parameter != null) { try { convertedParameter = Convert.ChangeType(parameter, ParameterType.GetElementType()); } catch (Exception ex) { ReportBadConversion(parameter, ex); } Values.Add(convertedParameter); continue; } if (parameter != null) { try { convertedParameter = Convert.ChangeType(parameter, ParameterType); } catch (Exception ex) { ReportBadConversion(parameter, ex); continue; } } if (MemberInfo is FieldInfo) { ((FieldInfo)MemberInfo).SetValue(OptionBundle, convertedParameter); continue; } if (MemberInfo is PropertyInfo) { ((PropertyInfo)MemberInfo).SetValue(OptionBundle, convertedParameter, null); continue; } if ((WhatToDoNext)((MethodInfo)MemberInfo).Invoke(OptionBundle, new object[] { convertedParameter }) == WhatToDoNext.AbandonProgram) System.Environment.Exit(1); } } string ExtractParamName(string shortDescription) { int whereBegins = shortDescription.IndexOf("{", StringComparison.Ordinal); if (whereBegins < 0) paramName = _("PARAM"); else { int whereEnds = shortDescription.IndexOf("}", StringComparison.Ordinal); if (whereEnds < whereBegins) whereEnds = shortDescription.Length + 1; paramName = shortDescription.Substring(whereBegins + 1, whereEnds - whereBegins - 1); shortDescription = shortDescription.Substring(0, whereBegins) + paramName + shortDescription.Substring(whereEnds + 1); } return shortDescription; } int HowManyBeforeExceedingMaxOccurs(int howMany) { if (MaxOccurs > 0 && (Occurs + howMany) > MaxOccurs) { Error.WriteLine(TranslateAndFormat("Option {0} can be used at most {1} times. Ignoring extras...", LongForm, MaxOccurs)); howMany = MaxOccurs - Occurs; } Occurs += howMany; return howMany; } bool IsAlternate(string compoundArg) { OptionDetails next = NextAlternate; while (next != null) { if (next.IsThisOption(compoundArg)) return true; next = next.NextAlternate; } return false; } bool IsThisOption(string arg) { if (arg != null && arg != string.Empty) { arg = arg.TrimStart('-', '/'); if (VBCStyleBoolean) arg = arg.TrimEnd('-', '+'); return (MatchShortForm(arg) || arg == LongForm || arg == AlternateForm); } return false; } bool MatchShortForm(string arg) => arg.Length == 1 && arg[0] == ShortForm; void ReportBadConversion(string parameter, Exception ex) { WriteLine(TranslateAndFormat("The value '{0}' is not convertible to the appropriate type '{1}' for the {2} option (reason '{3}')", parameter, ParameterType.Name, DefaultForm, ex.Message)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// DisksOperations operations. /// </summary> public partial interface IDisksOperations { /// <summary> /// List disks in a given user profile. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Disk>>> ListWithHttpMessagesAsync(string labName, string userName, ODataQuery<Disk> odataQuery = default(ODataQuery<Disk>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get disk. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='expand'> /// Specify the $expand query. Example: 'properties($select=diskType)' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<Disk>> GetWithHttpMessagesAsync(string labName, string userName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or replace an existing disk. This operation can take a /// while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='disk'> /// A Disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<Disk>> CreateOrUpdateWithHttpMessagesAsync(string labName, string userName, string name, Disk disk, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or replace an existing disk. This operation can take a /// while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='disk'> /// A Disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<Disk>> BeginCreateOrUpdateWithHttpMessagesAsync(string labName, string userName, string name, Disk disk, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete disk. This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string userName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete disk. This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string labName, string userName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Attach and create the lease of the disk to the virtual machine. /// This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='attachDiskProperties'> /// Properties of the disk to attach. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> AttachWithHttpMessagesAsync(string labName, string userName, string name, AttachDiskProperties attachDiskProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Attach and create the lease of the disk to the virtual machine. /// This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='attachDiskProperties'> /// Properties of the disk to attach. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginAttachWithHttpMessagesAsync(string labName, string userName, string name, AttachDiskProperties attachDiskProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Detach and break the lease of the disk attached to the virtual /// machine. This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='detachDiskProperties'> /// Properties of the disk to detach. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DetachWithHttpMessagesAsync(string labName, string userName, string name, DetachDiskProperties detachDiskProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Detach and break the lease of the disk attached to the virtual /// machine. This operation can take a while to complete. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='userName'> /// The name of the user profile. /// </param> /// <param name='name'> /// The name of the disk. /// </param> /// <param name='detachDiskProperties'> /// Properties of the disk to detach. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDetachWithHttpMessagesAsync(string labName, string userName, string name, DetachDiskProperties detachDiskProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List disks in a given user profile. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<Disk>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.Monitor.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Monitor Management Client /// </summary> public partial class MonitorManagementClient : ServiceClient<MonitorManagementClient>, IMonitorManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The Azure subscription Id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAutoscaleSettingsOperations. /// </summary> public virtual IAutoscaleSettingsOperations AutoscaleSettings { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the IAlertRuleIncidentsOperations. /// </summary> public virtual IAlertRuleIncidentsOperations AlertRuleIncidents { get; private set; } /// <summary> /// Gets the IAlertRulesOperations. /// </summary> public virtual IAlertRulesOperations AlertRules { get; private set; } /// <summary> /// Gets the ILogProfilesOperations. /// </summary> public virtual ILogProfilesOperations LogProfiles { get; private set; } /// <summary> /// Gets the IDiagnosticSettingsOperations. /// </summary> public virtual IDiagnosticSettingsOperations DiagnosticSettings { get; private set; } /// <summary> /// Gets the IDiagnosticSettingsCategoryOperations. /// </summary> public virtual IDiagnosticSettingsCategoryOperations DiagnosticSettingsCategory { get; private set; } /// <summary> /// Gets the IActionGroupsOperations. /// </summary> public virtual IActionGroupsOperations ActionGroups { get; private set; } /// <summary> /// Gets the IActivityLogAlertsOperations. /// </summary> public virtual IActivityLogAlertsOperations ActivityLogAlerts { get; private set; } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MonitorManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MonitorManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MonitorManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MonitorManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { AutoscaleSettings = new AutoscaleSettingsOperations(this); Operations = new Operations(this); AlertRuleIncidents = new AlertRuleIncidentsOperations(this); AlertRules = new AlertRulesOperations(this); LogProfiles = new LogProfilesOperations(this); DiagnosticSettings = new DiagnosticSettingsOperations(this); DiagnosticSettingsCategory = new DiagnosticSettingsCategoryOperations(this); ActionGroups = new ActionGroupsOperations(this); ActivityLogAlerts = new ActivityLogAlertsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleDataSource>("odata.type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleDataSource>("odata.type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleCondition>("odata.type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleCondition>("odata.type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleAction>("odata.type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleAction>("odata.type")); CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using MailGun.Data; namespace MailGun.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc3") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("MailGun.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Signum.Utilities; using System.Collections; using Signum.Entities; using System.Threading; using System.Threading.Tasks; using Signum.Engine.Connection; namespace Signum.Engine.Linq { public interface ITranslateResult { string CleanCommandText(); SqlPreCommandSimple MainCommand { get; set; } object? Execute(); Task<object?> ExecuteAsync(CancellationToken token); LambdaExpression GetMainProjector(); } interface IChildProjection { LookupToken Token { get; } void Fill(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever); Task FillAsync(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever, CancellationToken token); SqlPreCommandSimple Command { get; } bool IsLazy { get; } } class EagerChildProjection<K, V>: IChildProjection { public LookupToken Token { get; set; } public SqlPreCommandSimple Command { get; set; } internal Expression<Func<IProjectionRow, KeyValuePair<K, V>>> ProjectorExpression; public EagerChildProjection(LookupToken token, SqlPreCommandSimple command, Expression<Func<IProjectionRow, KeyValuePair<K, V>>> projectorExpression) { Token = token; Command = command; ProjectorExpression = projectorExpression; } public void Fill(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever) { using (HeavyProfiler.Log("SQL", () => Command.sp_executesql())) using (var reader = Executor.UnsafeExecuteDataReader(Command)) { ProjectionRowEnumerator<KeyValuePair<K, V>> enumerator = new ProjectionRowEnumerator<KeyValuePair<K, V>>(reader.Reader, ProjectorExpression, lookups, retriever, CancellationToken.None); IEnumerable<KeyValuePair<K, V>> enumerabe = new ProjectionRowEnumerable<KeyValuePair<K, V>>(enumerator); try { var lookUp = enumerabe.ToLookup(a => a.Key, a => a.Value); lookups.Add(Token, lookUp); } catch (Exception ex) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = Command; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } } public async Task FillAsync(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever, CancellationToken token) { using (HeavyProfiler.Log("SQL", () => Command.sp_executesql())) using (var reader = await Executor.UnsafeExecuteDataReaderAsync(Command, token: token)) { ProjectionRowEnumerator<KeyValuePair<K, V>> enumerator = new ProjectionRowEnumerator<KeyValuePair<K, V>>(reader.Reader, ProjectorExpression, lookups, retriever, token); IEnumerable<KeyValuePair<K, V>> enumerabe = new ProjectionRowEnumerable<KeyValuePair<K, V>>(enumerator); try { var lookUp = enumerabe.ToLookup(a => a.Key, a => a.Value); lookups.Add(Token, lookUp); } catch (Exception ex) when (!(ex is OperationCanceledException)) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = Command; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } } public bool IsLazy { get { return false; } } } class LazyChildProjection<K, V> : IChildProjection where K : notnull { public LookupToken Token { get; } public SqlPreCommandSimple Command { get; } internal Expression<Func<IProjectionRow, KeyValuePair<K, MList<V>.RowIdElement>>> ProjectorExpression; public LazyChildProjection(LookupToken token, SqlPreCommandSimple command, Expression<Func<IProjectionRow, KeyValuePair<K, MList<V>.RowIdElement>>> projectorExpression) { Token = token; Command = command; ProjectorExpression = projectorExpression; } public void Fill(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever) { Dictionary<K, MList<V>>? requests = (Dictionary<K, MList<V>>?)lookups.TryGetC(Token); if (requests == null) return; using (HeavyProfiler.Log("SQL", () => Command.sp_executesql())) using (var reader = Executor.UnsafeExecuteDataReader(Command)) { ProjectionRowEnumerator<KeyValuePair<K, MList<V>.RowIdElement>> enumerator = new ProjectionRowEnumerator<KeyValuePair<K, MList<V>.RowIdElement>>(reader.Reader, ProjectorExpression, lookups, retriever, CancellationToken.None); IEnumerable<KeyValuePair<K, MList<V>.RowIdElement>> enumerabe = new ProjectionRowEnumerable<KeyValuePair<K, MList<V>.RowIdElement>>(enumerator); try { var lookUp = enumerabe.ToLookup(a => a.Key, a => a.Value); foreach (var kvp in requests) { var results = lookUp[kvp.Key]; ((IMListPrivate<V>)kvp.Value).InnerList.AddRange(results); ((IMListPrivate<V>)kvp.Value).InnerListModified(results.Select(a => a.Element).ToList(), null); retriever.ModifiablePostRetrieving(kvp.Value); } } catch (Exception ex) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = Command; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } } public async Task FillAsync(Dictionary<LookupToken, IEnumerable> lookups, IRetriever retriever, CancellationToken token) { Dictionary<K, MList<V>>? requests = (Dictionary<K, MList<V>>?)lookups.TryGetC(Token); if (requests == null) return; using (HeavyProfiler.Log("SQL", () => Command.sp_executesql())) using (var reader = await Executor.UnsafeExecuteDataReaderAsync(Command, token: token)) { ProjectionRowEnumerator<KeyValuePair<K, MList<V>.RowIdElement>> enumerator = new ProjectionRowEnumerator<KeyValuePair<K, MList<V>.RowIdElement>>(reader.Reader, ProjectorExpression, lookups, retriever, token); IEnumerable<KeyValuePair<K, MList<V>.RowIdElement>> enumerabe = new ProjectionRowEnumerable<KeyValuePair<K, MList<V>.RowIdElement>>(enumerator); try { var lookUp = enumerabe.ToLookup(a => a.Key, a => a.Value); foreach (var kvp in requests) { var results = lookUp[kvp.Key]; ((IMListPrivate<V>)kvp.Value).AssignMList(results.ToList()); ((IMListPrivate<V>)kvp.Value).InnerListModified(results.Select(a => a.Element).ToList(), null); retriever.ModifiablePostRetrieving(kvp.Value); } } catch (Exception ex) when (!(ex is OperationCanceledException)) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = Command; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } } public bool IsLazy { get { return true; } } } class TranslateResult<T> : ITranslateResult { public UniqueFunction? Unique { get; set; } internal List<IChildProjection> EagerProjections { get; set; } internal List<IChildProjection> LazyChildProjections { get; set; } public SqlPreCommandSimple MainCommand { get; set; } internal Expression<Func<IProjectionRow, T>> ProjectorExpression; public TranslateResult( List<IChildProjection> eagerProjections, List<IChildProjection> lazyChildProjections, SqlPreCommandSimple mainCommand, Expression<Func<IProjectionRow, T>> projectorExpression, UniqueFunction? unique) { EagerProjections = eagerProjections; LazyChildProjections = lazyChildProjections; MainCommand = mainCommand; ProjectorExpression = projectorExpression; Unique = unique; } public object? Execute() { return SqlServerRetry.Retry(() => { using (new EntityCache()) using (Transaction tr = new Transaction()) { object? result; using (var retriever = EntityCache.NewRetriever()) { var lookups = new Dictionary<LookupToken, IEnumerable>(); foreach (var child in EagerProjections) child.Fill(lookups, retriever); using (HeavyProfiler.Log("SQL", () => MainCommand.sp_executesql())) using (var reader = Executor.UnsafeExecuteDataReader(MainCommand)) { ProjectionRowEnumerator<T> enumerator = new ProjectionRowEnumerator<T>(reader.Reader, ProjectorExpression, lookups, retriever, CancellationToken.None); IEnumerable<T> enumerable = new ProjectionRowEnumerable<T>(enumerator); try { if (Unique == null) result = enumerable.ToList(); else result = UniqueMethod(enumerable, Unique.Value); } catch (Exception ex) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = MainCommand; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } foreach (var child in LazyChildProjections) child.Fill(lookups, retriever); retriever.CompleteAll(); } return tr.Commit(result); } }); } public Task<object?> ExecuteAsync(CancellationToken token) { return SqlServerRetry.RetryAsync(async () => { using (new EntityCache()) using (Transaction tr = new Transaction()) { object? result; using (var retriever = EntityCache.NewRetriever()) { var lookups = new Dictionary<LookupToken, IEnumerable>(); foreach (var child in EagerProjections) await child.FillAsync(lookups, retriever, token); using (HeavyProfiler.Log("SQL", () => MainCommand.sp_executesql())) using (var reader = await Executor.UnsafeExecuteDataReaderAsync(MainCommand, token: token)) { ProjectionRowEnumerator<T> enumerator = new ProjectionRowEnumerator<T>(reader.Reader, ProjectorExpression, lookups, retriever, token); IEnumerable<T> enumerable = new ProjectionRowEnumerable<T>(enumerator); try { if (Unique == null) result = enumerable.ToList(); else result = UniqueMethod(enumerable, Unique.Value); } catch (Exception ex) when (!(ex is OperationCanceledException)) { FieldReaderException fieldEx = enumerator.Reader.CreateFieldReaderException(ex); fieldEx.Command = MainCommand; fieldEx.Row = enumerator.Row; fieldEx.Projector = ProjectorExpression; throw fieldEx; } } foreach (var child in LazyChildProjections) await child.FillAsync(lookups, retriever, token); retriever.CompleteAll(); } return tr.Commit(result); } }); } internal T UniqueMethod(IEnumerable<T> enumerable, UniqueFunction uniqueFunction) { switch (uniqueFunction) { case UniqueFunction.First: return enumerable.FirstEx(); case UniqueFunction.FirstOrDefault: return enumerable.FirstOrDefault(); case UniqueFunction.Single: return enumerable.SingleEx(); case UniqueFunction.SingleOrDefault: return enumerable.SingleOrDefaultEx(); default: throw new InvalidOperationException(); } } public string CleanCommandText() { try { SqlPreCommand? eager = EagerProjections?.Select(cp => cp.Command).Combine(Spacing.Double); SqlPreCommand? lazy = LazyChildProjections?.Select(cp => cp.Command).Combine(Spacing.Double); return SqlPreCommandConcat.Combine(Spacing.Double, eager == null ? null : new SqlPreCommandSimple("--------- Eager Client Joins ----------------"), eager, eager == null && lazy == null ? null : new SqlPreCommandSimple("--------- MAIN QUERY ------------------------"), MainCommand, lazy == null ? null : new SqlPreCommandSimple("--------- Lazy Client Joins (if needed) -----"), lazy)!.PlainSql(); } catch { return MainCommand.Sql; } } public LambdaExpression GetMainProjector() { return this.ProjectorExpression; } } }
#region File Description //----------------------------------------------------------------------------- // MaterialsAndLights.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace MaterialsAndLightsSample { /// <summary> /// The central class for the sample Game. /// </summary> public class MaterialsAndLights : Microsoft.Xna.Framework.Game { #region Sample Fields private GraphicsDeviceManager graphics; private SampleArcBallCamera camera; private Vector2 safeBounds; private Vector2 debugTextHeight; private SpriteBatch spriteBatch; private SpriteFont debugTextFont; private GamePadState lastGpState; private KeyboardState lastKbState; private Effect pointLightMeshEffect; private string shaderVersionString = string.Empty; private Matrix projection; private Random random = new Random(); #endregion #region Scene Fields private Matrix meshRotation; private Matrix[] meshWorlds; private Material[] materials; private Material floorMaterial; private Matrix floorWorld; private int materialRotation = 0; private PointLight[] lights; private Model[] sampleMeshes; private Model pointLightMesh; private int numLights; private int maxLights; private Matrix lightMeshWorld; #endregion #region Shared Effect Fields private Effect baseEffect; private EffectParameter viewParameter; private EffectParameter projectionParameter; private EffectParameter cameraPositionParameter; #endregion #region Initialization and Cleanup public MaterialsAndLights() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // enable default sample behaviors. graphics.PreferredBackBufferWidth = 853; graphics.PreferredBackBufferHeight = 480; graphics.MinimumVertexShaderProfile = ShaderProfile.VS_2_0; graphics.MinimumPixelShaderProfile = ShaderProfile.PS_2_0; } /// <summary> /// Initialize the sample. /// </summary> protected override void Initialize() { // create a default world and matrix meshRotation = Matrix.Identity; // create the mesh array sampleMeshes = new Model[5]; // set up the sample camera camera = new SampleArcBallCamera(SampleArcBallCameraMode.RollConstrained); camera.Distance = 12; // orbit the camera so we're looking down the z=-1 axis, // at the "front" of the object camera.OrbitRight(MathHelper.Pi); // orbit up a bit for perspective camera.OrbitUp(.2f); //set up a ring of meshes meshWorlds = new Matrix[8]; for (int i = 0; i < 8; i++) { float theta = MathHelper.TwoPi * ((float) i / 8f); meshWorlds[i] = Matrix.CreateTranslation( 5f * (float)Math.Sin(theta), 0, 5f * (float)Math.Cos(theta)); } // set the initial material assignments to the geometry materialRotation = 2; // stretch the cube out to represent a "floor" // that will help visualize the light radii floorWorld = Matrix.CreateScale(30f, 1f, 30f) * Matrix.CreateTranslation(0, -2.2f, 0); lightMeshWorld = Matrix.CreateScale(.2f); base.Initialize(); } /// <summary> /// Load the graphics content. /// </summary> protected override void LoadContent() { // create the spritebatch for debug text spriteBatch = new SpriteBatch(graphics.GraphicsDevice); // load meshes sampleMeshes[0] = Content.Load<Model>("Meshes\\Cube"); sampleMeshes[1] = Content.Load<Model>("Meshes\\SphereHighPoly"); sampleMeshes[2] = Content.Load<Model>("Meshes\\Cylinder"); sampleMeshes[3] = Content.Load<Model>("Meshes\\Cone"); pointLightMesh = Content.Load<Model>("Meshes\\SphereLowPoly"); // load the sprite font for debug text debugTextFont = Content.Load<SpriteFont>("DebugText"); debugTextHeight = new Vector2(0, debugTextFont.LineSpacing + 5); //load the effects pointLightMeshEffect = Content.Load<Effect>("Effects\\PointLightMesh"); ////////////////////////////////////////////////////////////// // Example 1.1 // // // // To light the materials with a large number of lights // // in a single pass, this example requires Shader Model 3.0 // // level hardare. The Xbox 360 will always use the SM3.0 // // version of the shader code, but pre-SM-3.0 PC harware // // requires a fallback. In this sample, the fallback is // // limited to 2 lights in a single pass. // ////////////////////////////////////////////////////////////// if (graphics.GraphicsDevice.GraphicsDeviceCapabilities. PixelShaderVersion.Major >= 3) { baseEffect = Content.Load<Effect>("Effects\\MaterialShader30"); lights = new PointLight[8]; maxLights = 8; numLights = 1; baseEffect.Parameters["numLights"].SetValue(numLights); shaderVersionString = "Using Shader Model 3.0"; } else { baseEffect = Content.Load<Effect>("Effects\\MaterialShader20"); lights = new PointLight[2]; maxLights = 2; numLights = 1; baseEffect.Parameters["numLights"].SetValue(numLights); shaderVersionString = "Using Shader Model 2.0"; } // generate random light paramters GenerateRandomLights(); // cache the effect parameters viewParameter = baseEffect.Parameters["view"]; projectionParameter = baseEffect.Parameters["projection"]; cameraPositionParameter = baseEffect.Parameters["cameraPosition"]; // create the materials materials = new Material[8]; for (int i = 0; i < materials.Length; i++) { materials[i] = new Material(Content, graphics.GraphicsDevice, baseEffect); } floorMaterial = new Material(Content, graphics.GraphicsDevice, baseEffect); ////////////////////////////////////////////////////////////// // Example 1.2 // // // // Each material will have a unique set of properties. For // // the purposes of this sample, the materials are assigned // // at runtime. Often, these kinds of material properties // // are specific to the Model being used, and can be // // imported through the Content Pipeline using custom // // processors and/or importers. // ////////////////////////////////////////////////////////////// materials[0].SetBasicProperties(Color.Purple, .5f, 1.2f); materials[1].SetBasicProperties(Color.Orange, 8f, 2f); materials[2].SetBasicProperties(Color.Green, 2f, 3f); materials[3].SetBasicProperties(Color.White, 256f, 16f); materials[4].SetTexturedMaterial(Color.CornflowerBlue, 64f, 4f, null, "Scratches", .5f, .5f); materials[5].SetTexturedMaterial(Color.LemonChiffon, 32f, 4f, "Marble", "Scratches", 1f, 1f); materials[6].SetTexturedMaterial(Color.White, 32f, 16f, "Wood", null, 3f, 3f); materials[7].SetTexturedMaterial(Color.White, 64f, 64f, "Hexes", "HexesSpecular", 4f, 2f); floorMaterial.SetTexturedMaterial(Color.White, 16f, .8f, "Grid", "Grid", 15f, 15f); ////////////////////////////////////////////////////////////// // Example 1.3 // // // // The ambient light color does not change at all during // // runtime, and it is applied to all materials in the // // scene. All of the clone textures for each material will // // be updated since the clones use the same effect pool and // // the ambientLightColor parameter is maked "shared" in the // // effect. By sharing this parameter amongst all materials // // the usage is both more readable and optimized. // ////////////////////////////////////////////////////////////// baseEffect.Parameters["ambientLightColor"].SetValue( new Vector4(.15f, .15f, .15f, 1.0f)); // Recalculate the projection properties on every LoadGraphicsContent call. // That way, if the window gets resized, then the perspective matrix will // be updated accordingly float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height; float fieldOfView = aspectRatio * MathHelper.PiOver4 * 3f / 4f; projection = Matrix.CreatePerspectiveFieldOfView( fieldOfView, aspectRatio, .1f, 1000f); projectionParameter.SetValue(projection); // calculate the safe left and top edges of the screen safeBounds = new Vector2( (float)graphics.GraphicsDevice.Viewport.X + (float)graphics.GraphicsDevice.Viewport.Width * 0.1f, (float)graphics.GraphicsDevice.Viewport.Y + (float)graphics.GraphicsDevice.Viewport.Height * 0.1f ); } #endregion #region Update and Render /// <summary> /// This function populates the lights list with semi-random /// light properties. /// </summary> public void GenerateRandomLights() { for (int i = 0; i < lights.Length; i++) { //generate a "circle" of lights float theta = MathHelper.TwoPi * ((float)(i / 2) / (float)lights.Length) + (MathHelper.Pi * i); Vector4 position = new Vector4( 8f * (float)Math.Sin(theta), 3, 8f * (float)Math.Cos(theta), 1.0f); ////////////////////////////////////////////////////////////// // Example 1.4 // // // // The lights paramter is an arrray of light structures. // // Each light structure coresponds to an individual light, // // so an element in the array is associated with the new // // PointLight instance. // ////////////////////////////////////////////////////////////// lights[i] = new PointLight( position, baseEffect.Parameters["lights"].Elements[i]); //randomize the color, range, and power of the lights lights[i].Range = 25f + ((float)random.NextDouble() * 10f); lights[i].Falloff = 2f + ((float)random.NextDouble() * 4f); lights[i].Color = new Color(new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble())); } // always set light 0 to pure white as a reference point lights[0].Color = Color.White; } /// <summary> /// Update the game world. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { GamePadState gpState = GamePad.GetState(PlayerIndex.One); KeyboardState kbState = Keyboard.GetState(); // Check for exit if ((gpState.Buttons.Back == ButtonState.Pressed) || kbState.IsKeyDown(Keys.Escape)) { Exit(); } // handle inputs for the sample camera camera.HandleDefaultGamepadControls(gpState, gameTime); camera.HandleDefaultKeyboardControls(kbState, gameTime); // handle inputs specific to this sample HandleInput(gameTime, gpState, kbState); // The camera position should also be updated for the // Phong specular component to be meaningful. cameraPositionParameter.SetValue(camera.Position); // replace the "last" gamepad and keyboard states lastGpState = gpState; lastKbState = kbState; base.Update(gameTime); } private void HandleInput(GameTime gameTime, GamePadState gpState, KeyboardState kbState) { float elapsedTime = (float) gameTime.ElapsedGameTime.TotalSeconds; // handle input for rotating the materials if (((gpState.Buttons.X == ButtonState.Pressed) && (lastGpState.Buttons.X == ButtonState.Released)) || (kbState.IsKeyDown(Keys.Tab) && lastKbState.IsKeyUp(Keys.Tab))) { // switch the active mesh materialRotation = (materialRotation + 1) % materials.Length; } // handle input for adding lights to the scene if (((gpState.Buttons.RightShoulder == ButtonState.Pressed) && (lastGpState.Buttons.RightShoulder == ButtonState.Released)) || (kbState.IsKeyDown(Keys.Add) && lastKbState.IsKeyUp(Keys.Add))) { numLights = ((numLights) % (maxLights )) + 1; baseEffect.Parameters["numLights"].SetValue(numLights); } // handle input for removing lights from the scene if (((gpState.Buttons.LeftShoulder == ButtonState.Pressed) && (lastGpState.Buttons.LeftShoulder == ButtonState.Released)) || (kbState.IsKeyDown(Keys.Subtract) && lastKbState.IsKeyUp(Keys.Subtract))) { numLights = (numLights - 1); if (numLights < 1) numLights = maxLights; baseEffect.Parameters["numLights"].SetValue(numLights); } // handle input for generating new values for the lights if (((gpState.Buttons.Y == ButtonState.Pressed) && (lastGpState.Buttons.Y == ButtonState.Released)) || (kbState.IsKeyDown(Keys.Space) && lastKbState.IsKeyUp(Keys.Space))) { GenerateRandomLights(); } // handle mesh rotation inputs float dx = SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Left, Keys.Right) + gpState.ThumbSticks.Left.X; float dy = SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Down, Keys.Up) + gpState.ThumbSticks.Left.Y; // apply mesh rotation from inputs if (dx != 0) { meshRotation *= Matrix.CreateFromAxisAngle(camera.Up, elapsedTime * dx); } if (dy != 0) { meshRotation *= Matrix.CreateFromAxisAngle(camera.Right, elapsedTime * -dy); } // handle the light rotation inputs float lightRotation = SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.PageUp, Keys.PageDown) + gpState.Triggers.Right - gpState.Triggers.Left; if (lightRotation != 0) { Matrix rotation = Matrix.CreateRotationY(lightRotation * elapsedTime); foreach (PointLight light in lights) { // rotate all of the lights by transforming their positions light.Position = Vector4.Transform(light.Position, rotation); } } } /// <summary> /// Draw the current scene. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.Black); // enable the depth buffer since geometry will be drawn graphics.GraphicsDevice.RenderState.DepthBufferEnable = true; graphics.GraphicsDevice.RenderState.DepthBufferWriteEnable = true; // always set the shared effects parameters viewParameter.SetValue(camera.ViewMatrix); cameraPositionParameter.SetValue(camera.Position); ////////////////////////////////////////////////////////////// // Example 1.5 // // // // The materials in this sample can be applied to any of // // the primitive meshs in the scene. Sorting by materials // // can generally improve performance by minimizing // // state switching on the graphics device. // ////////////////////////////////////////////////////////////// for (int i = 0; i < 8; i++) { Matrix world = meshRotation * meshWorlds[i]; materials[(i + materialRotation) % 8].DrawModelWithMaterial( sampleMeshes[i % 4], ref world); } floorMaterial.DrawModelWithMaterial(sampleMeshes[0], ref floorWorld); // draw a representation of the point lights in the scene DrawLights(); // draw the technique name and specular settings spriteBatch.Begin(); spriteBatch.DrawString(debugTextFont, shaderVersionString, safeBounds, Color.White); spriteBatch.DrawString(debugTextFont, "Number of lights: " + numLights + " out of " + maxLights , safeBounds + (1f * debugTextHeight), Color.White); spriteBatch.DrawString(debugTextFont, "Use Shoulder Buttons to add lights", safeBounds + (2f * debugTextHeight), Color.White); spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// This simple draw function is used to draw the on-screen /// representation of the lights affecting the meshes in the scene. /// </summary> public void DrawLights() { ModelMesh mesh = pointLightMesh.Meshes[0]; ModelMeshPart meshPart = mesh.MeshParts[0]; graphics.GraphicsDevice.Vertices[0].SetSource( mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride); graphics.GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration; graphics.GraphicsDevice.Indices = mesh.IndexBuffer; pointLightMeshEffect.Begin(SaveStateMode.None); pointLightMeshEffect.CurrentTechnique.Passes[0].Begin(); for (int i = 0; i < numLights; i++) { lightMeshWorld.M41 = lights[i].Position.X; lightMeshWorld.M42 = lights[i].Position.Y; lightMeshWorld.M43 = lights[i].Position.Z; pointLightMeshEffect.Parameters["world"].SetValue(lightMeshWorld); pointLightMeshEffect.Parameters["lightColor"].SetValue( lights[i].Color.ToVector4()); pointLightMeshEffect.CommitChanges(); graphics.GraphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, meshPart.BaseVertex, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount); } pointLightMeshEffect.CurrentTechnique.Passes[0].End(); pointLightMeshEffect.End(); } #endregion #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static void Main() { using (MaterialsAndLights game = new MaterialsAndLights()) { game.Run(); } } #endregion } }
using System; using OpenMetaverse; using System.Drawing; using log4net; using System.Reflection; namespace Voxel { public class CreateHandler : ICommandHandler { private enum Direction { Up, // z-axis Down, West, // x-axis East, North, // y-axis South, U, D, W, E, N, S } private UserPrimManager userPrimManager; public CreateHandler (UserPrimManager u) { userPrimManager = u; } private bool tryParseVector (string vecStr, out Vector3 pos) { char[] comma = {','}; string[] coords = vecStr.Split (comma); float x, y, z; if (coords.Length != 3) { pos = new Vector3(0, 0, 0); return false; } if (!(float.TryParse(coords[0], out x) && float.TryParse(coords[1], out y) && float.TryParse(coords[2], out z))) { pos = new Vector3(0, 0, 0); return false; } pos = new Vector3(x, y, z); return true; } private Vector3 makeRelativePosition(Direction dir, Vector3 lastPos) { Vector3 delta; switch (dir) { case Direction.U: case Direction.Up: delta = new Vector3 (0.0f, 0.0f, 1.0f); break; case Direction.D: case Direction.Down: delta = new Vector3 (0.0f, 0.0f, -1.0f); break; case Direction.W: case Direction.West: delta = new Vector3 (1.0f, 0.0f, 0.0f); break; case Direction.E: case Direction.East: delta = new Vector3 (-1.0f, 0.0f, 0.0f); break; case Direction.N: case Direction.North: delta = new Vector3 (0.0f, 1.0f, 0.0f); break; case Direction.S: case Direction.South: delta = new Vector3 (0.0f, -1.0f, 0.0f); break; default: delta = new Vector3 (0, 0, 0); break; } return lastPos + delta; } private bool tryParsePosition(string posStr, Vector3 lastPos, out Vector3 pos) { Direction dir; if (Enum.TryParse<CreateHandler.Direction> (posStr, true, out dir)) { pos = makeRelativePosition (dir, lastPos); return true; } else if (tryParseVector (posStr, out pos)) { return true; } else { pos = new Vector3 (0, 0, 0); return false; } } private bool tryParseHTMLColor(string colorStr, out Color4 color) { Color htmlCol; bool valid = true; try { htmlCol = ColorTranslator.FromHtml (string.Format ("#{0}", colorStr)); valid = true; } catch { htmlCol = Color.Empty; valid = false; } color = new Color4 (); color.R = htmlCol.R/255.0f; color.G = htmlCol.G/255.0f; color.B = htmlCol.B/255.0f; color.A = 1.0f; return valid; } private bool tryParseColor(string colorStr, out Color4 color) { KnownColor k; if (Enum.TryParse<KnownColor> (colorStr, true, out k)) { Color c = Color.FromKnownColor (k); color = new Color4 (); color.R = c.R/255.0f; color.G = c.G/255.0f; color.B = c.B/255.0f; color.A = 1.0f; Voxel.Log.Info (string.Format ("[Voxel] Mapping color {0} as ({1},{2},{3},{4})->({5},{6},{7},{8})", colorStr, c.R, c.G, c.B, c.A, color.R, color.G, color.B, color.A)); return true; } else if (tryParseHTMLColor (colorStr, out color)) { return true; } else { return false; } } private bool tryParseBlock(string blockStr, Block lastBlock, out Block block) { char[] semicolon = {';'}; string[] sections = blockStr.Split (semicolon); Vector3 pos; Color4 color; switch (sections.Length) { case 1: color = lastBlock.Color; if (!tryParsePosition(sections[0], lastBlock.Pos, out pos)) { block = null; } else { block = new Block(pos, color); } break; case 2: if (!(tryParsePosition(sections[0], lastBlock.Pos, out pos) && tryParseColor(sections[1], out color))) { block = null; } else { block = new Block(pos, color); } break; default: block = null; break; } return block != null; } public bool TryExecute(Command cmd) { Voxel.Log.Info ("[Voxel] Executing command."); string[] args = cmd.Args; if (args.Length < 2) { return false; } Block[] blocks = new Block[args.Length-1]; PrimManager pm = userPrimManager.GetPrimManager (cmd.User); Block lastBlock = pm.LastBlock (); for (int i = 1; i < args.Length; i++) { Block block; if (!tryParseBlock (args [i], lastBlock, out block)) { return false; } blocks [i - 1] = block; lastBlock = block; } pm.AddBlocks (blocks); return true; } } }
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace JelloScrum.Model.Helpers { using System; using System.Collections.Generic; using Entities; using Enumerations; /// <summary> /// Struct containing information about the velocity statistic /// </summary> public struct Velocity { private decimal hoursTotalEstimatedInSprint; private decimal hoursTotalRegisteredInSprint; private decimal hoursTotalEstimatedForCompletedStoriesInSprint; private decimal hoursTotalRegisteredForCompletedStoriesInSprint; private int storyPointsTotalEstimatedInSprint; private int storyPointsTotalEstimatedForCompletedStoriesInSprint; private decimal numberOfDaysInSprint; /// <summary> /// Total hours estimated in this sprint /// </summary> public decimal HoursTotalEstimatedInSprint { get { return hoursTotalEstimatedInSprint; } set { hoursTotalEstimatedInSprint = value; } } /// <summary> /// Total hours spent in this sprint /// </summary> public decimal HoursTotalRegisteredInSprint { get { return hoursTotalRegisteredInSprint; } set { hoursTotalRegisteredInSprint = value; } } /// <summary> /// Total time estimated for completed stories in this sprint /// </summary> public decimal HoursTotalEstimatedForCompletedStoriesInSprint { get { return hoursTotalEstimatedForCompletedStoriesInSprint; } set { hoursTotalEstimatedForCompletedStoriesInSprint = value; } } /// <summary> /// Total time spent on closed stories in this sprint /// </summary> public decimal HoursTotalRegisteredForCompletedStoriesInSprint { get { return hoursTotalRegisteredForCompletedStoriesInSprint; } set { hoursTotalRegisteredForCompletedStoriesInSprint = value; } } /// <summary> /// Total amount of storypoints in this sprint /// </summary> public int StoryPointsTotalEstimatedInSprint { get { return storyPointsTotalEstimatedInSprint; } set { storyPointsTotalEstimatedInSprint = value; } } /// <summary> /// Total amount of story points estimated for closed stories in this sprint /// </summary> public int StoryPointsTotalEstimatedForCompletedStoriesInSprint { get { return storyPointsTotalEstimatedForCompletedStoriesInSprint; } set { storyPointsTotalEstimatedForCompletedStoriesInSprint = value; } } /// <summary> /// Number of days this sprint takes (for all developers). /// If 2 developers work 4 weeks this should be 40 /// </summary> public decimal NumberOfDaysInSprint { get { return numberOfDaysInSprint; } set { numberOfDaysInSprint = value; } } /// <summary> /// Gets the amount of storypoints that are closed in this sprint each day /// </summary> public decimal StoryPointVelocity { get { if (numberOfDaysInSprint == 0) return 0; return storyPointsTotalEstimatedForCompletedStoriesInSprint/numberOfDaysInSprint; } } /// <summary> /// Hours velocity /// </summary> public decimal HoursVelocity { get { if (numberOfDaysInSprint == 0) return 0; return hoursTotalEstimatedForCompletedStoriesInSprint / numberOfDaysInSprint; } } } /// <summary> /// struct containing information about taskprogress /// </summary> public struct TaskProgress { private int completedTasks; private int incompleteTasks; private int totalTasks; private int assignedTasks; private int unassignedTasks; /// <summary> /// Completed tasks /// </summary> public int CompletedTasks { get { return completedTasks; } set { completedTasks = value; } } /// <summary> /// Incomplete tasks /// </summary> public int IncompleteTasks { get { return incompleteTasks; } set { incompleteTasks = value; } } /// <summary> /// Percentage of closed tasks /// </summary> public decimal CompletedTasksPercentage() { if (TotalTasks > 0) return 100 * ((decimal)completedTasks / TotalTasks); return 0; } /// <summary> /// Rounded percentage closed tasks /// </summary> /// <param name="numberOfDecimals"></param> /// <returns></returns> public decimal CompletedTasksPercentage(int numberOfDecimals) { return Math.Round(CompletedTasksPercentage(), numberOfDecimals, MidpointRounding.AwayFromZero); } /// <summary> /// Percentage incomplete tasks /// </summary> public decimal IncompleteTasksPercentage() { return 100 - CompletedTasksPercentage(); } /// <summary> /// Rounded percentage incomplete tasks /// </summary> public decimal IncompleteTasksPercentage(int numberOfDecimals) { return Math.Round(IncompleteTasksPercentage(), numberOfDecimals, MidpointRounding.AwayFromZero); } /// <summary> /// Percentage taken tasks /// </summary> public decimal AssignedTasksPercentage() { if (TotalTasks > 0) return 100 * ((decimal)assignedTasks / TotalTasks); return 0; } /// <summary> /// Rounded percentage taken tasks /// </summary> /// <param name="numberOfDecimals"></param> /// <returns></returns> public decimal AssignedTasksPercentage(int numberOfDecimals) { return Math.Round(AssignedTasksPercentage(), numberOfDecimals, MidpointRounding.AwayFromZero); } /// <summary> /// Percentage open tasks /// </summary> public decimal UnassignedTasksPercentage() { return 100 - AssignedTasksPercentage(); } /// <summary> /// Rounded percentage open tasks /// </summary> public decimal UnassignedTasksPercentage(int numberOfDecimals) { return Math.Round(UnassignedTasksPercentage(), numberOfDecimals, MidpointRounding.AwayFromZero); } /// <summary> /// Total tasks /// </summary> public int TotalTasks { get { return totalTasks; } set { totalTasks = value; } } /// <summary> /// Taken tasks /// </summary> public int AssignedTasks { get { return assignedTasks; } set { assignedTasks = value; } } /// <summary> /// Open tasks /// </summary> public int UnassignedTasks { get { return unassignedTasks; } set { unassignedTasks = value; } } } /// <summary> /// Used to calculate all kinds of statistics. /// </summary> public static class SprintHealthHelper { /// <summary> /// Calculates information about the velocity of the given sprint /// </summary> /// <param name="sprint"></param> /// <returns></returns> public static Velocity GetVelocity(Sprint sprint) { Velocity velocity = new Velocity(); if(sprint != null) { velocity.NumberOfDaysInSprint = sprint.WorkDays; foreach (SprintStory sprintStory in sprint.SprintStories) { velocity.HoursTotalEstimatedInSprint += Convert.ToDecimal(sprintStory.Estimation.TotalHours); if (sprintStory.Story.StoryPoints != StoryPoint.Unknown) velocity.StoryPointsTotalEstimatedInSprint += sprintStory.Story.StoryPointsValue; if (sprintStory.State == State.Closed) { velocity.HoursTotalEstimatedForCompletedStoriesInSprint += Convert.ToDecimal(sprintStory.Estimation.TotalHours); if (sprintStory.Story.StoryPoints != StoryPoint.Unknown) velocity.StoryPointsTotalEstimatedForCompletedStoriesInSprint += sprintStory.Story.StoryPointsValue; } foreach (Task task in sprintStory.Story.Tasks) { foreach (TimeRegistration tijdRegistratie in task.TimeRegistrations) { if (tijdRegistratie.Sprint == sprintStory.Sprint) { velocity.HoursTotalRegisteredInSprint += Convert.ToDecimal(tijdRegistratie.Time.TotalHours); if (task.State == State.Closed) { velocity.HoursTotalRegisteredForCompletedStoriesInSprint += Convert.ToDecimal(tijdRegistratie.Time.TotalHours); } } } } } } return velocity; } /// <summary> /// Calculates the taskprogress of the given sprint /// </summary> /// <param name="sprint"></param> /// <returns></returns> public static TaskProgress GetTaskProgress(Sprint sprint) { TaskProgress taskProgress = new TaskProgress(); List<Task> tasks = new List<Task>(); if(sprint != null) { foreach (SprintStory sprintStory in sprint.SprintStories) { tasks.AddRange(sprintStory.Story.Tasks); } } foreach (Task task in tasks) { taskProgress.TotalTasks++; if (task.State == State.Closed) taskProgress.CompletedTasks++; else taskProgress.IncompleteTasks++; if (task.AssignedUser == null) taskProgress.UnassignedTasks++; else taskProgress.AssignedTasks++; } return taskProgress; } } }
// 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.Configuration.Internal.DelegatingConfigHost.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.Configuration.Internal { public partial class DelegatingConfigHost : IInternalConfigHost { #region Methods and constructors public virtual new Object CreateConfigurationContext(string configPath, string locationSubPath) { return default(Object); } public virtual new Object CreateDeprecatedConfigContext(string configPath) { return default(Object); } public virtual new string DecryptSection(string encryptedXml, System.Configuration.ProtectedConfigurationProvider protectionProvider, System.Configuration.ProtectedConfigurationSection protectedConfigSection) { return default(string); } protected DelegatingConfigHost() { } public virtual new void DeleteStream(string streamName) { } public virtual new string EncryptSection(string clearTextXml, System.Configuration.ProtectedConfigurationProvider protectionProvider, System.Configuration.ProtectedConfigurationSection protectedConfigSection) { return default(string); } public virtual new string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) { return default(string); } public virtual new Type GetConfigType(string typeName, bool throwOnError) { return default(Type); } public virtual new string GetConfigTypeName(Type t) { return default(string); } public virtual new void GetRestrictedPermissions(IInternalConfigRecord configRecord, out System.Security.PermissionSet permissionSet, out bool isHostReady) { permissionSet = default(System.Security.PermissionSet); isHostReady = default(bool); } public virtual new string GetStreamName(string configPath) { return default(string); } public virtual new string GetStreamNameForConfigSource(string streamName, string configSource) { return default(string); } public virtual new Object GetStreamVersion(string streamName) { return default(Object); } public virtual new IDisposable Impersonate() { return default(IDisposable); } public virtual new void Init(IInternalConfigRoot configRoot, Object[] hostInitParams) { } public virtual new void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, Object[] hostInitConfigurationParams) { configPath = default(string); locationConfigPath = default(string); } public virtual new bool IsAboveApplication(string configPath) { return default(bool); } public virtual new bool IsConfigRecordRequired(string configPath) { return default(bool); } public virtual new bool IsDefinitionAllowed(string configPath, System.Configuration.ConfigurationAllowDefinition allowDefinition, System.Configuration.ConfigurationAllowExeDefinition allowExeDefinition) { return default(bool); } public virtual new bool IsFile(string streamName) { return default(bool); } public virtual new bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) { return default(bool); } public virtual new bool IsInitDelayed(IInternalConfigRecord configRecord) { return default(bool); } public virtual new bool IsLocationApplicable(string configPath) { return default(bool); } public virtual new bool IsSecondaryRoot(string configPath) { return default(bool); } public virtual new bool IsTrustedConfigPath(string configPath) { return default(bool); } public virtual new Stream OpenStreamForRead(string streamName, bool assertPermissions) { return default(Stream); } public virtual new Stream OpenStreamForRead(string streamName) { return default(Stream); } public virtual new Stream OpenStreamForWrite(string streamName, string templateStreamName, ref Object writeContext, bool assertPermissions) { return default(Stream); } public virtual new Stream OpenStreamForWrite(string streamName, string templateStreamName, ref Object writeContext) { return default(Stream); } public virtual new bool PrefetchAll(string configPath, string streamName) { return default(bool); } public virtual new bool PrefetchSection(string sectionGroupName, string sectionName) { return default(bool); } public virtual new void RequireCompleteInit(IInternalConfigRecord configRecord) { } public virtual new Object StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { return default(Object); } public virtual new void StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { } public virtual new void VerifyDefinitionAllowed(string configPath, System.Configuration.ConfigurationAllowDefinition allowDefinition, System.Configuration.ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { } public virtual new void WriteCompleted(string streamName, bool success, Object writeContext, bool assertPermissions) { } public virtual new void WriteCompleted(string streamName, bool success, Object writeContext) { } #endregion #region Properties and indexers protected IInternalConfigHost Host { get { return default(IInternalConfigHost); } set { } } public virtual new bool IsRemote { get { return default(bool); } } public virtual new bool SupportsChangeNotifications { get { return default(bool); } } public virtual new bool SupportsLocation { get { return default(bool); } } public virtual new bool SupportsPath { get { return default(bool); } } public virtual new bool SupportsRefresh { get { return default(bool); } } #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 System.Diagnostics.CodeAnalysis; namespace Microsoft.CSharp.RuntimeBinder.Semantics { /* // =========================================================================== Defines structs that package an aggregate member together with generic type argument information. // ===========================================================================*/ /****************************************************************************** SymWithType and its cousins. These package an aggregate member (field, prop, event, or meth) together with the particular instantiation of the aggregate (the AggregateType). The default constructor does nothing so these are not safe to use uninitialized. Note that when they are used as member of an EXPR they are automatically zero filled by newExpr. ******************************************************************************/ internal class SymWithType { private AggregateType _ats; private Symbol _sym; public SymWithType() { } public SymWithType(Symbol sym, AggregateType ats) { Set(sym, ats); } public virtual void Clear() { _sym = null; _ats = null; } public AggregateType Ats { get { return _ats; } } public Symbol Sym { get { return _sym; } } public new AggregateType GetType() { // This conflicts with object.GetType. Turn every usage of this // into a get on Ats. return Ats; } public static bool operator ==(SymWithType swt1, SymWithType swt2) { if (ReferenceEquals(swt1, swt2)) { return true; } else if (ReferenceEquals(swt1, null)) { return swt2._sym == null; } else if (ReferenceEquals(swt2, null)) { return swt1._sym == null; } return swt1.Sym == swt2.Sym && swt1.Ats == swt2.Ats; } public static bool operator !=(SymWithType swt1, SymWithType swt2) => !(swt1 == swt2); [ExcludeFromCodeCoverage] // == overload should always be the method called. public override bool Equals(object obj) { Debug.Fail("Sub-optimal equality called. Check if this is correct."); SymWithType other = obj as SymWithType; if (other == null) return false; return Sym == other.Sym && Ats == other.Ats; } [ExcludeFromCodeCoverage] // Never used as a key. public override int GetHashCode() { Debug.Fail("If using this as a key, implement IEquatable<SymWithType>"); return (Sym?.GetHashCode() ?? 0) + (Ats?.GetHashCode() ?? 0); } // The SymWithType is considered NULL iff the Symbol is NULL. public static implicit operator bool (SymWithType swt) { return swt != null; } // These assert that the Symbol is of the correct type. public MethodOrPropertySymbol MethProp() { return Sym as MethodOrPropertySymbol; } public MethodSymbol Meth() { return Sym as MethodSymbol; } public PropertySymbol Prop() { return Sym as PropertySymbol; } public FieldSymbol Field() { return Sym as FieldSymbol; } public EventSymbol Event() { return Sym as EventSymbol; } public void Set(Symbol sym, AggregateType ats) { if (sym == null) ats = null; Debug.Assert(ats == null || sym.parent == ats.getAggregate()); _sym = sym; _ats = ats; } } internal class MethPropWithType : SymWithType { public MethPropWithType() { } public MethPropWithType(MethodOrPropertySymbol mps, AggregateType ats) { Set(mps, ats); } } internal sealed class MethWithType : MethPropWithType { public MethWithType() { } public MethWithType(MethodSymbol meth, AggregateType ats) { Set(meth, ats); } } internal sealed class PropWithType : MethPropWithType { public PropWithType() { } public PropWithType(PropertySymbol prop, AggregateType ats) { Set(prop, ats); } public PropWithType(SymWithType swt) { Set(swt.Sym as PropertySymbol, swt.Ats); } } internal sealed class EventWithType : SymWithType { public EventWithType() { } public EventWithType(EventSymbol @event, AggregateType ats) { Set(@event, ats); } } internal sealed class FieldWithType : SymWithType { public FieldWithType() { } public FieldWithType(FieldSymbol field, AggregateType ats) { Set(field, ats); } } /****************************************************************************** MethPropWithInst and MethWithInst. These extend MethPropWithType with the method type arguments. Properties will never have type args, but methods and properties share a lot of code so it's convenient to allow both here. The default constructor does nothing so these are not safe to use uninitialized. Note that when they are used as member of an EXPR they are automatically zero filled by newExpr. ******************************************************************************/ internal class MethPropWithInst : MethPropWithType { public TypeArray TypeArgs { get; private set; } public MethPropWithInst() { Set(null, null, null); } public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats) : this(mps, ats, null) { } public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs) { Set(mps, ats, typeArgs); } public override void Clear() { base.Clear(); TypeArgs = null; } public void Set(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs) { if (mps == null) { ats = null; typeArgs = null; } Debug.Assert(ats == null || mps != null && mps.getClass() == ats.getAggregate()); base.Set(mps, ats); TypeArgs = typeArgs; } } internal sealed class MethWithInst : MethPropWithInst { public MethWithInst() { } public MethWithInst(MethodSymbol meth, AggregateType ats) : this(meth, ats, null) { } public MethWithInst(MethodSymbol meth, AggregateType ats, TypeArray typeArgs) { Set(meth, ats, typeArgs); } public MethWithInst(MethPropWithInst mpwi) { Set(mpwi.Sym.AsMethodSymbol(), mpwi.Ats, mpwi.TypeArgs); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using BTDB.Buffer; namespace BTDB.KVDBLayer.BTree { class BTreeLeaf : IBTreeLeafNode, IBTreeNode { internal readonly long TransactionId; BTreeLeafMember[] _keyvalues; internal const int MaxMembers = 30; BTreeLeaf(long transactionId, int length) { TransactionId = transactionId; _keyvalues = new BTreeLeafMember[length]; } internal BTreeLeaf(long transactionId, int length, Func<BTreeLeafMember> memberGenerator) { Debug.Assert(length > 0 && length <= MaxMembers); TransactionId = transactionId; _keyvalues = new BTreeLeafMember[length]; for (int i = 0; i < _keyvalues.Length; i++) { _keyvalues[i] = memberGenerator(); } } internal BTreeLeaf(long transactionId, BTreeLeafMember[] newKeyValues) { TransactionId = transactionId; _keyvalues = newKeyValues; } internal static IBTreeNode CreateFirst(CreateOrUpdateCtx ctx) { var result = new BTreeLeaf(ctx.TransactionId, 1); result._keyvalues[0] = NewMemberFromCtx(ctx); return result; } int Find(byte[] prefix, ByteBuffer key) { var left = 0; var right = _keyvalues.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keyvalues[middle].Key; var result = BitArrayManipulation.CompareByteArray(prefix, prefix.Length, currentKey, Math.Min(currentKey.Length, prefix.Length)); if (result == 0) { result = BitArrayManipulation.CompareByteArray(key.Buffer, key.Offset, key.Length, currentKey, prefix.Length, currentKey.Length - prefix.Length); if (result == 0) { return middle * 2 + 1; } } if (result < 0) { right = middle; } else { left = middle + 1; } } return left * 2; } public void CreateOrUpdate(CreateOrUpdateCtx ctx) { var index = Find(ctx.KeyPrefix, ctx.Key); if ((index & 1) == 1) { index = index / 2; ctx.Created = false; ctx.KeyIndex = index; var m = _keyvalues[index]; m.ValueFileId = ctx.ValueFileId; m.ValueOfs = ctx.ValueOfs; m.ValueSize = ctx.ValueSize; var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeaf(ctx.TransactionId, _keyvalues.Length); Array.Copy(_keyvalues, leaf._keyvalues, _keyvalues.Length); ctx.Node1 = leaf; ctx.Update = true; } leaf._keyvalues[index] = m; ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } index = index / 2; ctx.Created = true; ctx.KeyIndex = index; if (_keyvalues.Length < MaxMembers) { var newKeyValues = new BTreeLeafMember[_keyvalues.Length + 1]; Array.Copy(_keyvalues, 0, newKeyValues, 0, index); newKeyValues[index] = NewMemberFromCtx(ctx); Array.Copy(_keyvalues, index, newKeyValues, index + 1, _keyvalues.Length - index); var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeaf(ctx.TransactionId, newKeyValues); ctx.Node1 = leaf; ctx.Update = true; } else { _keyvalues = newKeyValues; } ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } ctx.Split = true; var keyCountLeft = (_keyvalues.Length + 1) / 2; var keyCountRight = _keyvalues.Length + 1 - keyCountLeft; var leftNode = new BTreeLeaf(ctx.TransactionId, keyCountLeft); var rightNode = new BTreeLeaf(ctx.TransactionId, keyCountRight); ctx.Node1 = leftNode; ctx.Node2 = rightNode; if (index < keyCountLeft) { Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, index); leftNode._keyvalues[index] = NewMemberFromCtx(ctx); Array.Copy(_keyvalues, index, leftNode._keyvalues, index + 1, keyCountLeft - index - 1); Array.Copy(_keyvalues, keyCountLeft - 1, rightNode._keyvalues, 0, keyCountRight); ctx.Stack.Add(new NodeIdxPair { Node = leftNode, Idx = index }); ctx.SplitInRight = false; } else { Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, keyCountLeft); Array.Copy(_keyvalues, keyCountLeft, rightNode._keyvalues, 0, index - keyCountLeft); rightNode._keyvalues[index - keyCountLeft] = NewMemberFromCtx(ctx); Array.Copy(_keyvalues, index, rightNode._keyvalues, index - keyCountLeft + 1, keyCountLeft + keyCountRight - 1 - index); ctx.Stack.Add(new NodeIdxPair { Node = rightNode, Idx = index - keyCountLeft }); ctx.SplitInRight = true; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, byte[] prefix, ByteBuffer key) { var idx = Find(prefix, key); FindResult result; if ((idx & 1) == 1) { result = FindResult.Exact; idx = idx / 2; } else { result = FindResult.Previous; idx = idx / 2 - 1; } stack.Add(new NodeIdxPair { Node = this, Idx = idx }); keyIndex = idx; return result; } static BTreeLeafMember NewMemberFromCtx(CreateOrUpdateCtx ctx) { return new BTreeLeafMember { Key = ctx.WholeKey(), ValueFileId = ctx.ValueFileId, ValueOfs = ctx.ValueOfs, ValueSize = ctx.ValueSize }; } public long CalcKeyCount() { return _keyvalues.Length; } public byte[] GetLeftMostKey() { return _keyvalues[0].Key; } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { stack.Add(new NodeIdxPair { Node = this, Idx = (int)keyIndex }); } public long FindLastWithPrefix(byte[] prefix) { var left = 0; var right = _keyvalues.Length - 1; byte[] currentKey; int result; while (left < right) { var middle = (left + right) / 2; currentKey = _keyvalues[middle].Key; result = BitArrayManipulation.CompareByteArray(prefix, prefix.Length, currentKey, Math.Min(currentKey.Length, prefix.Length)); if (result < 0) { right = middle; } else { left = middle + 1; } } currentKey = _keyvalues[left].Key; result = BitArrayManipulation.CompareByteArray(prefix, prefix.Length, currentKey, Math.Min(currentKey.Length, prefix.Length)); if (result < 0) left--; return left; } public bool NextIdxValid(int idx) { return idx + 1 < _keyvalues.Length; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { // Nothing to do } public void FillStackByRightMost(List<NodeIdxPair> stack, int i) { // Nothing to do } public int GetLastChildrenIdx() { return _keyvalues.Length - 1; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { var newKeyValues = new BTreeLeafMember[_keyvalues.Length + firstKeyIndex - lastKeyIndex - 1]; Array.Copy(_keyvalues, 0, newKeyValues, 0, (int)firstKeyIndex); Array.Copy(_keyvalues, (int)lastKeyIndex + 1, newKeyValues, (int)firstKeyIndex, newKeyValues.Length - (int)firstKeyIndex); if (TransactionId == transactionId) { _keyvalues = newKeyValues; return this; } return new BTreeLeaf(transactionId, newKeyValues); } public void Iterate(BTreeIterateAction action) { var kv = _keyvalues; for (var i = 0; i < kv.Length; i++) { var member = kv[i]; action(member.ValueFileId, member.ValueOfs, member.ValueSize); } } public IBTreeNode RemappingIterate(long transactionId, BTreeRemappingIterateAction action) { var result = this; var keyvalues = _keyvalues; for (var i = 0; i < keyvalues.Length; i++) { uint newFileId; uint newOffset; if (action(keyvalues[i].ValueFileId, keyvalues[i].ValueOfs, out newFileId, out newOffset)) { if (result.TransactionId != transactionId) { var newKeyValues = new BTreeLeafMember[keyvalues.Length]; Array.Copy(keyvalues, newKeyValues, newKeyValues.Length); result = new BTreeLeaf(transactionId, newKeyValues); keyvalues = newKeyValues; } keyvalues[i].ValueFileId = newFileId; keyvalues[i].ValueOfs = newOffset; } } return result; } public ByteBuffer GetKey(int idx) { return ByteBuffer.NewAsync(_keyvalues[idx].Key); } public BTreeValue GetMemberValue(int idx) { var kv = _keyvalues[idx]; return new BTreeValue { ValueFileId = kv.ValueFileId, ValueOfs = kv.ValueOfs, ValueSize = kv.ValueSize }; } public void SetMemberValue(int idx, BTreeValue value) { var kv = _keyvalues[idx]; kv.ValueFileId = value.ValueFileId; kv.ValueOfs = value.ValueOfs; kv.ValueSize = value.ValueSize; _keyvalues[idx] = kv; } } }
using System; using Shouldly; using Spk.Common.Helpers.Guard; using Xunit; namespace Spk.Common.Tests.Helpers.Guard { public partial class ArgumentGuardTests { public class GuardIsLessThan_double { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( double argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( double argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_float { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( float argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( float argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_decimal { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( decimal argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( decimal argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_short { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( short argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( short argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_int { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( int argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( int argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_long { [Theory] [InlineData(1, 2)] [InlineData(-1231, -1230)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( long argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] [InlineData(-1230, -1231)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( long argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_ushort { [Theory] [InlineData(1, 2)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( ushort argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( ushort argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } public class GuardIsLessThan_uint { [Theory] [InlineData(1, 2)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( uint argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( uint argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } public class GuardIsLessThan_ulong { [Theory] [InlineData(1, 2)] public void GuardIsLessThan_ShouldReturnUnalteredValue_WhenArgumentIsLessThanTarget( ulong argument, double target) { var result = argument.GuardIsLessThan(target, nameof(argument)); result.ShouldBe(argument); } [Theory] [InlineData(2, 1)] [InlineData(2, 2)] public void GuardIsLessThan_ShouldThrow_WhenArgumentIsNotLessThanTarget( ulong argument, double target) { Assert.Throws<ArgumentOutOfRangeException>( nameof(argument), () => { argument.GuardIsLessThan(target, nameof(argument)); }); } } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.IO; using System.Collections.Generic; namespace GuruComponents.Netrix.UserInterface.ColorPicker { /// <summary> /// ColorPanelUserControl is used to host an instance of ColorPanel together with various options. /// </summary> /// <remarks> /// This is the base control which is placed into the /// <see cref="GuruComponents.Netrix.UserInterface.ColorPicker.ColorPanelForm">ColorPanelForm</see> /// form to be dropped from the /// <see cref="GuruComponents.Netrix.UserInterface.ColorPicker.ColorPickerUserControl">ColorPickerUserControl</see>. /// Normally this control should not be placed as a standalone user control onto a form. It is public to /// be used if a replacement of the <see cref="GuruComponents.Netrix.UserInterface.ColorPicker.ColorPanelForm">ColorPanelForm</see> form /// is requiered. /// <para> /// This control uses the satellite assemblies to localize the labels. For that reason, the control /// should not be used without the satellites for all languages used in the final application. Otherwise /// a replacement string is used as the embedded default resource. /// </para> /// </remarks> [ToolboxItem(true)] [ToolboxBitmap(typeof(GuruComponents.Netrix.UserInterface.ResourceManager), "ToolBox.ColorEditor.ico")] [Designer(typeof(GuruComponents.Netrix.UserInterface.NetrixUIDesigner))] public class ColorPanelUserControl : System.Windows.Forms.UserControl { private ColorPanel colorPanel = null; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.RadioButton radioButtonNo; private System.Windows.Forms.RadioButton radioButtonSaturation; private System.Windows.Forms.RadioButton radioButtonDistance; private System.Windows.Forms.RadioButton radioButtonName; private System.Windows.Forms.RadioButton radioButtonBrightness; private System.Windows.Forms.RadioButton radioButtonCont; private System.Windows.Forms.Button buttonWeb; private System.Windows.Forms.Button buttonCustom; private System.Windows.Forms.Button buttonSystem; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonNoColor; private System.Windows.Forms.PictureBox pictureBox1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// The contructor which instantiate the control. /// </summary> /// <remarks> /// Build the control using this constructor when used on a form. /// </remarks> public ColorPanelUserControl() { InitializeComponent(); SetUp(); this.buttonWeb.BackColor = SystemColors.Control; this.buttonWeb.Focus(); } private static Stream s = typeof(ColorPanelUserControl).Assembly.GetManifestResourceStream("GuruComponents.Netrix.UserInterface.Resources.Resx.NoColor.ico"); internal void SetUp() { this.radioButtonNo.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonNo.Text"); //"Standard"; this.radioButtonCont.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonCont.Text"); //"Continued"; this.groupBox2.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.groupBox2.Text"); //"Sort Options"; this.radioButtonBrightness.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonBrightness.Text"); //"Brightness"; this.radioButtonName.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonName.Text"); //"Name"; this.radioButtonDistance.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonDistance.Text"); //"Distance"; this.radioButtonSaturation.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.radioButtonSaturation.Text"); //"Saturation"; this.buttonWeb.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.buttonWeb.Text"); //"Web"; this.buttonCustom.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.buttonCustom.Text"); //"Custom"; this.buttonSystem.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.buttonSystem.Text"); //"System"; this.label1.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.label1.Text"); //"Hit ESC to cancel"; this.buttonNoColor.Text = GuruComponents.Netrix.UserInterface.ResourceManager.GetString("ColorPanelUserControl.buttonNoColor.Text"); //"No Color"; this.buttonNoColor.Image = Image.FromStream(s); this.pictureBox1.Image = Image.FromStream(s); ArrangeButtons(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ColorPanelUserControl)); this.colorPanel = new GuruComponents.Netrix.UserInterface.ColorPicker.ColorPanel(); this.radioButtonNo = new System.Windows.Forms.RadioButton(); this.radioButtonCont = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.radioButtonBrightness = new System.Windows.Forms.RadioButton(); this.radioButtonName = new System.Windows.Forms.RadioButton(); this.radioButtonDistance = new System.Windows.Forms.RadioButton(); this.radioButtonSaturation = new System.Windows.Forms.RadioButton(); this.buttonWeb = new System.Windows.Forms.Button(); this.buttonCustom = new System.Windows.Forms.Button(); this.buttonSystem = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.buttonNoColor = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // colorPanel // this.colorPanel.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.colorPanel.BackColor = System.Drawing.SystemColors.ControlDark; this.colorPanel.ColorWellSize = new System.Drawing.Size(12, 12); this.colorPanel.Location = new System.Drawing.Point(0, 0); this.colorPanel.Name = "colorPanel"; this.colorPanel.Size = new System.Drawing.Size(220, 148); this.colorPanel.TabIndex = 13; this.colorPanel.ColorChanged += new GuruComponents.Netrix.UserInterface.ColorPicker.ColorChangedEventHandler(this.colorPanel_ColorChanged); // // radioButtonNo // this.radioButtonNo.Checked = true; this.radioButtonNo.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonNo.Location = new System.Drawing.Point(8, 18); this.radioButtonNo.Name = "radioButtonNo"; this.radioButtonNo.Size = new System.Drawing.Size(111, 16); this.radioButtonNo.TabIndex = 4; this.radioButtonNo.TabStop = true; this.radioButtonNo.Tag = "No"; this.radioButtonNo.Text = "Standard"; this.radioButtonNo.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // radioButtonCont // this.radioButtonCont.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonCont.Location = new System.Drawing.Point(8, 34); this.radioButtonCont.Name = "radioButtonCont"; this.radioButtonCont.Size = new System.Drawing.Size(111, 16); this.radioButtonCont.TabIndex = 5; this.radioButtonCont.Tag = "continues"; this.radioButtonCont.Text = "Continued"; this.radioButtonCont.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.radioButtonBrightness); this.groupBox2.Controls.Add(this.radioButtonName); this.groupBox2.Controls.Add(this.radioButtonDistance); this.groupBox2.Controls.Add(this.radioButtonSaturation); this.groupBox2.Controls.Add(this.radioButtonCont); this.groupBox2.Controls.Add(this.radioButtonNo); this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBox2.Location = new System.Drawing.Point(224, 28); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(127, 121); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; this.groupBox2.Text = "Sort Options"; // // radioButtonBrightness // this.radioButtonBrightness.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonBrightness.Location = new System.Drawing.Point(8, 98); this.radioButtonBrightness.Name = "radioButtonBrightness"; this.radioButtonBrightness.Size = new System.Drawing.Size(111, 16); this.radioButtonBrightness.TabIndex = 9; this.radioButtonBrightness.Tag = "Brightness"; this.radioButtonBrightness.Text = "Brightness"; this.radioButtonBrightness.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // radioButtonName // this.radioButtonName.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonName.Location = new System.Drawing.Point(8, 82); this.radioButtonName.Name = "radioButtonName"; this.radioButtonName.Size = new System.Drawing.Size(111, 16); this.radioButtonName.TabIndex = 8; this.radioButtonName.Tag = "Name"; this.radioButtonName.Text = "Name"; this.radioButtonName.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // radioButtonDistance // this.radioButtonDistance.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonDistance.Location = new System.Drawing.Point(8, 66); this.radioButtonDistance.Name = "radioButtonDistance"; this.radioButtonDistance.Size = new System.Drawing.Size(111, 16); this.radioButtonDistance.TabIndex = 7; this.radioButtonDistance.Tag = "Distance"; this.radioButtonDistance.Text = "Distance"; this.radioButtonDistance.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // radioButtonSaturation // this.radioButtonSaturation.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonSaturation.Location = new System.Drawing.Point(8, 50); this.radioButtonSaturation.Name = "radioButtonSaturation"; this.radioButtonSaturation.Size = new System.Drawing.Size(111, 16); this.radioButtonSaturation.TabIndex = 6; this.radioButtonSaturation.Tag = "Saturation"; this.radioButtonSaturation.Text = "Saturation"; this.radioButtonSaturation.CheckedChanged += new System.EventHandler(this.radioButtonNo_CheckedChanged); // // buttonWeb // this.buttonWeb.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonWeb.BackColor = System.Drawing.SystemColors.ControlDark; this.buttonWeb.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonWeb.Location = new System.Drawing.Point(1, 146); this.buttonWeb.Name = "buttonWeb"; this.buttonWeb.Size = new System.Drawing.Size(72, 22); this.buttonWeb.TabIndex = 8; this.buttonWeb.Tag = "0"; this.buttonWeb.Text = "Web"; this.buttonWeb.Click += new System.EventHandler(this.button_Click); // // buttonCustom // this.buttonCustom.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonCustom.BackColor = System.Drawing.SystemColors.ControlDark; this.buttonCustom.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonCustom.Location = new System.Drawing.Point(74, 146); this.buttonCustom.Name = "buttonCustom"; this.buttonCustom.Size = new System.Drawing.Size(72, 22); this.buttonCustom.TabIndex = 9; this.buttonCustom.Tag = "1"; this.buttonCustom.Text = "Custom"; this.buttonCustom.Click += new System.EventHandler(this.button_Click); // // buttonSystem // this.buttonSystem.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonSystem.BackColor = System.Drawing.SystemColors.ControlDark; this.buttonSystem.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonSystem.Location = new System.Drawing.Point(149, 146); this.buttonSystem.Name = "buttonSystem"; this.buttonSystem.Size = new System.Drawing.Size(72, 22); this.buttonSystem.TabIndex = 10; this.buttonSystem.Tag = "2"; this.buttonSystem.Text = "System"; this.buttonSystem.Click += new System.EventHandler(this.button_Click); // // label1 // this.label1.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.label1.BackColor = System.Drawing.SystemColors.Info; this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label1.ForeColor = System.Drawing.SystemColors.InfoText; this.label1.Location = new System.Drawing.Point(224, 151); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(127, 13); this.label1.TabIndex = 11; this.label1.Text = "Hit ESC to cancel"; // // buttonNoColor // this.buttonNoColor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.buttonNoColor.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonNoColor.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonNoColor.Location = new System.Drawing.Point(224, 0); this.buttonNoColor.Name = "buttonNoColor"; this.buttonNoColor.Size = new System.Drawing.Size(128, 23); this.buttonNoColor.TabIndex = 12; this.buttonNoColor.Text = "No Color"; this.buttonNoColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonNoColor.Click += new System.EventHandler(this.buttonNoColor_Click); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(313, 3); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(24, 15); this.pictureBox1.TabIndex = 14; this.pictureBox1.TabStop = false; // // ColorPanelUserControl // this.Controls.Add(this.groupBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.colorPanel); this.Controls.Add(this.buttonNoColor); this.Controls.Add(this.label1); this.Controls.Add(this.buttonSystem); this.Controls.Add(this.buttonCustom); this.Controls.Add(this.buttonWeb); this.Name = "ColorPanelUserControl"; this.Size = new System.Drawing.Size(357, 170); this.Tag = "0"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ColorPanelForm_KeyDown); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// This method internally sets the names of buttons /// </summary> /// <param name="standard"></param> /// <param name="cont"></param> /// <param name="saturation"></param> /// <param name="bright"></param> /// <param name="name"></param> /// <param name="distance"></param> internal void SetColorSortNames(string standard, string cont, string saturation, string bright, string name, string distance) { this.radioButtonBrightness.Text = bright; this.radioButtonCont.Text = cont; this.radioButtonDistance.Text = distance; this.radioButtonNo.Text = standard; this.radioButtonSaturation.Text = saturation; this.radioButtonName.Text = name; } /// <summary> /// Sets the control in an undefined state. /// </summary> /// <remarks> /// This is used to inform other controls to not rewrite the value in the control. /// </remarks> public void ResetControl() { ResetControl(new List<Color>()); SetUp(); } /// <summary> /// Sets the control in an undefined state. /// </summary> /// <remarks> /// This is used to inform other controls /// to not rewrite the value in the control. Additionally the custom color table /// is filled with a array of colors. /// </remarks> /// <param name="customiser">Array of colors to customize the palette.</param> public void ResetControl(List<Color> customiser) { this.CustomColors = customiser; } private void colorPanel_ColorChanged(object sender, ColorChangedEventArgs e) { this.Color = this.colorPanel.Color; if (ColorChanged != null) { ColorChanged(sender, e); } } private void ColorPanelForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { e.Handled = true; this.colorPanel.ResetColor(); return; } if (e.KeyCode == Keys.Enter) { e.Handled = true; return; } } private void radioButtonNo_CheckedChanged(object sender, System.EventArgs e) { RadioButton r = (RadioButton) sender; switch (r.Tag.ToString()) { case "No": if (this.buttonWeb.BackColor == SystemColors.Control) { this.colorPanel.ColorSet = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSet.Web; } this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Unsorted; break; case "continues": this.colorPanel.ColorSet = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSet.Continues; this.buttonWeb.BackColor = SystemColors.Control; this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Unsorted; break; case "Saturation": this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Saturation; break; case "Distance": this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Distance; break; case "Brightness": this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Brightness; break; case "Name": this.colorPanel.ColorSortOrder = GuruComponents.Netrix.UserInterface.ColorPicker.ColorSortOrder.Name; break; } } private void button_Click(object sender, System.EventArgs e) { Button b = (Button) sender; this.buttonWeb.BackColor = SystemColors.ControlDark; this.buttonCustom.BackColor = SystemColors.ControlDark; this.buttonSystem.BackColor = SystemColors.ControlDark; switch (b.Tag.ToString()) { case "0": this.buttonWeb.BackColor = SystemColors.Control; if (this.radioButtonCont.Checked) { this.colorPanel.ColorSet = ColorSet.Continues; } else { this.colorPanel.ColorSet = ColorSet.Web; } this.radioButtonCont.Enabled = true; break; case "1": this.buttonCustom.BackColor = SystemColors.Control; this.colorPanel.ColorSet = ColorSet.Custom; //this.radioButtonNo.Checked = true; this.radioButtonCont.Enabled = false; break; case "2": this.buttonSystem.BackColor = SystemColors.Control; this.colorPanel.ColorSet = ColorSet.System; //this.radioButtonNo.Checked = true; this.radioButtonCont.Enabled = false; break; } } /// <summary> /// Gets or sets the Border of the panel. /// </summary> /// <remarks> /// The value of type <see cref="System.Windows.Forms.BorderStyle"/> controls the style around /// the embedded color panel, not of the whole control. /// </remarks> public System.Windows.Forms.BorderStyle PanelBorderStyle { get { return colorPanel.BorderStyle; } set { colorPanel.BorderStyle = value; } } /// <summary> /// The current selected color. /// </summary> /// <remarks> /// Gets or sets the color which becomes selected if found on the currently opened panel. /// </remarks> public System.Drawing.Color Color { get { return colorPanel.Color; } set { colorPanel.Color = value; } } /// <summary> /// Gets or sets the color panel. /// </summary> /// <remarks> /// This controls the color display and switches the buttons accordingly the current setting. /// The possible values are: /// <list type="bullet"> /// <item>Web</item> /// <item>System</item> /// <item>Custom</item> /// </list> /// </remarks> public ColorSet ColorSet { get { return colorPanel.ColorSet; } set { colorPanel.ColorSet = value; switch (value) { case ColorSet.Custom: this.buttonCustom.BackColor = SystemColors.Control; this.buttonSystem.BackColor = SystemColors.ControlDark; this.buttonWeb.BackColor = SystemColors.ControlDark; break; case ColorSet.System: this.buttonCustom.BackColor = SystemColors.ControlDark; this.buttonSystem.BackColor = SystemColors.Control; this.buttonWeb.BackColor = SystemColors.ControlDark; break; case ColorSet.Web: this.buttonCustom.BackColor = SystemColors.ControlDark; this.buttonSystem.BackColor = SystemColors.ControlDark; this.buttonWeb.BackColor = SystemColors.Control; break; } } } /// <summary> /// The size of one colored square in pixels. /// </summary> /// <remarks> /// /// </remarks> public System.Drawing.Size ColorWellSize { get { return colorPanel.ColorWellSize; } set { colorPanel.ColorWellSize = value; } } /// <summary> /// Gets or sets the color sort technique. /// </summary> /// <remarks> /// /// </remarks> public ColorSortOrder ColorSortOrder { get { return colorPanel.ColorSortOrder; } set { colorPanel.ColorSortOrder = value; } } /// <summary> /// Gets or sets the number of columns displayed. /// </summary> /// <remarks> /// This value should /// not be changed because the sorted color patterns does not work /// with different column numbers. /// </remarks> public int Columns { get { return colorPanel.Columns; } set { colorPanel.Columns = value; } } /// <summary> /// Gets or sets the custom colors. /// </summary> /// <remarks> /// /// </remarks> public List<Color> CustomColors { get { return colorPanel.CustomColors; } set { colorPanel.CustomColors = value; } } /// <summary> /// Gets or sets the current color. /// </summary> /// <remarks> /// /// </remarks> public System.Drawing.Color CurrentColor { get { return colorPanel.Color; } set { colorPanel.Color = value; } } /// <summary> /// Fired if the color has changed. /// </summary> public event ColorChangedEventHandler ColorChanged; /// <summary> /// Event informs the caller that the user will reset the color. /// </summary> public event ColorCancelEventHandler ColorCancel; private void colorPanel_Resize(object sender, System.EventArgs e) { // make the form the same size as the panel colorPanel.Top = 0; colorPanel.Left = 0; this.Width = colorPanel.Width; this.Height = colorPanel.Height; } private void colorPanel_PanelClosing(object sender, EventArgs e) { } private void buttonNoColor_Click(object sender, System.EventArgs e) { colorPanel.Color = Color.Empty; this.Color = Color.Empty; if (ColorCancel != null) { ColorCancel(this, new ColorChangedEventArgs(Color.Empty)); } } /// <summary> /// Controls visiblity of "Web" button. /// </summary> public bool ButtonWebVisible { set { this.buttonWeb.Visible = value; ArrangeButtons(); } } /// <summary> /// Controls visiblity of "Custom" button. /// </summary> public bool ButtonCustomVisible { set { this.buttonCustom.Visible = value; ArrangeButtons(); } } /// <summary> /// Controls visiblity of "System" button. /// </summary> public bool ButtonSystemVisible { set { this.buttonSystem.Visible = value; ArrangeButtons(); } } private void ArrangeButtons() { int mode = (this.buttonWeb.Visible ? 1 : 0) + (this.buttonCustom.Visible ? 2 : 0) + (this.buttonSystem.Visible ? 4 : 0); this.buttonWeb.Enabled = true; this.buttonCustom.Enabled = true; this.buttonSystem.Enabled = true; switch (mode) { case 0: break; case 1: this.buttonWeb.Width = colorPanel.Width - 2; this.buttonWeb.Left = 2; this.buttonWeb.Enabled = false; break; case 2: this.buttonCustom.Width = colorPanel.Width - 2; this.buttonCustom.Left = 2; this.buttonCustom.Enabled = false; break; case 3: this.buttonWeb.Width = colorPanel.Width / 2 - 2; this.buttonWeb.Left = 2; this.buttonCustom.Width = colorPanel.Width / 2 - 2; this.buttonCustom.Left = this.buttonWeb.Right + 2; break; case 4: this.buttonSystem.Width = colorPanel.Width - 2; this.buttonSystem.Left = 2; this.buttonSystem.Enabled = false; break; case 5: this.buttonWeb.Width = colorPanel.Width / 2 - 2; this.buttonWeb.Left = 2; this.buttonSystem.Width = colorPanel.Width / 2 - 2; this.buttonSystem.Left = this.buttonWeb.Right + 2; break; case 6: this.buttonCustom.Width = colorPanel.Width / 2 - 2; this.buttonCustom.Left = 2; this.buttonSystem.Width = colorPanel.Width / 2 - 2; this.buttonSystem.Left = this.buttonCustom.Right + 2; break; case 7: this.buttonWeb.Width = colorPanel.Width / 3 - 2; this.buttonWeb.Left = 2; this.buttonCustom.Width = colorPanel.Width / 3 - 2; this.buttonCustom.Left = buttonWeb.Right + 2; this.buttonSystem.Width = colorPanel.Width / 3 - 2; this.buttonSystem.Left = buttonCustom.Right + 2; break; } } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERCLevel; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H08_Region (editable child object).<br/> /// This is a generated base class of <see cref="H08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="H09_CityObjects"/> of type <see cref="H09_CityColl"/> (1:M relation to <see cref="H10_City"/>)<br/> /// This class is an item of <see cref="H07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class H08_Region : BusinessBase<H08_Region> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID"); /// <summary> /// Gets the Regions ID. /// </summary> /// <value>The Regions ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name"); /// <summary> /// Gets or sets the Regions Name. /// </summary> /// <value>The Regions Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<H09_Region_Child> H09_Region_SingleObjectProperty = RegisterProperty<H09_Region_Child>(p => p.H09_Region_SingleObject, "H09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the H09 Region Single Object ("self load" child property). /// </summary> /// <value>The H09 Region Single Object.</value> public H09_Region_Child H09_Region_SingleObject { get { return GetProperty(H09_Region_SingleObjectProperty); } private set { LoadProperty(H09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<H09_Region_ReChild> H09_Region_ASingleObjectProperty = RegisterProperty<H09_Region_ReChild>(p => p.H09_Region_ASingleObject, "H09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the H09 Region ASingle Object ("self load" child property). /// </summary> /// <value>The H09 Region ASingle Object.</value> public H09_Region_ReChild H09_Region_ASingleObject { get { return GetProperty(H09_Region_ASingleObjectProperty); } private set { LoadProperty(H09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<H09_CityColl> H09_CityObjectsProperty = RegisterProperty<H09_CityColl>(p => p.H09_CityObjects, "H09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the H09 City Objects ("self load" child property). /// </summary> /// <value>The H09 City Objects.</value> public H09_CityColl H09_CityObjects { get { return GetProperty(H09_CityObjectsProperty); } private set { LoadProperty(H09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="H08_Region"/> object.</returns> internal static H08_Region NewH08_Region() { return DataPortal.CreateChild<H08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="H08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="H08_Region"/> object.</returns> internal static H08_Region GetH08_Region(SafeDataReader dr) { H08_Region obj = new H08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(H09_Region_SingleObjectProperty, DataPortal.CreateChild<H09_Region_Child>()); LoadProperty(H09_Region_ASingleObjectProperty, DataPortal.CreateChild<H09_Region_ReChild>()); LoadProperty(H09_CityObjectsProperty, DataPortal.CreateChild<H09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID")); LoadProperty(Region_NameProperty, dr.GetString("Region_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(H09_Region_SingleObjectProperty, H09_Region_Child.GetH09_Region_Child(Region_ID)); LoadProperty(H09_Region_ASingleObjectProperty, H09_Region_ReChild.GetH09_Region_ReChild(Region_ID)); LoadProperty(H09_CityObjectsProperty, H09_CityColl.GetH09_CityColl(Region_ID)); } /// <summary> /// Inserts a new <see cref="H08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H06_Country parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IH08_RegionDal>(); using (BypassPropertyChecks) { int region_ID = -1; dal.Insert( parent.Country_ID, out region_ID, Region_Name ); LoadProperty(Region_IDProperty, region_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="H08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IH08_RegionDal>(); using (BypassPropertyChecks) { dal.Update( Region_ID, Region_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="H08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IH08_RegionDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Region_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Tasks; using FluentAssertions; using Xunit.Abstractions; using static Neo4j.Driver.IntegrationTests.VersionComparison; using static Neo4j.Driver.IntegrationTests.DatabaseExtensions; using Neo4j.Driver.Internal.Util; using Neo4j.Driver.IntegrationTests.Internals; namespace Neo4j.Driver.IntegrationTests.Direct { public class BoltV4IT : DirectDriverTestBase { public BoltV4IT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabase() { await VerifyDatabaseNameOnSummary(null, "neo4j"); } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecified() { await VerifyDatabaseNameOnSummary("neo4j", "neo4j"); } [RequireEnterpriseEdition("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDatabase() { await CreateDatabase(Server.Driver, "foo"); try { await VerifyDatabaseNameOnSummary("foo", "foo"); } finally { await DropDatabase(Server.Driver, "foo"); } } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabaseInTx() { await VerifyDatabaseNameOnSummaryTx(null, "neo4j"); } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecifiedInTx() { await VerifyDatabaseNameOnSummaryTx("neo4j", "neo4j"); } [RequireEnterpriseEdition("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDatabaseInTx() { await CreateDatabase(Server.Driver, "foo"); try { await VerifyDatabaseNameOnSummaryTx("foo", "foo"); } finally { await DropDatabase(Server.Driver, "foo"); } } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabaseInTxFunc() { await VerifyDatabaseNameOnSummaryTxFunc(null, "neo4j"); } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecifiedInTxFunc() { Console.WriteLine($"Version = {ServerVersion.From(BoltkitHelper.ServerVersion())}"); await VerifyDatabaseNameOnSummaryTxFunc("neo4j", "neo4j"); } [RequireEnterpriseEdition("4.0.0", GreaterThanOrEqualTo)] public async Task ShouldReturnDatabaseInfoForDatabaseInTxFunc() { await CreateDatabase(Server.Driver, "foo"); try { await VerifyDatabaseNameOnSummaryTxFunc("foo", "foo"); } finally { await DropDatabase(Server.Driver, "foo"); } } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public void ShouldThrowForNonExistentDatabase() { this.Awaiting(_ => VerifyDatabaseNameOnSummary("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*database does not exist.*"); } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public void ShouldThrowForNonExistentDatabaseInTx() { this.Awaiting(_ => VerifyDatabaseNameOnSummaryTx("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*database does not exist.*"); } [RequireServerFact("4.0.0", GreaterThanOrEqualTo)] public void ShouldThrowForNonExistentDatabaseInTxFunc() { this.Awaiting(_ => VerifyDatabaseNameOnSummaryTxFunc("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*database does not exist.*"); } [RequireServerFact("4.0.0", VersionComparison.LessThan)] public void ShouldThrowWhenDatabaseIsSpecified() { this.Awaiting(_ => VerifyDatabaseNameOnSummary("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*to a server that does not support multiple databases.*"); } [RequireServerFact("4.0.0", VersionComparison.LessThan)] public void ShouldThrowWhenDatabaseIsSpecifiedInTx() { this.Awaiting(_ => VerifyDatabaseNameOnSummaryTx("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*to a server that does not support multiple databases.*"); } [RequireServerFact("4.0.0", VersionComparison.LessThan)] public void ShouldThrowWhenDatabaseIsSpecifiedInTxFunc() { this.Awaiting(_ => VerifyDatabaseNameOnSummaryTxFunc("bar", "bar")).Should().Throw<ClientException>() .WithMessage("*to a server that does not support multiple databases.*"); } private async Task VerifyDatabaseNameOnSummary(string name, string expected) { var session = Server.Driver.AsyncSession(o => { if (!string.IsNullOrEmpty(name)) { o.WithDatabase(name); } }); try { var cursor = await session.RunAsync("RETURN 1"); var summary = await cursor.ConsumeAsync(); summary.Database.Should().NotBeNull(); summary.Database.Name.Should().Be(expected); } finally { await session.CloseAsync(); } } private async Task VerifyDatabaseNameOnSummaryTx(string name, string expected) { var session = Server.Driver.AsyncSession(o => { if (!string.IsNullOrEmpty(name)) { o.WithDatabase(name); } }); try { var txc = await session.BeginTransactionAsync(); var cursor = await txc.RunAsync("RETURN 1"); var summary = await cursor.ConsumeAsync(); summary.Database.Should().NotBeNull(); summary.Database.Name.Should().Be(expected); await txc.CommitAsync(); } finally { await session.CloseAsync(); } } private async Task VerifyDatabaseNameOnSummaryTxFunc(string name, string expected) { var session = Server.Driver.AsyncSession(o => { if (!string.IsNullOrEmpty(name)) { o.WithDatabase(name); } }); try { var summary = await session.ReadTransactionAsync(async txc => { var cursor = await txc.RunAsync("RETURN 1"); return await cursor.ConsumeAsync(); }); summary.Database.Should().NotBeNull(); summary.Database.Name.Should().Be(expected); } finally { await session.CloseAsync(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // this file contains the data structures for the in memory database // containing display and formatting information using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.PowerShell.Commands; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { internal enum EnumerableExpansion { /// <summary> /// Process core only, ignore IEumerable. /// </summary> CoreOnly, /// <summary> /// Process IEnumerable, ignore core. /// </summary> EnumOnly, /// <summary> /// Process both core and IEnumerable, core first. /// </summary> Both, } #region Type Info Database internal sealed partial class TypeInfoDataBase { // define the sections corresponding the XML file internal DefaultSettingsSection defaultSettingsSection = new DefaultSettingsSection(); internal TypeGroupsSection typeGroupSection = new TypeGroupsSection(); internal ViewDefinitionsSection viewDefinitionsSection = new ViewDefinitionsSection(); internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder(); /// <summary> /// Cache for resource strings in format.ps1xml. /// </summary> internal DisplayResourceManagerCache displayResourceManagerCache = new DisplayResourceManagerCache(); } internal sealed class DatabaseLoadingInfo { internal string fileDirectory = null; internal string filePath = null; internal bool isFullyTrusted = false; internal bool isProductCode = false; internal string xPath = null; internal DateTime loadTime = DateTime.Now; } #endregion #region Default Settings #if _LATER internal class SettableOnceValue<T> { SettableOnceValue (T defaultValue) { this._default = defaultValue; } internal void f(T x) { Nullable<T> y = x; this._value = y; // this._value = (Nullable<T>)x; } internal T Value { /* set { if (_value == null) { this._value = value; } } */ get { if (_value != null) return this._value.Value; return _default; } } private Nullable<T> _value; private T _default; } #endif internal sealed class DefaultSettingsSection { internal bool MultilineTables { set { if (!_multilineTables.HasValue) { _multilineTables = value; } } get { if (_multilineTables.HasValue) return _multilineTables.Value; return false; } } private bool? _multilineTables; internal FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); internal ShapeSelectionDirectives shapeSelectionDirectives = new ShapeSelectionDirectives(); internal List<EnumerableExpansionDirective> enumerableExpansionDirectiveList = new List<EnumerableExpansionDirective>(); } internal sealed class FormatErrorPolicy { /// <summary> /// If true, display error messages. /// </summary> internal bool ShowErrorsAsMessages { set { if (!_showErrorsAsMessages.HasValue) { _showErrorsAsMessages = value; } } get { if (_showErrorsAsMessages.HasValue) return _showErrorsAsMessages.Value; return false; } } private bool? _showErrorsAsMessages; /// <summary> /// If true, display an error string in the formatted display /// (e.g. cell in a table) /// </summary> internal bool ShowErrorsInFormattedOutput { set { if (!_showErrorsInFormattedOutput.HasValue) { _showErrorsInFormattedOutput = value; } } get { if (_showErrorsInFormattedOutput.HasValue) return _showErrorsInFormattedOutput.Value; return false; } } private bool? _showErrorsInFormattedOutput; /// <summary> /// String to display in the formatted display (e.g. cell in a table) /// when the evaluation of a PSPropertyExpression fails. /// </summary> internal string errorStringInFormattedOutput = "#ERR"; /// <summary> /// String to display in the formatted display (e.g. cell in a table) /// when a format operation on a value fails. /// </summary> internal string formatErrorStringInFormattedOutput = "#FMTERR"; } internal sealed class ShapeSelectionDirectives { internal int PropertyCountForTable { set { if (!_propertyCountForTable.HasValue) { _propertyCountForTable = value; } } get { if (_propertyCountForTable.HasValue) return _propertyCountForTable.Value; return 4; } } private int? _propertyCountForTable; internal List<FormatShapeSelectionOnType> formatShapeSelectionOnTypeList = new List<FormatShapeSelectionOnType>(); } internal enum FormatShape { Table, List, Wide, Complex, Undefined } internal abstract class FormatShapeSelectionBase { internal FormatShape formatShape = FormatShape.Undefined; } internal sealed class FormatShapeSelectionOnType : FormatShapeSelectionBase { internal AppliesTo appliesTo; } internal sealed class EnumerableExpansionDirective { internal EnumerableExpansion enumerableExpansion = EnumerableExpansion.EnumOnly; internal AppliesTo appliesTo; } #endregion #region Type Groups Definitions internal sealed class TypeGroupsSection { internal List<TypeGroupDefinition> typeGroupDefinitionList = new List<TypeGroupDefinition>(); } internal sealed class TypeGroupDefinition { internal string name; internal List<TypeReference> typeReferenceList = new List<TypeReference>(); } internal abstract class TypeOrGroupReference { internal string name; /// <summary> /// Optional expression for conditional binding. /// </summary> internal ExpressionToken conditionToken = null; } internal sealed class TypeReference : TypeOrGroupReference { } internal sealed class TypeGroupReference : TypeOrGroupReference { } #endregion #region Elementary Tokens internal abstract class FormatToken { } internal sealed class TextToken : FormatToken { internal string text; internal StringResourceReference resource; } internal sealed class NewLineToken : FormatToken { internal int count = 1; } internal sealed class FrameToken : FormatToken { /// <summary> /// Item associated with this frame definition. /// </summary> internal ComplexControlItemDefinition itemDefinition = new ComplexControlItemDefinition(); /// <summary> /// Frame info associated with this frame definition. /// </summary> internal FrameInfoDefinition frameInfoDefinition = new FrameInfoDefinition(); } internal sealed class FrameInfoDefinition { /// <summary> /// Left indentation for a frame is relative to the parent frame. /// it must be a value >=0. /// </summary> internal int leftIndentation = 0; /// <summary> /// Right indentation for a frame is relative to the parent frame. /// it must be a value >=0. /// </summary> internal int rightIndentation = 0; /// <summary> /// It can have the following values: /// 0 : ignore /// greater than 0 : it represents the indentation for the first line (i.e. "first line indent"). /// The first line will be indented by the indicated number of characters. /// less than 0 : it represents the hanging of the first line WRT the following ones /// (i.e. "first line hanging"). /// </summary> internal int firstLine = 0; } internal sealed class ExpressionToken { internal ExpressionToken() { } internal ExpressionToken(string expressionValue, bool isScriptBlock) { this.expressionValue = expressionValue; this.isScriptBlock = isScriptBlock; } internal bool isScriptBlock; internal string expressionValue; } internal abstract class PropertyTokenBase : FormatToken { /// <summary> /// Optional expression for conditional binding. /// </summary> internal ExpressionToken conditionToken = null; internal ExpressionToken expression = new ExpressionToken(); internal bool enumerateCollection = false; } internal sealed class CompoundPropertyToken : PropertyTokenBase { /// <summary> /// An inline control or a reference to a control definition. /// </summary> internal ControlBase control = null; } internal sealed class FieldPropertyToken : PropertyTokenBase { internal FieldFormattingDirective fieldFormattingDirective = new FieldFormattingDirective(); } internal sealed class FieldFormattingDirective { internal string formatString = null; // optional } #endregion Elementary Tokens #region Control Definitions: common data /// <summary> /// Root class for all the control types. /// </summary> internal abstract class ControlBase { internal static string GetControlShapeName(ControlBase control) { if (control is TableControlBody) { return FormatShape.Table.ToString(); } if (control is ListControlBody) { return FormatShape.List.ToString(); } if (control is WideControlBody) { return FormatShape.Wide.ToString(); } if (control is ComplexControlBody) { return FormatShape.Complex.ToString(); } return string.Empty; } /// <summary> /// Returns a Shallow Copy of the current object. /// </summary> /// <returns></returns> internal virtual ControlBase Copy() { System.Management.Automation.Diagnostics.Assert(false, "This should never be called directly on the base. Let the derived class implement this method."); return this; } } /// <summary> /// Reference to a control. /// </summary> internal sealed class ControlReference : ControlBase { /// <summary> /// Name of the control we refer to, it cannot be null. /// </summary> internal string name = null; /// <summary> /// Type of the control we refer to, it cannot be null. /// </summary> internal Type controlType = null; } /// <summary> /// Base class for all control definitions /// NOTE: this is an extensibility point, if a new control /// needs to be created, it has to be derived from this class. /// </summary> internal abstract class ControlBody : ControlBase { /// <summary> /// RULE: valid only for table and wide only. /// </summary> internal bool? autosize = null; /// <summary> /// RULE: only valid for table. /// </summary> internal bool repeatHeader = false; } /// <summary> /// Class to hold a definition of a control. /// </summary> internal sealed class ControlDefinition { /// <summary> /// Name of the control we define, it cannot be null. /// </summary> internal string name = null; /// <summary> /// Body of the control we define, it cannot be null. /// </summary> internal ControlBody controlBody = null; } #endregion #region View Definitions: common data internal sealed class ViewDefinitionsSection { internal List<ViewDefinition> viewDefinitionList = new List<ViewDefinition>(); } internal sealed partial class AppliesTo { // it can contain either a type or type group reference internal List<TypeOrGroupReference> referenceList = new List<TypeOrGroupReference>(); } internal sealed class GroupBy { internal StartGroup startGroup = new StartGroup(); // NOTE: extension point for describing: // * end group statistics // * end group footer // This can be done with defining a new Type called EndGroup with fields // such as stat and footer. } internal sealed class StartGroup { /// <summary> /// Expression to be used to select the grouping. /// </summary> internal ExpressionToken expression = null; /// <summary> /// An inline control or a reference to a control definition. /// </summary> internal ControlBase control = null; /// <summary> /// Alternative (and simplified) representation for the control /// RULE: if the control object is null, use this one. /// </summary> internal TextToken labelTextToken = null; } /// <summary> /// Container for control definitions. /// </summary> internal sealed class FormatControlDefinitionHolder { /// <summary> /// List of control definitions. /// </summary> internal List<ControlDefinition> controlDefinitionList = new List<ControlDefinition>(); } /// <summary> /// Definition of a view. /// </summary> internal sealed class ViewDefinition { internal DatabaseLoadingInfo loadingInfo; /// <summary> /// The name of this view. Must not be null. /// </summary> internal string name; /// <summary> /// Applicability of the view. Mandatory. /// </summary> internal AppliesTo appliesTo = new AppliesTo(); /// <summary> /// Optional grouping directive. /// </summary> internal GroupBy groupBy; /// <summary> /// Container for optional local formatting directives. /// </summary> internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder(); /// <summary> /// Main control for the view (e.g. reference to a control or a control body. /// </summary> internal ControlBase mainControl; /// <summary> /// RULE: only valid for list and complex. /// </summary> internal bool outOfBand; /// <summary> /// Set if the view is for help output, used so we can prune the view from Get-FormatData /// because those views are too complicated and big for remoting. /// </summary> internal bool isHelpFormatter; internal Guid InstanceId { get; private set; } internal ViewDefinition() { InstanceId = Guid.NewGuid(); } } /// <summary> /// Base class for all the "shape"-Directive classes. /// </summary> internal abstract class FormatDirective { } #endregion #region Localized Resources internal sealed class StringResourceReference { internal DatabaseLoadingInfo loadingInfo = null; internal string assemblyName = null; internal string assemblyLocation = null; internal string baseName = null; internal string resourceId = null; } #endregion } namespace System.Management.Automation { /// <summary> /// Specifies additional type definitions for an object. /// </summary> public sealed class ExtendedTypeDefinition { /// <summary> /// A format definition may apply to multiple types. This api returns /// the first typename that this format definition applies to, but there /// may be other types that apply. <see cref="TypeNames"/> should be /// used instead. /// </summary> public string TypeName { get { return TypeNames[0]; } } /// <summary> /// The list of type names this set of format definitions applies to. /// </summary> public List<string> TypeNames { get; internal set; } /// <summary> /// The formatting view definition for /// the specified type. /// </summary> public List<FormatViewDefinition> FormatViewDefinition { get; internal set; } /// <summary> /// Overloaded to string method for /// better display. /// </summary> /// <returns></returns> public override string ToString() { return TypeName; } /// <summary> /// Constructor for the ExtendedTypeDefinition. /// </summary> /// <param name="typeName"></param> /// <param name="viewDefinitions"></param> public ExtendedTypeDefinition(string typeName, IEnumerable<FormatViewDefinition> viewDefinitions) : this() { if (string.IsNullOrEmpty(typeName)) throw PSTraceSource.NewArgumentNullException("typeName"); if (viewDefinitions == null) throw PSTraceSource.NewArgumentNullException("viewDefinitions"); TypeNames.Add(typeName); foreach (FormatViewDefinition definition in viewDefinitions) { FormatViewDefinition.Add(definition); } } /// <summary> /// Initiate an instance of ExtendedTypeDefinition with the type name. /// </summary> /// <param name="typeName"></param> public ExtendedTypeDefinition(string typeName) : this() { if (string.IsNullOrEmpty(typeName)) throw PSTraceSource.NewArgumentNullException("typeName"); TypeNames.Add(typeName); } internal ExtendedTypeDefinition() { FormatViewDefinition = new List<FormatViewDefinition>(); TypeNames = new List<string>(); } } /// <summary> /// Defines a formatting view for a particular type. /// </summary> [DebuggerDisplay("{Name}")] public sealed class FormatViewDefinition { /// <summary>Name of the formatting view as defined in the formatting file</summary> public string Name { get; private set; } /// <summary>The control defined by this formatting view can be one of table, list, wide, or custom</summary> public PSControl Control { get; private set; } /// <summary>instance id of the original view this will be used to distinguish two views with the same name and control types</summary> internal Guid InstanceId { get; set; } internal FormatViewDefinition(string name, PSControl control, Guid instanceid) { Name = name; Control = control; InstanceId = instanceid; } /// <summary/> public FormatViewDefinition(string name, PSControl control) { if (string.IsNullOrEmpty(name)) throw PSTraceSource.NewArgumentNullException("name"); if (control == null) throw PSTraceSource.NewArgumentNullException("control"); Name = name; Control = control; } } /// <summary> /// Defines a control for the formatting types defined by PowerShell. /// </summary> public abstract class PSControl { /// <summary> /// Each control can group items and specify a header for the group. /// You can group by same property value, or result of evaluating a script block. /// </summary> public PSControlGroupBy GroupBy { get; set; } /// <summary> /// When the "shape" of formatting has been determined by previous objects, /// sometimes you want objects of different types to continue using that shape /// (table, list, or whatever) even if they specify their own views, and sometimes /// you want your view to take over. When OutOfBand is true, the view will apply /// regardless of previous objects that may have selected the shape. /// </summary> public bool OutOfBand { get; set; } internal abstract void WriteToXml(FormatXmlWriter writer); internal virtual bool SafeForExport() { return GroupBy == null || GroupBy.IsSafeForExport(); } internal virtual bool CompatibleWithOldPowerShell() { // This is too strict, the GroupBy would just be ignored by the remote // PowerShell, but that's still wrong. // OutOfBand is also ignored by old PowerShell, but it's of less importance. return GroupBy == null; } } /// <summary> /// Allows specifying a header for groups of related objects being formatted, can /// be specified on any type of PSControl. /// </summary> public sealed class PSControlGroupBy { /// <summary> /// Specifies the property or expression (script block) that controls grouping. /// </summary> public DisplayEntry Expression { get; set; } /// <summary> /// Optional - used to specify a label for the header of a group. /// </summary> public string Label { get; set; } /// <summary> /// Optional - used to format the header of a group. /// </summary> public CustomControl CustomControl { get; set; } internal bool IsSafeForExport() { return (Expression == null || Expression.SafeForExport()) && (CustomControl == null || CustomControl.SafeForExport()); } internal static PSControlGroupBy Get(GroupBy groupBy) { if (groupBy != null) { // TODO - groupBy.startGroup.control var expressionToken = groupBy.startGroup.expression; return new PSControlGroupBy { Expression = new DisplayEntry(expressionToken), Label = (groupBy.startGroup.labelTextToken != null) ? groupBy.startGroup.labelTextToken.text : null }; } return null; } } /// <summary> /// One entry in a format display unit, script block or property name. /// </summary> public sealed class DisplayEntry { /// <summary>Returns the type of this value</summary> public DisplayEntryValueType ValueType { get; internal set; } /// <summary>Returns the value as a string</summary> public string Value { get; internal set; } internal DisplayEntry() { } /// <summary>Public constructor for DisplayEntry</summary> public DisplayEntry(string value, DisplayEntryValueType type) { if (string.IsNullOrEmpty(value)) if (value == null || type == DisplayEntryValueType.Property) throw PSTraceSource.NewArgumentNullException("value"); Value = value; ValueType = type; } /// <summary/> public override string ToString() { return (ValueType == DisplayEntryValueType.Property ? "property: " : "script: ") + Value; } internal DisplayEntry(ExpressionToken expression) { Value = expression.expressionValue; ValueType = expression.isScriptBlock ? DisplayEntryValueType.ScriptBlock : DisplayEntryValueType.Property; if (string.IsNullOrEmpty(Value)) if (Value == null || ValueType == DisplayEntryValueType.Property) throw PSTraceSource.NewArgumentNullException("value"); } internal bool SafeForExport() { return ValueType != DisplayEntryValueType.ScriptBlock; } } /// <summary> /// Each control (table, list, wide, or custom) may have multiple entries. If there are multiple /// entries, there must be a default entry with no condition, all other entries must have EntrySelectedBy /// specified. This is useful when you need a single view for grouping or otherwise just selecting the /// shape of formatting, but need distinct formatting rules for each instance. For example, when /// listing files, you may want to group based on the parent path, but select different entries /// depending on if the item is a file or directory. /// </summary> public sealed class EntrySelectedBy { /// <summary> /// An optional list of typenames that apply to the entry. /// </summary> public List<string> TypeNames { get; set; } /// <summary> /// An optional condition that applies to the entry. /// </summary> public List<DisplayEntry> SelectionCondition { get; set; } internal static EntrySelectedBy Get(IEnumerable<string> entrySelectedByType, IEnumerable<DisplayEntry> entrySelectedByCondition) { EntrySelectedBy result = null; if (entrySelectedByType != null || entrySelectedByCondition != null) { result = new EntrySelectedBy(); bool isEmpty = true; if (entrySelectedByType != null) { result.TypeNames = new List<string>(entrySelectedByType); if (result.TypeNames.Count > 0) isEmpty = false; } if (entrySelectedByCondition != null) { result.SelectionCondition = new List<DisplayEntry>(entrySelectedByCondition); if (result.SelectionCondition.Count > 0) isEmpty = false; } if (isEmpty) return null; } return result; } internal static EntrySelectedBy Get(List<TypeOrGroupReference> references) { EntrySelectedBy result = null; if (references != null && references.Count > 0) { result = new EntrySelectedBy(); foreach (TypeOrGroupReference tr in references) { if (tr.conditionToken != null) { if (result.SelectionCondition == null) result.SelectionCondition = new List<DisplayEntry>(); result.SelectionCondition.Add(new DisplayEntry(tr.conditionToken)); continue; } if (tr is TypeGroupReference) continue; if (result.TypeNames == null) result.TypeNames = new List<string>(); result.TypeNames.Add(tr.name); } } return result; } internal bool SafeForExport() { if (SelectionCondition == null) return true; foreach (var cond in SelectionCondition) { if (!cond.SafeForExport()) return false; } return true; } internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell know nothing about selection conditions. return SelectionCondition == null || SelectionCondition.Count == 0; } } /// <summary> /// Specifies possible alignment enumerations for display cells. /// </summary> public enum Alignment { /// <summary> /// Not defined. /// </summary> Undefined = 0, /// <summary> /// Left of the cell, contents will trail with a ... if exceeded - ex "Display..." /// </summary> Left = 1, /// <summary> /// Center of the cell. /// </summary> Center = 2, /// <summary> /// Right of the cell, contents will lead with a ... if exceeded - ex "...456" /// </summary> Right = 3, } /// <summary> /// Specifies the type of entry value. /// </summary> public enum DisplayEntryValueType { /// <summary> /// The value is a property. Look for a property with the specified name. /// </summary> Property = 0, /// <summary> /// The value is a scriptblock. Evaluate the script block and fill the entry with the result. /// </summary> ScriptBlock = 1, } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace Aurora.Modules.Chat { public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule { #region Delegates /// <summary> /// delegate for sending a grid instant message asynchronously /// </summary> public delegate void GridInstantMessageDelegate( GridInstantMessage im, GridRegion prevRegion); #endregion /// <summary> /// Param UUID - AgentID /// Param string - HTTP path to the region the user is in, blank if not found /// </summary> public Dictionary<UUID, string> IMUsersCache = new Dictionary<UUID, string>(); private bool m_Enabled; protected List<IScene> m_Scenes = new List<IScene>(); #region IMessageTransferModule Members public event UndeliveredMessage OnUndeliveredMessage; public virtual void SendInstantMessages(GridInstantMessage im, List<UUID> AgentsToSendTo) { //Check for local users first List<UUID> RemoveUsers = new List<UUID>(); foreach (IScene scene in m_Scenes) { foreach (UUID t in AgentsToSendTo) { IScenePresence user; if (!RemoveUsers.Contains(t) && scene.TryGetScenePresence(t, out user)) { // Local message user.ControllingClient.SendInstantMessage(im); RemoveUsers.Add(t); } } } //Clear the local users out foreach (UUID agentID in RemoveUsers) { AgentsToSendTo.Remove(agentID); } SendMultipleGridInstantMessageViaXMLRPC(im, AgentsToSendTo); } public virtual void SendInstantMessage(GridInstantMessage im) { UUID toAgentID = im.toAgentID; //Look locally first foreach (IScene scene in m_Scenes) { IScenePresence user; if (scene.TryGetScenePresence(toAgentID, out user)) { user.ControllingClient.SendInstantMessage(im); return; } ISceneChildEntity childPrim = null; if ((childPrim = scene.GetSceneObjectPart(toAgentID)) != null) { im.toAgentID = childPrim.OwnerID; SendInstantMessage(im); return; } } //MainConsole.Instance.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID); SendGridInstantMessageViaXMLRPC(im); } #endregion #region ISharedRegionModule Members public virtual void Initialise(IConfigSource config) { IConfig cnf = config.Configs["Messaging"]; if (cnf != null && cnf.GetString( "MessageTransferModule", "MessageTransferModule") != "MessageTransferModule") { MainConsole.Instance.Debug("[MESSAGE TRANSFER]: Disabled by configuration"); return; } m_Enabled = true; } public virtual void AddRegion(IScene scene) { if (!m_Enabled) return; lock (m_Scenes) { //MainConsole.Instance.Debug("[MESSAGE TRANSFER]: Message transfer module active"); scene.RegisterModuleInterface<IMessageTransferModule>(this); m_Scenes.Add(scene); } } public virtual void PostInitialise() { if (!m_Enabled) return; MainServer.Instance.AddXmlRPCHandler( "grid_instant_message", processXMLRPCGridInstantMessage); } public virtual void RegionLoaded(IScene scene) { } public virtual void RemoveRegion(IScene scene) { if (!m_Enabled) return; lock (m_Scenes) m_Scenes.Remove(scene); } public virtual void Close() { } public virtual string Name { get { return "MessageTransferModule"; } } public virtual Type ReplaceableInterface { get { return null; } } #endregion private void HandleUndeliveredMessage(GridInstantMessage im, string reason) { UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage; // If this event has handlers, then an IM from an agent will be // considered delivered. This will suppress the error message. // if (handlerUndeliveredMessage != null) { handlerUndeliveredMessage(im, reason); return; } //MainConsole.Instance.DebugFormat("[INSTANT MESSAGE]: Undeliverable"); } /// <summary> /// Process a XMLRPC Grid Instant Message /// </summary> /// <param name = "request">XMLRPC parameters /// </param> /// <param name="remoteClient"> </param> /// <returns>Nothing much</returns> protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient) { bool successful = false; GridInstantMessage gim = new GridInstantMessage(); Hashtable requestData = (Hashtable) request.Params[0]; if (requestData.ContainsKey("message")) { try { //Deserialize it gim.FromOSD((OSDMap) OSDParser.DeserializeJson(requestData["message"].ToString())); } catch { UUID fromAgentID = UUID.Zero; UUID toAgentID = UUID.Zero; UUID imSessionID = UUID.Zero; uint timestamp = 0; string fromAgentName = ""; string message = ""; byte dialog = (byte) 0; bool fromGroup = false; byte offline = 0; uint ParentEstateID = 0; Vector3 Position = Vector3.Zero; UUID RegionID = UUID.Zero; byte[] binaryBucket = new byte[0]; float pos_x = 0; float pos_y = 0; float pos_z = 0; if (requestData.ContainsKey("from_agent_id") && requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id") && requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name") && requestData.ContainsKey("message") && requestData.ContainsKey("dialog") && requestData.ContainsKey("from_group") && requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id") && requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y") && requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id") && requestData.ContainsKey("binary_bucket")) { // Do the easy way of validating the UUIDs UUID.TryParse((string) requestData["from_agent_id"], out fromAgentID); UUID.TryParse((string) requestData["to_agent_id"], out toAgentID); UUID.TryParse((string) requestData["im_session_id"], out imSessionID); UUID.TryParse((string) requestData["region_id"], out RegionID); try { timestamp = (uint) Convert.ToInt32((string) requestData["timestamp"]); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } fromAgentName = (string) requestData["from_agent_name"]; message = (string) requestData["message"]; if (message == null) message = string.Empty; // Bytes don't transfer well over XMLRPC, so, we Base64 Encode them. string requestData1 = (string) requestData["dialog"]; if (string.IsNullOrEmpty(requestData1)) { dialog = 0; } else { byte[] dialogdata = Convert.FromBase64String(requestData1); dialog = dialogdata[0]; } if ((string) requestData["from_group"] == "TRUE") fromGroup = true; string requestData2 = (string) requestData["offline"]; if (String.IsNullOrEmpty(requestData2)) { offline = 0; } else { byte[] offlinedata = Convert.FromBase64String(requestData2); offline = offlinedata[0]; } try { ParentEstateID = (uint) Convert.ToInt32((string) requestData["parent_estate_id"]); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } try { pos_x = (uint) Convert.ToInt32((string) requestData["position_x"]); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } try { pos_y = (uint) Convert.ToInt32((string) requestData["position_y"]); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } try { pos_z = (uint) Convert.ToInt32((string) requestData["position_z"]); } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } Position = new Vector3(pos_x, pos_y, pos_z); string requestData3 = (string) requestData["binary_bucket"]; binaryBucket = string.IsNullOrEmpty(requestData3) ? new byte[0] : Convert.FromBase64String(requestData3); // Create a New GridInstantMessageObject the the data gim.fromAgentID = fromAgentID; gim.fromAgentName = fromAgentName; gim.fromGroup = fromGroup; gim.imSessionID = imSessionID; gim.RegionID = UUID.Zero; // RegionID.Guid; gim.timestamp = timestamp; gim.toAgentID = toAgentID; gim.message = message; gim.dialog = dialog; gim.offline = 0; gim.ParentEstateID = ParentEstateID; gim.Position = Position; gim.binaryBucket = binaryBucket; } } if (gim.dialog == (byte) InstantMessageDialog.GodLikeRequestTeleport) gim.dialog = (byte) InstantMessageDialog.RequestTeleport; // Trigger the Instant message in the scene. foreach (IScene scene in m_Scenes) { IScenePresence user; if (scene.TryGetScenePresence(gim.toAgentID, out user)) { if (!user.IsChildAgent) { scene.EventManager.TriggerIncomingInstantMessage(gim); successful = true; } } } if (!successful) { // If the message can't be delivered to an agent, it // is likely to be a group IM. On a group IM, the // imSessionID = toAgentID = group id. Raise the // unhandled IM event to give the groups module // a chance to pick it up. We raise that in a random // scene, since the groups module is shared. // m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim); } } //Send response back to region calling if it was successful // calling region uses this to know when to look up a user's location again. XmlRpcResponse resp = new XmlRpcResponse(); Hashtable respdata = new Hashtable(); if (successful) respdata["success"] = "TRUE"; else respdata["success"] = "FALSE"; resp.Value = respdata; return resp; } protected virtual void GridInstantMessageCompleted(IAsyncResult iar) { GridInstantMessageDelegate icon = (GridInstantMessageDelegate) iar.AsyncState; icon.EndInvoke(iar); } protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im) { GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync; d.BeginInvoke(im, null, GridInstantMessageCompleted, d); } protected virtual void SendMultipleGridInstantMessageViaXMLRPC(GridInstantMessage im, List<UUID> users) { Dictionary<UUID, string> HTTPPaths = new Dictionary<UUID, string>(); foreach (UUID agentID in users) { lock (IMUsersCache) { string HTTPPath = ""; if (!IMUsersCache.TryGetValue(agentID, out HTTPPath)) HTTPPath = ""; else HTTPPaths.Add(agentID, HTTPPath); } } List<UUID> CompletedUsers = new List<UUID>(); foreach (KeyValuePair<UUID, string> kvp in HTTPPaths) { //Fix the agentID im.toAgentID = kvp.Key; Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); //We've tried to send an IM to them before, pull out their info //Send the IM to their last location if (!doIMSending(kvp.Value, msgdata)) { msgdata = ConvertGridInstantMessageToXMLRPCXML(im); if (!doIMSending(kvp.Value, msgdata)) { //If this fails, the user has either moved from their stored location or logged out //Since it failed, let it look them up again and rerun lock (IMUsersCache) { IMUsersCache.Remove(kvp.Key); } } } else { //Send the IM, and it made it to the user, return true CompletedUsers.Add(kvp.Key); } } //Remove the finished users foreach (UUID agentID in CompletedUsers) { users.Remove(agentID); } HTTPPaths.Clear(); //Now query the grid server for the agents #if (!ISWIN) List<string> Queries = new List<string>(); foreach (UUID agentId in users) Queries.Add(agentId.ToString()); #else List<string> Queries = users.Select(agentID => agentID.ToString()).ToList(); #endif if (Queries.Count == 0) return; //All done //Ask for the user new style first List<string> AgentLocations = m_Scenes[0].RequestModuleInterface<IAgentInfoService>().GetAgentsLocations(im.fromAgentID.ToString(), Queries); //If this is false, this doesn't exist on the presence server and we use the legacy way if (AgentLocations.Count != 0) { for (int i = 0; i < users.Count; i++) { //No agents, so this user is offline if (AgentLocations[i] == "NotOnline") { IMUsersCache.Remove(users[i]); MainConsole.Instance.Debug("[GRID INSTANT MESSAGE]: Unable to deliver an instant message to " + users[i] + ", user was not online"); im.toAgentID = users[i]; HandleUndeliveredMessage(im, "User is not set as online by presence service."); continue; } if (AgentLocations[i] == "NonExistant") { IMUsersCache.Remove(users[i]); MainConsole.Instance.Info("[GRID INSTANT MESSAGE]: Unable to deliver an instant message to " + users[i] + ", user does not exist"); im.toAgentID = users[i]; HandleUndeliveredMessage(im, "User does not exist."); continue; } HTTPPaths.Add(users[i], AgentLocations[i]); } } else { MainConsole.Instance.Info("[GRID INSTANT MESSAGE]: Unable to deliver an instant message, no users found."); return; } //We found the agent's location, now ask them about the user foreach (KeyValuePair<UUID, string> kvp in HTTPPaths) { if (kvp.Value != "") { im.toAgentID = kvp.Key; Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); if (!doIMSending(kvp.Value, msgdata)) { msgdata = ConvertGridInstantMessageToXMLRPCXML(im); if (!doIMSending(kvp.Value, msgdata)) { //It failed lock (IMUsersCache) { //Remove them so we keep testing against the db IMUsersCache.Remove(kvp.Key); } HandleUndeliveredMessage(im, "Failed to send IM to destination."); } } else { //Add to the cache if (!IMUsersCache.ContainsKey(kvp.Key)) IMUsersCache.Add(kvp.Key, kvp.Value); //Send the IM, and it made it to the user, return true continue; } } else { lock (IMUsersCache) { //Remove them so we keep testing against the db IMUsersCache.Remove(kvp.Key); } HandleUndeliveredMessage(im, "Agent Location was blank."); } } } /// <summary> /// Recursive SendGridInstantMessage over XMLRPC method. /// This is called from within a dedicated thread. /// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from /// itself, prevRegionHandle will be the last region handle that we tried to send. /// If the handles are the same, we look up the user's location using the grid. /// If the handles are still the same, we end. The send failed. /// </summary> /// <param name = "prevRegionHandle"> /// Pass in 0 the first time this method is called. It will be called recursively with the last /// regionhandle tried /// </param> protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, GridRegion prevRegion) { UUID toAgentID = im.toAgentID; string HTTPPath = ""; Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im); lock (IMUsersCache) { if (!IMUsersCache.TryGetValue(toAgentID, out HTTPPath)) HTTPPath = ""; } if (HTTPPath != "") { //We've tried to send an IM to them before, pull out their info //Send the IM to their last location if (!doIMSending(HTTPPath, msgdata)) { msgdata = ConvertGridInstantMessageToXMLRPCXML(im); if (!doIMSending(HTTPPath, msgdata)) { //If this fails, the user has either moved from their stored location or logged out //Since it failed, let it look them up again and rerun lock (IMUsersCache) { IMUsersCache.Remove(toAgentID); } //Clear the path and let it continue trying again. HTTPPath = ""; } } else { //Send the IM, and it made it to the user, return true return; } } //Now query the grid server for the agent IAgentInfoService ais = m_Scenes[0].RequestModuleInterface<IAgentInfoService>(); List<string> AgentLocations = ais.GetAgentsLocations(im.fromAgentID.ToString(), new List<string>(new[] { toAgentID.ToString() })); if (AgentLocations.Count > 0) { //No agents, so this user is offline if (AgentLocations[0] == "NotOnline") { lock (IMUsersCache) { //Remove them so we keep testing against the db IMUsersCache.Remove(toAgentID); } MainConsole.Instance.Info("[GRID INSTANT MESSAGE]: Unable to deliver an instant message"); HandleUndeliveredMessage(im, "User is not set as online by presence service."); return; } if (AgentLocations[0] == "NonExistant") { IMUsersCache.Remove(toAgentID); MainConsole.Instance.Info("[GRID INSTANT MESSAGE]: Unable to deliver an instant message to " + toAgentID + ", user does not exist"); HandleUndeliveredMessage(im, "User does not exist."); return; } HTTPPath = AgentLocations[0]; } //We found the agent's location, now ask them about the user if (HTTPPath != "") { if (!doIMSending(HTTPPath, msgdata)) { msgdata = ConvertGridInstantMessageToXMLRPCXML(im); if (!doIMSending(HTTPPath, msgdata)) { //It failed, stop now lock (IMUsersCache) { //Remove them so we keep testing against the db IMUsersCache.Remove(toAgentID); } MainConsole.Instance.Info( "[GRID INSTANT MESSAGE]: Unable to deliver an instant message as the region could not be found"); HandleUndeliveredMessage(im, "Failed to send IM to destination."); return; } } else { //Add to the cache if (!IMUsersCache.ContainsKey(toAgentID)) IMUsersCache.Add(toAgentID, HTTPPath); //Send the IM, and it made it to the user, return true return; } } else { //Couldn't find them, stop for now lock (IMUsersCache) { //Remove them so we keep testing against the db IMUsersCache.Remove(toAgentID); } MainConsole.Instance.Info( "[GRID INSTANT MESSAGE]: Unable to deliver an instant message as the region could not be found"); HandleUndeliveredMessage(im, "Agent Location was blank."); } } /// <summary> /// This actually does the XMLRPC Request /// </summary> /// <param name = "httpInfo">RegionInfo we pull the data out of to send the request to</param> /// <param name = "xmlrpcdata">The Instant Message data Hashtable</param> /// <returns>Bool if the message was successfully delivered at the other side.</returns> protected virtual bool doIMSending(string httpInfo, Hashtable xmlrpcdata) { ArrayList SendParams = new ArrayList {xmlrpcdata}; XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams); try { XmlRpcResponse GridResp = GridReq.Send(httpInfo, 7000); Hashtable responseData = (Hashtable) GridResp.Value; if (responseData.ContainsKey("success")) { if ((string) responseData["success"] == "TRUE") return true; return false; } return false; } catch (WebException e) { MainConsole.Instance.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to " + httpInfo, e.Message); } return false; } /// <summary> /// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC /// </summary> /// <param name = "msg">The GridInstantMessage object</param> /// <returns>Hashtable containing the XMLRPC request</returns> protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg) { Hashtable gim = new Hashtable(); gim["message"] = OSDParser.SerializeJsonString(msg.ToOSD()); return gim; } protected virtual Hashtable ConvertGridInstantMessageToXMLRPCXML(GridInstantMessage msg) { Hashtable gim = new Hashtable(); gim["from_agent_id"] = msg.fromAgentID.ToString(); // Kept for compatibility gim["from_agent_session"] = UUID.Zero.ToString(); gim["to_agent_id"] = msg.toAgentID.ToString(); gim["im_session_id"] = msg.imSessionID.ToString(); gim["timestamp"] = msg.timestamp.ToString(); gim["from_agent_name"] = msg.fromAgentName; gim["message"] = msg.message; byte[] dialogdata = new byte[1]; dialogdata[0] = msg.dialog; gim["dialog"] = Convert.ToBase64String(dialogdata, Base64FormattingOptions.None); if (msg.fromGroup) gim["from_group"] = "TRUE"; else gim["from_group"] = "FALSE"; byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline; gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None); gim["parent_estate_id"] = msg.ParentEstateID.ToString(); gim["position_x"] = msg.Position.X.ToString(); gim["position_y"] = msg.Position.Y.ToString(); gim["position_z"] = msg.Position.Z.ToString(); gim["region_id"] = msg.RegionID.ToString(); gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket, Base64FormattingOptions.None); return gim; } } }
using System; using System.Collections.Generic; using System.Linq; using Plugin.Connectivity.Abstractions; using Windows.Networking.Connectivity; using System.Threading.Tasks; using Windows.Networking.Sockets; using Windows.Networking; using System.Diagnostics; using Windows.ApplicationModel.Core; namespace Plugin.Connectivity { /// <summary> /// Connectivity Implementation for WinRT /// </summary> public class ConnectivityImplementation : BaseConnectivity { bool isConnected; /// <summary> /// Default constructor /// </summary> public ConnectivityImplementation() { isConnected = IsConnected; NetworkInformation.NetworkStatusChanged += NetworkStatusChanged; } async void NetworkStatusChanged(object sender) { var previous = isConnected; var newConnected = IsConnected; var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher; if (dispatcher != null) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (previous != newConnected) OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected }); OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = newConnected, ConnectionTypes = this.ConnectionTypes }); }); } else { if (previous != newConnected) OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = newConnected }); OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = newConnected, ConnectionTypes = this.ConnectionTypes }); } } /// <summary> /// Gets if there is an active internet connection /// </summary> public override bool IsConnected { get { var profile = NetworkInformation.GetInternetConnectionProfile(); if (profile == null) isConnected = false; else isConnected = profile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None; return isConnected; } } /// <summary> /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false. /// You can use it to check remote calls though. /// </summary> /// <param name="host"></param> /// <param name="msTimeout"></param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; try { var serverHost = new HostName(host); using (var client = new StreamSocket()) { await client.ConnectAsync(serverHost, "http"); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } } /// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty). TrimEnd('/'); try { using (var tcpClient = new StreamSocket()) { await tcpClient.ConnectAsync( new Windows.Networking.HostName(host), port.ToString(), SocketProtectionLevel.PlainSocket); var localIp = tcpClient.Information.LocalAddress.DisplayName; var remoteIp = tcpClient.Information.RemoteAddress.DisplayName; tcpClient.Dispose(); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } } /// <summary> /// Gets the list of all active connection types. /// </summary> public override IEnumerable<ConnectionType> ConnectionTypes { get { var networkInterfaceList = NetworkInformation.GetConnectionProfiles(); foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)) { var type = ConnectionType.Other; if (networkInterfaceInfo.NetworkAdapter != null) { switch (networkInterfaceInfo.NetworkAdapter.IanaInterfaceType) { case 6: type = ConnectionType.Desktop; break; case 71: type = ConnectionType.WiFi; break; case 243: case 244: type = ConnectionType.Cellular; break; } } yield return type; } } } /// <summary> /// Retrieves a list of available bandwidths for the platform. /// Only active connections. /// </summary> public override IEnumerable<UInt64> Bandwidths { get { var networkInterfaceList = NetworkInformation.GetConnectionProfiles(); foreach (var networkInterfaceInfo in networkInterfaceList.Where(networkInterfaceInfo => networkInterfaceInfo.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)) { UInt64 speed = 0; if (networkInterfaceInfo.NetworkAdapter != null) { speed = (UInt64)networkInterfaceInfo.NetworkAdapter.OutboundMaxBitsPerSecond; } yield return speed; } } } private bool disposed = false; /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> public override void Dispose(bool disposing) { if (!disposed) { if (disposing) { NetworkInformation.NetworkStatusChanged -= NetworkStatusChanged; } disposed = true; } base.Dispose(disposing); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; using System.Management.Automation.Tracing; using System.Security; using System.Threading; using System.Globalization; namespace System.Management.Automation { /// <summary> /// Monad Logging in general is a two layer architecture. At the upper layer are the /// Msh Log Engine and Logging Api. At the lower layer is the Provider Interface /// and Log Providers. This architecture is adopted to achieve independency between /// Monad logging and logging details of different logging technology. /// /// This file implements the upper layer of the Monad Logging architecture. /// Lower layer of Msh Log architecture is implemented in LogProvider.cs file. /// /// Logging Api is made up of following five sets /// 1. Engine Health Event /// 2. Engine Lifecycle Event /// 3. Command Lifecycle Event /// 4. Provider Lifecycle Event /// 5. Settings Event /// /// Msh Log Engine provides features in following areas, /// 1. Loading and managing logging providers. Based on some "Provider Catalog", engine will try to /// load providers. First provider that is successfully loaded will be used for low level logging. /// If no providers can be loaded, a dummy provider will be used, which will essentially do nothing. /// 2. Implementation of logging api functions. These api functions is implemented by calling corresponding /// functions in provider interface. /// 3. Sequence Id Generation. Unique id are generated in this class. These id's will be attached to events. /// 4. Monad engine state management. Engine state is stored in ExecutionContext class but managed here. /// Later on, this feature may be moved to engine itself (where it should belongs to) when sophisticated /// engine state model is established. /// 5. Logging policy support. Events are logged or not logged based on logging policy settings (which is stored /// in session state of the engine. /// /// MshLog class is defined as a static class. This essentially make the logging api to be a static api. /// /// We want to provide sufficient synchronization for static functions calls. /// This is not needed for now because of following two reasons, /// a. Currently, only one monad engine can be running in one process. So logically only one /// event will be log at a time. /// b. Even in the case of multiple events are logged, underlining logging media should /// provide synchronization. /// </summary> internal static class MshLog { #region Initialization /// <summary> /// A static dictionary to keep track of log providers for different shellId's. /// /// The value of this dictionary is never empty. A value of type DummyProvider means /// no logging. /// </summary> private static ConcurrentDictionary<string, Collection<LogProvider>> s_logProviders = new ConcurrentDictionary<string, Collection<LogProvider>>(); private const string _crimsonLogProviderAssemblyName = "MshCrimsonLog"; private const string _crimsonLogProviderTypeName = "System.Management.Automation.Logging.CrimsonLogProvider"; private static Collection<string> s_ignoredCommands = new Collection<string>(); /// <summary> /// Static constructor. /// </summary> static MshLog() { s_ignoredCommands.Add("Out-Lineoutput"); s_ignoredCommands.Add("Format-Default"); } /// <summary> /// Currently initialization is done in following sequence /// a. Try to load CrimsonLogProvider (in the case of Longhorn) /// b. If a fails, use the DummyLogProvider instead. (in low-level OS) /// /// In the longer turn, we may need to use a "Provider Catalog" for /// log provider loading. /// </summary> /// <param name="shellId"></param> /// <returns></returns> private static IEnumerable<LogProvider> GetLogProvider(string shellId) { return s_logProviders.GetOrAdd(shellId, CreateLogProvider); } /// <summary> /// Get Log Provider based on Execution Context. /// </summary> /// <param name="executionContext"></param> /// <returns></returns> private static IEnumerable<LogProvider> GetLogProvider(ExecutionContext executionContext) { if (executionContext == null) { throw PSTraceSource.NewArgumentNullException("executionContext"); } string shellId = executionContext.ShellID; return GetLogProvider(shellId); } /// <summary> /// Get Log Provider based on Log Context. /// </summary> /// <param name="logContext"></param> /// <returns></returns> private static IEnumerable<LogProvider> GetLogProvider(LogContext logContext) { System.Diagnostics.Debug.Assert(logContext != null); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(logContext.ShellId)); return GetLogProvider(logContext.ShellId); } /// <summary> /// Create a log provider based on a shell Id. /// </summary> /// <param name="shellId"></param> /// <returns></returns> private static Collection<LogProvider> CreateLogProvider(string shellId) { Collection<LogProvider> providers = new Collection<LogProvider>(); // Porting note: Linux does not support ETW try { #if !CORECLR // TODO:CORECLR EventLogLogProvider not handled yet LogProvider eventLogLogProvider = new EventLogLogProvider(shellId); providers.Add(eventLogLogProvider); #endif #if UNIX LogProvider sysLogProvider = new PSSysLogProvider(); providers.Add(sysLogProvider); #else LogProvider etwLogProvider = new PSEtwLogProvider(); providers.Add(etwLogProvider); #endif return providers; } catch (ArgumentException) { } catch (InvalidOperationException) { } catch (SecurityException) { // This exception will happen if we try to create an event source // (corresponding to the current running minishell) // when running as non-admin user. In that case, we will default // to dummy log. } providers.Add(new DummyLogProvider()); return providers; } /// <summary> /// This will set the current log provider to be dummy log. /// </summary> /// <param name="shellId"></param> internal static void SetDummyLog(string shellId) { Collection<LogProvider> providers = new Collection<LogProvider> { new DummyLogProvider() }; s_logProviders.AddOrUpdate(shellId, providers, (key, value) => providers); } #endregion #region Engine Health Event Logging Api /// <summary> /// LogEngineHealthEvent: Log an engine health event. If engine state is changed, a engine /// lifecycle event will be logged also. /// /// This is the basic form of EngineHealthEvent logging api, in which all parameters are provided. /// /// Variant form of this function is defined below, which will make parameters additionalInfo /// and newEngineState optional. /// </summary> /// <param name="executionContext">Execution context for the engine that is running.</param> /// <param name="eventId">EventId for the event to be logged.</param> /// <param name="exception">Exception associated with this event.</param> /// <param name="severity">Severity of this event.</param> /// <param name="additionalInfo">Additional information for this event.</param> /// <param name="newEngineState">New engine state.</param> internal static void LogEngineHealthEvent(ExecutionContext executionContext, int eventId, Exception exception, Severity severity, Dictionary<string, string> additionalInfo, EngineState newEngineState) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } if (exception == null) { PSTraceSource.NewArgumentNullException("exception"); return; } InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogEngineHealthEvent(provider, executionContext)) { provider.LogEngineHealthEvent(GetLogContext(executionContext, invocationInfo, severity), eventId, exception, additionalInfo); } } if (newEngineState != EngineState.None) { LogEngineLifecycleEvent(executionContext, newEngineState, invocationInfo); } } /// <summary> /// This is a variation of LogEngineHealthEvent api to make additionalInfo and newEngineState /// optional. /// </summary> /// <param name="executionContext"></param> /// <param name="eventId"></param> /// <param name="exception"></param> /// <param name="severity"></param> internal static void LogEngineHealthEvent(ExecutionContext executionContext, int eventId, Exception exception, Severity severity) { LogEngineHealthEvent(executionContext, eventId, exception, severity, null); } /// <summary> /// This is a variation of LogEngineHealthEvent api to make eventid, additionalInfo and newEngineState /// optional. /// /// A default event id for engine health event will be used. /// </summary> /// <param name="executionContext"></param> /// <param name="exception"></param> /// <param name="severity"></param> internal static void LogEngineHealthEvent(ExecutionContext executionContext, Exception exception, Severity severity) { LogEngineHealthEvent(executionContext, 100, exception, severity, null); } /// <summary> /// This is a variation of LogEngineHealthEvent api to make newEngineState /// optional. /// </summary> /// <param name="executionContext"></param> /// <param name="eventId"></param> /// <param name="exception"></param> /// <param name="severity"></param> /// <param name="additionalInfo"></param> internal static void LogEngineHealthEvent(ExecutionContext executionContext, int eventId, Exception exception, Severity severity, Dictionary<string, string> additionalInfo) { LogEngineHealthEvent(executionContext, eventId, exception, severity, additionalInfo, EngineState.None); } /// <summary> /// This is a variation of LogEngineHealthEvent api to make additionalInfo /// optional. /// </summary> /// <param name="executionContext"></param> /// <param name="eventId"></param> /// <param name="exception"></param> /// <param name="severity"></param> /// <param name="newEngineState"></param> internal static void LogEngineHealthEvent(ExecutionContext executionContext, int eventId, Exception exception, Severity severity, EngineState newEngineState) { LogEngineHealthEvent(executionContext, eventId, exception, severity, null, newEngineState); } /// <summary> /// LogEngineHealthEvent: This is an API for logging engine health event while execution context /// is not available. In this case, caller of this API will directly construct LogContext /// instance. /// /// This API is currently used only by runspace before engine start. /// </summary> /// <param name="logContext">LogContext to be.</param> /// <param name="eventId">EventId for the event to be logged.</param> /// <param name="exception">Exception associated with this event.</param> /// <param name="additionalInfo">Additional information for this event.</param> internal static void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<string, string> additionalInfo ) { if (logContext == null) { PSTraceSource.NewArgumentNullException("logContext"); return; } if (exception == null) { PSTraceSource.NewArgumentNullException("exception"); return; } // Here execution context doesn't exist, we will have to log this event regardless. // Don't check NeedToLogEngineHealthEvent here. foreach (LogProvider provider in GetLogProvider(logContext)) { provider.LogEngineHealthEvent(logContext, eventId, exception, additionalInfo); } } #endregion #region Engine Lifecycle Event Logging Api /// <summary> /// LogEngineLifecycleEvent: Log an engine lifecycle event. /// /// This is the basic form of EngineLifecycleEvent logging api, in which all parameters are provided. /// /// Variant form of this function is defined below, which will make parameter additionalInfo /// optional. /// </summary> /// <param name="executionContext">Execution context for current engine instance.</param> /// <param name="engineState">New engine state.</param> /// <param name="invocationInfo">InvocationInfo for current command that is running.</param> internal static void LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState, InvocationInfo invocationInfo) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } EngineState previousState = GetEngineState(executionContext); if (engineState == previousState) return; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogEngineLifecycleEvent(provider, executionContext)) { provider.LogEngineLifecycleEvent(GetLogContext(executionContext, invocationInfo), engineState, previousState); } } SetEngineState(executionContext, engineState); } /// <summary> /// This is a variation of basic LogEngineLifeCycleEvent api which makes invocationInfo /// optional. /// </summary> /// <param name="executionContext"></param> /// <param name="engineState"></param> internal static void LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState) { LogEngineLifecycleEvent(executionContext, engineState, null); } #endregion #region Command Health Event Logging Api /// <summary> /// LogProviderHealthEvent: Log a command health event. /// </summary> /// <param name="executionContext">Execution context for the engine that is running.</param> /// <param name="exception">Exception associated with this event.</param> /// <param name="severity">Severity of this event.</param> internal static void LogCommandHealthEvent(ExecutionContext executionContext, Exception exception, Severity severity ) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } if (exception == null) { PSTraceSource.NewArgumentNullException("exception"); return; } InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogCommandHealthEvent(provider, executionContext)) { provider.LogCommandHealthEvent(GetLogContext(executionContext, invocationInfo, severity), exception); } } } #endregion #region Command Lifecycle Event Logging Api /// <summary> /// LogCommandLifecycleEvent: Log a command lifecycle event. /// /// This is the only form of CommandLifecycleEvent logging api. /// </summary> /// <param name="executionContext">Execution Context for the current running engine.</param> /// <param name="commandState">New command state.</param> /// <param name="invocationInfo">Invocation data for current command that is running.</param> internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, CommandState commandState, InvocationInfo invocationInfo) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } if (invocationInfo == null) { PSTraceSource.NewArgumentNullException("invocationInfo"); return; } if (s_ignoredCommands.Contains(invocationInfo.MyCommand.Name)) { return; } LogContext logContext = null; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogCommandLifecycleEvent(provider, executionContext)) { provider.LogCommandLifecycleEvent( () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo)), commandState); } } } /// <summary> /// LogCommandLifecycleEvent: Log a command lifecycle event. /// /// This is a form of CommandLifecycleEvent which takes a commandName instead /// of invocationInfo. It is likely that invocationInfo is not available if /// the command failed security check. /// </summary> /// <param name="executionContext">Execution Context for the current running engine.</param> /// <param name="commandState">New command state.</param> /// <param name="commandName">Current command that is running.</param> internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, CommandState commandState, string commandName) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } LogContext logContext = null; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogCommandLifecycleEvent(provider, executionContext)) { provider.LogCommandLifecycleEvent( () => { if (logContext == null) { logContext = GetLogContext(executionContext, null); logContext.CommandName = commandName; } return logContext; }, commandState); } } } #endregion #region Pipeline Execution Detail Event Logging Api /// <summary> /// LogPipelineExecutionDetailEvent: Log a pipeline execution detail event. /// </summary> /// <param name="executionContext">Execution Context for the current running engine.</param> /// <param name="detail">Detail to be logged for this pipeline execution detail.</param> /// <param name="invocationInfo">Invocation data for current command that is running.</param> internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionContext, List<string> detail, InvocationInfo invocationInfo) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogPipelineExecutionDetailEvent(provider, executionContext)) { provider.LogPipelineExecutionDetailEvent(GetLogContext(executionContext, invocationInfo), detail); } } } /// <summary> /// LogPipelineExecutionDetailEvent: Log a pipeline execution detail event. /// /// This is a form of PipelineExecutionDetailEvent which takes a scriptName and commandLine /// instead of invocationInfo. This will save the need to fill in the commandName for /// this event. /// </summary> /// <param name="executionContext">Execution Context for the current running engine.</param> /// <param name="detail">Detail to be logged for this pipeline execution detail.</param> /// <param name="scriptName">Script that is currently running.</param> /// <param name="commandLine">Command line that is currently running.</param> internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionContext, List<string> detail, string scriptName, string commandLine) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } LogContext logContext = GetLogContext(executionContext, null); logContext.CommandLine = commandLine; logContext.ScriptName = scriptName; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogPipelineExecutionDetailEvent(provider, executionContext)) { provider.LogPipelineExecutionDetailEvent(logContext, detail); } } } #endregion #region Provider Health Event Logging Api /// <summary> /// LogProviderHealthEvent: Log a Provider health event. /// </summary> /// <param name="executionContext">Execution context for the engine that is running.</param> /// <param name="providerName">Name of the provider.</param> /// <param name="exception">Exception associated with this event.</param> /// <param name="severity">Severity of this event.</param> internal static void LogProviderHealthEvent(ExecutionContext executionContext, string providerName, Exception exception, Severity severity ) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } if (exception == null) { PSTraceSource.NewArgumentNullException("exception"); return; } InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogProviderHealthEvent(provider, executionContext)) { provider.LogProviderHealthEvent(GetLogContext(executionContext, invocationInfo, severity), providerName, exception); } } } #endregion #region Provider Lifecycle Event Logging Api /// <summary> /// LogProviderLifecycleEvent: Log a provider lifecycle event. /// /// This is the only form of ProviderLifecycleEvent logging api. /// </summary> /// <param name="executionContext">Execution Context for current engine that is running.</param> /// <param name="providerName">Provider name.</param> /// <param name="providerState">New provider state.</param> internal static void LogProviderLifecycleEvent(ExecutionContext executionContext, string providerName, ProviderState providerState) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogProviderLifecycleEvent(provider, executionContext)) { provider.LogProviderLifecycleEvent(GetLogContext(executionContext, null), providerName, providerState); } } } #endregion #region Settings Event Logging Api /// <summary> /// LogSettingsEvent: Log a settings event /// /// This is the basic form of LoggingSettingsEvent API. Variation of this function defined /// below will make parameter invocationInfo optional. /// </summary> /// <param name="executionContext">Execution context for current running engine.</param> /// <param name="variableName">Variable name.</param> /// <param name="newValue">New value for the variable.</param> /// <param name="previousValue">Previous value for the variable.</param> /// <param name="invocationInfo">Invocation data for the command that is currently running.</param> internal static void LogSettingsEvent(ExecutionContext executionContext, string variableName, string newValue, string previousValue, InvocationInfo invocationInfo) { if (executionContext == null) { PSTraceSource.NewArgumentNullException("executionContext"); return; } foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogSettingsEvent(provider, executionContext)) { provider.LogSettingsEvent(GetLogContext(executionContext, invocationInfo), variableName, newValue, previousValue); } } } /// <summary> /// This is a variation of basic LogSettingsEvent to make "invocationInfo" optional. /// </summary> /// <param name="executionContext"></param> /// <param name="variableName"></param> /// <param name="newValue"></param> /// <param name="previousValue"></param> internal static void LogSettingsEvent(ExecutionContext executionContext, string variableName, string newValue, string previousValue) { LogSettingsEvent(executionContext, variableName, newValue, previousValue, null); } #endregion #region Helper Functions /// <summary> /// Get current engine state for the engine instance corresponding to executionContext /// passed in. /// /// Engine state is stored in ExecutionContext. /// </summary> /// <param name="executionContext"></param> /// <returns></returns> private static EngineState GetEngineState(ExecutionContext executionContext) { return executionContext.EngineState; } /// <summary> /// Set current engine state for the engine instance corresponding to executionContext /// passed in. /// /// Engine state is stored in ExecutionContext. /// </summary> /// <param name="executionContext"></param> /// <param name="engineState"></param> private static void SetEngineState(ExecutionContext executionContext, EngineState engineState) { executionContext.EngineState = engineState; } /// <summary> /// Generate LogContext structure based on executionContext and invocationInfo passed in. /// /// LogContext structure is used in log provider interface. /// </summary> /// <param name="executionContext"></param> /// <param name="invocationInfo"></param> /// <returns></returns> internal static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo) { return GetLogContext(executionContext, invocationInfo, Severity.Informational); } /// <summary> /// Generate LogContext structure based on executionContext and invocationInfo passed in. /// /// LogContext structure is used in log provider interface. /// </summary> /// <param name="executionContext"></param> /// <param name="invocationInfo"></param> /// <param name="severity"></param> /// <returns></returns> private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) { if (executionContext == null) return null; LogContext logContext = new LogContext(); string shellId = executionContext.ShellID; logContext.ExecutionContext = executionContext; logContext.ShellId = shellId; logContext.Severity = severity.ToString(); if (executionContext.EngineHostInterface != null) { logContext.HostName = executionContext.EngineHostInterface.Name; logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString(); logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString(); } logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs()); if (executionContext.CurrentRunspace != null) { logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString(); logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString(); Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline(); if (currentPipeline != null) { logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture); } } logContext.SequenceNumber = NextSequenceNumber; try { if (executionContext.LogContextCache.User == null) { logContext.User = Environment.UserDomainName + "\\" + Environment.UserName; executionContext.LogContextCache.User = logContext.User; } else { logContext.User = executionContext.LogContextCache.User; } } catch (InvalidOperationException) { logContext.User = Logging.UnknownUserName; } System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; if (psSenderInfo != null) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture); if (invocationInfo == null) return logContext; logContext.ScriptName = invocationInfo.ScriptName; logContext.CommandLine = invocationInfo.Line; if (invocationInfo.MyCommand != null) { logContext.CommandName = invocationInfo.MyCommand.Name; logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString(); switch (invocationInfo.MyCommand.CommandType) { case CommandTypes.Application: logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path; break; case CommandTypes.ExternalScript: logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path; break; } } return logContext; } #endregion #region Logging Policy /// <summary> /// NeedToLogEngineHealthEvent: check whether logging engine health event is necessary. /// Whether to log engine event is controled by session variable "LogEngineHealthEvent" /// The default value for this is true (?). /// Reading a session variable from execution context for /// every single logging call may be expensive. We may need to use a different /// approach for this: /// a. ExecutionContext will cache the value for variable "LogEngineHealthEvent" /// b. If this variable is changed, a notification function will change the cached /// value in engine correspondently. /// This applies to other logging preference variable also. /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogEngineHealthEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogEngineHealthEventVarPath, true)); } /// <summary> /// NeedToLogEngineLifecycleEvent: check whether logging engine lifecycle event is necessary. /// Whether to log engine lifecycle event is controled by session variable "LogEngineLifecycleEvent" /// The default value for this is false (?). /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogEngineLifecycleEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogEngineLifecycleEventVarPath, true)); } /// <summary> /// NeedToLogCommandHealthEvent: check whether logging command health event is necessary. /// Whether to log command health event is controled by session variable "LogCommandHealthEvent" /// The default value for this is false (?). /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogCommandHealthEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogCommandHealthEventVarPath, false)); } /// <summary> /// NeedToLogCommandLifecycleEvent: check whether logging command event is necessary. /// Whether to log command lifecycle event is controled by session variable "LogCommandLifecycleEvent" /// The default value for this is false (?). /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogCommandLifecycleEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogCommandLifecycleEventVarPath, false)); } /// <summary> /// NeedToLogPipelineExecutionDetailEvent: check whether logging pipeline execution detail event is necessary. /// /// Whether to log command lifecycle event is controled by PSSnapin set up. /// /// Should we use session variable "LogPipelineExecutionEvent" to control this also? /// /// Currently we return true always since pipeline processor already check for whether to log /// logic from PSSnapin already. This may need to be changed. /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogPipelineExecutionDetailEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return true; // return LanguagePrimitives.IsTrue(executionContext.GetVariable("LogPipelineExecutionDetailEvent", false)); } /// <summary> /// NeedToLogProviderHealthEvent: check whether logging Provider health event is necessary. /// Whether to log Provider health event is controled by session variable "LogProviderHealthEvent" /// The default value for this is true. /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogProviderHealthEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogProviderHealthEventVarPath, true)); } /// <summary> /// NeedToLogProviderLifecycleEvent: check whether logging Provider lifecycle event is necessary. /// Whether to log Provider lifecycle event is controled by session variable "LogProviderLifecycleEvent" /// The default value for this is true. /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogProviderLifecycleEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogProviderLifecycleEventVarPath, true)); } /// <summary> /// NeedToLogSettingsEvent: check whether logging settings event is necessary. /// Whether to log settings event is controled by session variable "LogSettingsEvent" /// The default value for this is false (?). /// </summary> /// <param name="logProvider"></param> /// <param name="executionContext"></param> /// <returns></returns> private static bool NeedToLogSettingsEvent(LogProvider logProvider, ExecutionContext executionContext) { if (!logProvider.UseLoggingVariables()) { return true; } return LanguagePrimitives.IsTrue(executionContext.GetVariableValue(SpecialVariables.LogSettingsEventVarPath, true)); } #endregion #region Sequence Id Generator private static int s_nextSequenceNumber = 0; /// <summary> /// Generate next sequence id to be attached to current event. /// </summary> /// <value></value> private static string NextSequenceNumber { get { return Convert.ToString(Interlocked.Increment(ref s_nextSequenceNumber), CultureInfo.CurrentCulture); } } #endregion #region EventId Constants // General health issues. internal const int EVENT_ID_GENERAL_HEALTH_ISSUE = 100; // Dependency. resource not available internal const int EVENT_ID_RESOURCE_NOT_AVAILABLE = 101; // Connectivity. network connection failure internal const int EVENT_ID_NETWORK_CONNECTIVITY_ISSUE = 102; // Settings. fail to set some configuration settings internal const int EVENT_ID_CONFIGURATION_FAILURE = 103; // Performance. system is experiencing some performance issues internal const int EVENT_ID_PERFORMANCE_ISSUE = 104; // Security: system is experiencing some security issues internal const int EVENT_ID_SECURITY_ISSUE = 105; // Workload. system is overloaded. internal const int EVENT_ID_SYSTEM_OVERLOADED = 106; // Beta 1 only -- Unexpected Exception internal const int EVENT_ID_UNEXPECTED_EXCEPTION = 195; #endregion EventId Constants } /// <summary> /// Log context cache. /// </summary> internal class LogContextCache { internal string User { get; set; } = null; } #region Command State and Provider State /// <summary> /// Severity of the event. /// </summary> internal enum Severity { /// <summary> /// Undefined severity. /// </summary> None, /// <summary> /// Critical event causing engine not to work. /// </summary> Critical, /// <summary> /// Error causing engine partially work. /// </summary> Error, /// <summary> /// Problem that may not cause an immediate problem. /// </summary> Warning, /// <summary> /// Informational. /// </summary> Informational }; /// <summary> /// Enum for command states. /// </summary> internal enum CommandState { /// <summary> /// </summary> Started = 0, /// <summary> /// </summary> Stopped = 1, /// <summary> /// </summary> Terminated = 2 }; /// <summary> /// Enum for provider states. /// </summary> internal enum ProviderState { /// <summary> /// </summary> Started = 0, /// <summary> /// </summary> Stopped = 1, }; #endregion }
/* **************************************************************************** * * 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. * * * ***************************************************************************/ #if !CLR2 #else using Microsoft.Scripting.Ast; #endif using System.Collections.Generic; using System.Diagnostics; using System.Management.Automation.Language; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Management.Automation.Interpreter { internal sealed class InterpretedFrame { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ThreadLocal<InterpretedFrame> CurrentFrame = new ThreadLocal<InterpretedFrame>(); internal readonly Interpreter Interpreter; internal InterpretedFrame _parent; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] private readonly int[] _continuations; private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly object[] Data; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly StrongBox<object>[] Closure; public int StackIndex; public int InstructionIndex; internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure) { Interpreter = interpreter; StackIndex = interpreter.LocalCount; Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth]; int c = interpreter.Instructions.MaxContinuationDepth; if (c > 0) { _continuations = new int[c]; } Closure = closure; _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } public DebugInfo GetDebugInfo(int instructionIndex) { return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex); } public string Name { get { return Interpreter._name; } } #region Data Stack Operations public void Push(object value) { Data[StackIndex++] = value; } public void Push(bool value) { Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; } public void Push(int value) { Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value); } public object Pop() { return Data[--StackIndex]; } internal void SetStackDepth(int depth) { StackIndex = Interpreter.LocalCount + depth; } public object Peek() { return Data[StackIndex - 1]; } public void Dup() { int i = StackIndex; Data[i] = Data[i - 1]; StackIndex = i + 1; } public ExecutionContext ExecutionContext { get { return (ExecutionContext)Data[1]; } } public FunctionContext FunctionContext { get { return (FunctionContext)Data[0]; } } #endregion #region Stack Trace public InterpretedFrame Parent { get { return _parent; } } public static bool IsInterpretedFrame(MethodBase method) { // ContractUtils.RequiresNotNull(method, "method"); return method.DeclaringType == typeof(Interpreter) && method.Name == "Run"; } /// <summary> /// A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames. /// This method filters out the duplicate CLR frames. /// </summary> public static IEnumerable<StackFrame> GroupStackFrames(IEnumerable<StackFrame> stackTrace) { bool inInterpretedFrame = false; foreach (StackFrame frame in stackTrace) { if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod())) { if (inInterpretedFrame) { continue; } inInterpretedFrame = true; } else { inInterpretedFrame = false; } yield return frame; } } public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo() { var frame = this; do { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; } while (frame != null); } internal void SaveTraceToException(Exception exception) { if (exception.Data[typeof(InterpretedFrameInfo)] == null) { exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray(); } } public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) { return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[]; } #if DEBUG internal string[] Trace { get { var trace = new List<string>(); var frame = this; do { trace.Add(frame.Name); frame = frame.Parent; } while (frame != null); return trace.ToArray(); } } #endif internal ThreadLocal<InterpretedFrame>.StorageInfo Enter() { var currentFrame = InterpretedFrame.CurrentFrame.GetStorageInfo(); _parent = currentFrame.Value; currentFrame.Value = this; return currentFrame; } internal void Leave(ThreadLocal<InterpretedFrame>.StorageInfo currentFrame) { currentFrame.Value = _parent; } #endregion #region Continuations internal bool IsJumpHappened() { return _pendingContinuation >= 0; } public void RemoveContinuation() { _continuationIndex--; } public void PushContinuation(int continuation) { _continuations[_continuationIndex++] = continuation; } public int YieldToCurrentContinuation() { var target = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(target.StackDepth); return target.Index - InstructionIndex; } /// <summary> /// Get called from the LeaveFinallyInstruction. /// </summary> public int YieldToPendingContinuation() { Debug.Assert(_pendingContinuation >= 0); RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation]; // the current continuation might have higher priority (continuationIndex is the depth of the current continuation): if (pendingTarget.ContinuationStackDepth < _continuationIndex) { RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(currentTarget.StackDepth); return currentTarget.Index - InstructionIndex; } SetStackDepth(pendingTarget.StackDepth); if (_pendingValue != Interpreter.NoValue) { Data[StackIndex - 1] = _pendingValue; } // Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; return pendingTarget.Index - InstructionIndex; } internal void PushPendingContinuation() { Push(_pendingContinuation); Push(_pendingValue); _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } internal void PopPendingContinuation() { _pendingValue = Pop(); _pendingContinuation = (int)Pop(); } private static MethodInfo s_goto; private static MethodInfo s_voidGoto; internal static MethodInfo GotoMethod { get { return s_goto ??= typeof(InterpretedFrame).GetMethod("Goto"); } } internal static MethodInfo VoidGotoMethod { get { return s_voidGoto ??= typeof(InterpretedFrame).GetMethod("VoidGoto"); } } public int VoidGoto(int labelIndex) { return Goto(labelIndex, Interpreter.NoValue, gotoExceptionHandler: false); } public int Goto(int labelIndex, object value, bool gotoExceptionHandler) { // TODO: we know this at compile time (except for compiled loop): RuntimeLabel target = Interpreter._labels[labelIndex]; Debug.Assert(!gotoExceptionHandler || _continuationIndex == target.ContinuationStackDepth, "When it's time to jump to the exception handler, all previous finally blocks should already be processed"); if (_continuationIndex == target.ContinuationStackDepth) { SetStackDepth(target.StackDepth); if (value != Interpreter.NoValue) { Data[StackIndex - 1] = value; } return target.Index - InstructionIndex; } // if we are in the middle of executing jump we forget the previous target and replace it by a new one: _pendingContinuation = labelIndex; _pendingValue = value; return YieldToCurrentContinuation(); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Cloud.TextToSpeech.V1Beta1 { /// <summary>Resource name for the <c>Model</c> resource.</summary> public sealed partial class ModelName : gax::IResourceName, sys::IEquatable<ModelName> { /// <summary>The possible contents of <see cref="ModelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> ProjectLocationModel = 1, } private static gax::PathTemplate s_projectLocationModel = new gax::PathTemplate("projects/{project}/locations/{location}/models/{model}"); /// <summary>Creates a <see cref="ModelName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ModelName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ModelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ModelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ModelName"/> with the pattern <c>projects/{project}/locations/{location}/models/{model}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ModelName"/> constructed from the provided ids.</returns> public static ModelName FromProjectLocationModel(string projectId, string locationId, string modelId) => new ModelName(ResourceNameType.ProjectLocationModel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </returns> public static string Format(string projectId, string locationId, string modelId) => FormatProjectLocationModel(projectId, locationId, modelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </returns> public static string FormatProjectLocationModel(string projectId, string locationId, string modelId) => s_projectLocationModel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))); /// <summary>Parses the given resource name string into a new <see cref="ModelName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ModelName"/> if successful.</returns> public static ModelName Parse(string modelName) => Parse(modelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ModelName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ModelName"/> if successful.</returns> public static ModelName Parse(string modelName, bool allowUnparsed) => TryParse(modelName, allowUnparsed, out ModelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ModelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ModelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string modelName, out ModelName result) => TryParse(modelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ModelName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ModelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string modelName, bool allowUnparsed, out ModelName result) { gax::GaxPreconditions.CheckNotNull(modelName, nameof(modelName)); gax::TemplatedResourceName resourceName; if (s_projectLocationModel.TryParseName(modelName, out resourceName)) { result = FromProjectLocationModel(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(modelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ModelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string modelId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ModelId = modelId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ModelName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/models/{model}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> public ModelName(string projectId, string locationId, string modelId) : this(ResourceNameType.ProjectLocationModel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Model</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ModelId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationModel: return s_projectLocationModel.Expand(ProjectId, LocationId, ModelId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ModelName); /// <inheritdoc/> public bool Equals(ModelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ModelName a, ModelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ModelName a, ModelName b) => !(a == b); } public partial class CustomVoiceParams { /// <summary><see cref="ModelName"/>-typed view over the <see cref="Model"/> resource name property.</summary> public ModelName ModelAsModelName { get => string.IsNullOrEmpty(Model) ? null : ModelName.Parse(Model, allowUnparsed: true); set => Model = value?.ToString() ?? ""; } } }
/* * 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.IO; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Serialize and deserialize scene objects. /// </summary> /// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems /// right now - hopefully this isn't forever. public class SceneObjectSerializer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(string serialization) { return FromOriginalXmlFormat(UUID.Zero, serialization); } /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; // libomv.types changes UUID to Guid xmlData = xmlData.Replace("<UUID>", "<Guid>"); xmlData = xmlData.Replace("</UUID>", "</Guid>"); // Handle Nested <UUID><UUID> property xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>"); xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>"); try { StringReader sr; XmlTextReader reader; XmlNodeList parts; XmlDocument doc; int linkNum; doc = new XmlDocument(); doc.LoadXml(xmlData); parts = doc.GetElementsByTagName("RootPart"); if (parts.Count == 0) throw new Exception("Invalid Xml format - no root part"); sr = new StringReader(parts[0].InnerXml); reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(fromUserInventoryItemID, reader)); reader.Close(); sr.Close(); parts = doc.GetElementsByTagName("Part"); for (int i = 0; i < parts.Count; i++) { sr = new StringReader(parts[i].InnerXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); linkNum = part.LinkNum; sceneObject.AddPart(part); part.LinkNum = linkNum; part.TrimPermissions(); part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat( "[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { ToOriginalXmlFormat(sceneObject, writer); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer) { //m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name); //int time = System.Environment.TickCount; writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); writer.WriteStartElement(String.Empty, "RootPart", String.Empty); ToOriginalXmlFormat(sceneObject.RootPart, writer); writer.WriteEndElement(); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); lock (sceneObject.Children) { foreach (SceneObjectPart part in sceneObject.Children.Values) { if (part.UUID != sceneObject.RootPart.UUID) { writer.WriteStartElement(String.Empty, "Part", String.Empty); ToOriginalXmlFormat(part, writer); writer.WriteEndElement(); } } } writer.WriteEndElement(); // OtherParts sceneObject.SaveScriptedState(writer); writer.WriteEndElement(); // SceneObjectGroup //m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time); } protected static void ToOriginalXmlFormat(SceneObjectPart part, XmlTextWriter writer) { part.ToXml(writer); } public static SceneObjectGroup FromXml2Format(string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; // libomv.types changes UUID to Guid xmlData = xmlData.Replace("<UUID>", "<Guid>"); xmlData = xmlData.Replace("</UUID>", "</Guid>"); // Handle Nested <UUID><UUID> property xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>"); xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>"); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData); XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart"); if (parts.Count == 0) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes. xml was " + xmlData); return null; } StringReader sr = new StringReader(parts[0].OuterXml); XmlTextReader reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader)); reader.Close(); sr.Close(); // Then deal with the rest for (int i = 1; i < parts.Count; i++) { sr = new StringReader(parts[i].OuterXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); sceneObject.AddPart(part); part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the 'xml2' format. /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToXml2Format(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { ToXml2Format(sceneObject, writer); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the 'xml2' format. /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static void ToXml2Format(SceneObjectGroup sceneObject, XmlTextWriter writer) { //m_log.DebugFormat("[SERIALIZER]: Starting serialization of SOG {0} to XML2", Name); //int time = System.Environment.TickCount; writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); sceneObject.RootPart.ToXml(writer); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); lock (sceneObject.Children) { foreach (SceneObjectPart part in sceneObject.Children.Values) { if (part.UUID != sceneObject.RootPart.UUID) { part.ToXml(writer); } } } writer.WriteEndElement(); // End of OtherParts sceneObject.SaveScriptedState(writer); writer.WriteEndElement(); // End of SceneObjectGroup //m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0} to XML2, {1}ms", Name, System.Environment.TickCount - time); } } }
//----------------------------------------------------------------------- // <copyright file="InputStreamSinkStage.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.IO; using Akka.IO; using Akka.Pattern; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; using static Akka.Streams.Implementation.IO.InputStreamSinkStage; namespace Akka.Streams.Implementation.IO { /// <summary> /// INTERNAL API /// </summary> internal class InputStreamSinkStage : GraphStageWithMaterializedValue<SinkShape<ByteString>, Stream> { #region internal classes /// <summary> /// TBD /// </summary> internal interface IAdapterToStageMessage { } /// <summary> /// TBD /// </summary> internal class ReadElementAcknowledgement : IAdapterToStageMessage { /// <summary> /// TBD /// </summary> public static readonly ReadElementAcknowledgement Instance = new ReadElementAcknowledgement(); private ReadElementAcknowledgement() { } } /// <summary> /// TBD /// </summary> internal class Close : IAdapterToStageMessage { /// <summary> /// TBD /// </summary> public static readonly Close Instance = new Close(); private Close() { } } /// <summary> /// TBD /// </summary> internal interface IStreamToAdapterMessage { } /// <summary> /// TBD /// </summary> internal struct Data : IStreamToAdapterMessage { /// <summary> /// TBD /// </summary> public readonly ByteString Bytes; /// <summary> /// TBD /// </summary> /// <param name="bytes">TBD</param> public Data(ByteString bytes) { Bytes = bytes; } } /// <summary> /// TBD /// </summary> internal class Finished : IStreamToAdapterMessage { /// <summary> /// TBD /// </summary> public static readonly Finished Instance = new Finished(); private Finished() { } } /// <summary> /// TBD /// </summary> internal class Initialized : IStreamToAdapterMessage { /// <summary> /// TBD /// </summary> public static readonly Initialized Instance = new Initialized(); private Initialized() { } } /// <summary> /// TBD /// </summary> internal struct Failed : IStreamToAdapterMessage { /// <summary> /// TBD /// </summary> public readonly Exception Cause; /// <summary> /// TBD /// </summary> /// <param name="cause">TBD</param> public Failed(Exception cause) { Cause = cause; } } /// <summary> /// TBD /// </summary> internal interface IStageWithCallback { /// <summary> /// TBD /// </summary> /// <param name="msg">TBD</param> void WakeUp(IAdapterToStageMessage msg); } private sealed class Logic : InGraphStageLogic, IStageWithCallback { private readonly InputStreamSinkStage _stage; private readonly Action<IAdapterToStageMessage> _callback; public Logic(InputStreamSinkStage stage) : base(stage.Shape) { _stage = stage; _callback = GetAsyncCallback((IAdapterToStageMessage messagae) => { if(messagae is ReadElementAcknowledgement) SendPullIfAllowed(); else if (messagae is Close) CompleteStage(); }); SetHandler(stage._in, this); } public override void OnPush() { //1 is buffer for Finished or Failed callback if (_stage._dataQueue.Count + 1 == _stage._dataQueue.BoundedCapacity) throw new BufferOverflowException("Queue is full"); _stage._dataQueue.Add(new Data(Grab(_stage._in))); if (_stage._dataQueue.BoundedCapacity - _stage._dataQueue.Count > 1) SendPullIfAllowed(); } public override void OnUpstreamFinish() { _stage._dataQueue.Add(Finished.Instance); CompleteStage(); } public override void OnUpstreamFailure(Exception ex) { _stage._dataQueue.Add(new Failed(ex)); FailStage(ex); } public override void PreStart() { _stage._dataQueue.Add(Initialized.Instance); Pull(_stage._in); } public void WakeUp(IAdapterToStageMessage msg) => _callback(msg); private void SendPullIfAllowed() { if (_stage._dataQueue.BoundedCapacity - _stage._dataQueue.Count > 1 && !HasBeenPulled(_stage._in)) Pull(_stage._in); } } #endregion private readonly Inlet<ByteString> _in = new Inlet<ByteString>("InputStreamSink.in"); private readonly TimeSpan _readTimeout; private BlockingCollection<IStreamToAdapterMessage> _dataQueue; /// <summary> /// TBD /// </summary> /// <param name="readTimeout">TBD</param> public InputStreamSinkStage(TimeSpan readTimeout) { _readTimeout = readTimeout; Shape = new SinkShape<ByteString>(_in); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes => DefaultAttributes.InputStreamSink; /// <summary> /// TBD /// </summary> public override SinkShape<ByteString> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Stream> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var maxBuffer = inheritedAttributes.GetAttribute(new Attributes.InputBuffer(16, 16)).Max; if (maxBuffer <= 0) throw new ArgumentException("Buffer size must be greather than 0"); _dataQueue = new BlockingCollection<IStreamToAdapterMessage>(maxBuffer + 2); var logic = new Logic(this); return new LogicAndMaterializedValue<Stream>(logic, new InputStreamAdapter(_dataQueue, logic, _readTimeout)); } } /// <summary> /// INTERNAL API /// InputStreamAdapter that interacts with InputStreamSinkStage /// </summary> internal class InputStreamAdapter : Stream { #region not supported /// <summary> /// TBD /// </summary> /// <exception cref="NotSupportedException">TBD</exception> public override void Flush() { throw new NotSupportedException("This stream can only read"); } /// <summary> /// TBD /// </summary> /// <param name="offset">TBD</param> /// <param name="origin">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> /// <returns>TBD</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("This stream can only read"); } /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> /// <returns>TBD</returns> public override void SetLength(long value) { throw new NotSupportedException("This stream can only read"); } /// <summary> /// TBD /// </summary> /// <param name="buffer">TBD</param> /// <param name="offset">TBD</param> /// <param name="count">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> /// <returns>TBD</returns> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("This stream can only read"); } /// <summary> /// TBD /// </summary> /// <exception cref="NotSupportedException">TBD</exception> public override long Length { get { throw new NotSupportedException("This stream can only read"); } } /// <summary> /// TBD /// </summary> /// <exception cref="NotSupportedException">TBD</exception> public override long Position { get { throw new NotSupportedException("This stream can only read"); } set { throw new NotSupportedException("This stream can only read"); } } #endregion private static readonly Exception SubscriberClosedException = new IOException("Reactive stream is terminated, no reads are possible"); private readonly BlockingCollection<IStreamToAdapterMessage> _sharedBuffer; private readonly IStageWithCallback _sendToStage; private readonly TimeSpan _readTimeout; private bool _isActive = true; private bool _isStageAlive = true; private bool _isInitialized; private ByteString _detachedChunk; /// <summary> /// TBD /// </summary> /// <param name="sharedBuffer">TBD</param> /// <param name="sendToStage">TBD</param> /// <param name="readTimeout">TBD</param> public InputStreamAdapter(BlockingCollection<IStreamToAdapterMessage> sharedBuffer, IStageWithCallback sendToStage, TimeSpan readTimeout) { _sharedBuffer = sharedBuffer; _sendToStage = sendToStage; _readTimeout = readTimeout; } /// <summary> /// TBD /// </summary> /// <param name="disposing">TBD</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); ExecuteIfNotClosed(() => { // at this point Subscriber may be already terminated if (_isStageAlive) _sendToStage.WakeUp(InputStreamSinkStage.Close.Instance); _isActive = false; return NotUsed.Instance; }); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public sealed override int ReadByte() { var a = new byte[1]; return Read(a, 0, 1) != 0 ? a[0] : -1; } /// <summary> /// TBD /// </summary> /// <param name="buffer">TBD</param> /// <param name="offset">TBD</param> /// <param name="count">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <exception cref="IllegalStateException">TBD</exception> /// <exception cref="IOException">TBD</exception> /// <returns>TBD</returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer.Length <= 0) throw new ArgumentException("array size must be > 0"); if (offset < 0) throw new ArgumentException("offset must be >= 0"); if (count <= 0) throw new ArgumentException("count must be > 0"); if (offset + count > buffer.Length) throw new ArgumentException("offset + count must be smaller or equal to the array length"); return ExecuteIfNotClosed(() => { if (!_isStageAlive) return 0; if (_detachedChunk != null) return ReadBytes(buffer, offset, count); IStreamToAdapterMessage msg; var success = _sharedBuffer.TryTake(out msg, _readTimeout); if (!success) throw new IOException("Timeout on waiting for new data"); if (msg is Data) { _detachedChunk = ((Data) msg).Bytes; return ReadBytes(buffer, offset, count); } if (msg is Finished) { _isStageAlive = false; return 0; } if (msg is Failed) { _isStageAlive = false; throw ((Failed) msg).Cause; } throw new IllegalStateException("message 'Initialized' must come first"); }); } private T ExecuteIfNotClosed<T>(Func<T> f) { if (_isActive) { WaitIfNotInitialized(); return f(); } throw SubscriberClosedException; } private void WaitIfNotInitialized() { if (!_isInitialized) { IStreamToAdapterMessage message; _sharedBuffer.TryTake(out message, _readTimeout); if (message is Initialized) _isInitialized = true; else throw new IllegalStateException("First message must be Initialized notification"); } } private int ReadBytes(byte[] buffer, int offset, int count) { if(_detachedChunk == null || _detachedChunk.IsEmpty) throw new InvalidOperationException("Chunk must be pulled from shared buffer"); var availableInChunk = _detachedChunk.Count; var readBytes = GetData(buffer, offset, count, 0); if (readBytes >= availableInChunk) _sendToStage.WakeUp(ReadElementAcknowledgement.Instance); return readBytes; } private int GetData(byte[] buffer, int offset, int count, int gotBytes) { var chunk = GrabDataChunk(); if (chunk == null) return gotBytes; var size = chunk.Count; if (size <= count) { Array.Copy(chunk.ToArray(), 0, buffer, offset, size); _detachedChunk = null; if (size == count) return gotBytes + size; return GetData(buffer, offset + size, count - size, gotBytes + size); } Array.Copy(chunk.ToArray(), 0, buffer, offset, count); _detachedChunk = chunk.Drop(count); return gotBytes + count; } private ByteString GrabDataChunk() { if (_detachedChunk != null) return _detachedChunk; var chunk = _sharedBuffer.Take(); if (chunk is Data) { _detachedChunk = ((Data) chunk).Bytes; return _detachedChunk; } if (chunk is Finished) _isStageAlive = false; return null; } /// <summary> /// TBD /// </summary> public override bool CanRead => true; /// <summary> /// TBD /// </summary> public override bool CanSeek => false; /// <summary> /// TBD /// </summary> public override bool CanWrite => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryShiftTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteShiftTest(bool useInterpreter) { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableByteShiftTest(bool useInterpreter) { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteShiftTest(bool useInterpreter) { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifySByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableSByteShiftTest(bool useInterpreter) { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableSByteShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortShiftTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyUShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortShiftTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableUShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortShiftTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortShiftTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableShortShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntShiftTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyUIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntShiftTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableUIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntShiftTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntShiftTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableIntShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongShiftTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyULongShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongShiftTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableULongShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongShiftTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { VerifyLongShift(array[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongShiftTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { VerifyNullableLongShift(array[i], useInterpreter); } } #endregion #region Test verifiers private static int[] s_shifts = new[] { int.MinValue, -1, 0, 1, 2, 31, 32, 63, 64, int.MaxValue }; private static void VerifyByteShift(byte a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyByteShift(a, b, true, useInterpreter); VerifyByteShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyByteShift(byte a, int b, bool left, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int))) ); Func<byte> f = e.Compile(useInterpreter); Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), f()); Expression<Func<byte?>> en = Expression.Lambda<Func<byte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(int?))) ); Func<byte?> fn = en.Compile(useInterpreter); Assert.Equal(unchecked((byte)(left ? a << b : a >> b)), fn()); } private static void VerifyNullableByteShift(byte? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableByteShift(a, b, true, useInterpreter); VerifyNullableByteShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableByteShift(byte? a, int b, bool left, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(int))) ); Func<byte?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f()); e = Expression.Lambda<Func<byte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(unchecked((byte?)(left ? a << b : a >> b)), f()); } private static void VerifySByteShift(sbyte a, bool useInterpreter) { foreach (var b in s_shifts) { VerifySByteShift(a, b, true, useInterpreter); VerifySByteShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifySByteShift(sbyte a, int b, bool left, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int))) ); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), f()); Expression<Func<sbyte?>> en = Expression.Lambda<Func<sbyte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(int?))) ); Func<sbyte?> fn = en.Compile(useInterpreter); Assert.Equal(unchecked((sbyte)(left ? a << b : a >> b)), fn()); } private static void VerifyNullableSByteShift(sbyte? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableSByteShift(a, b, true, useInterpreter); VerifyNullableSByteShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableSByteShift(sbyte? a, int b, bool left, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(int))) ); Func<sbyte?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f()); e = Expression.Lambda<Func<sbyte?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(unchecked((sbyte?)(left ? a << b : a >> b)), f()); } private static void VerifyUShortShift(ushort a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyUShortShift(a, b, true, useInterpreter); VerifyUShortShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyUShortShift(ushort a, int b, bool left, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int))) ); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), f()); Expression<Func<ushort?>> en = Expression.Lambda<Func<ushort?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(int?))) ); Func<ushort?> fn = en.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(left ? a << b : a >> b)), fn()); } private static void VerifyNullableUShortShift(ushort? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableUShortShift(a, b, true, useInterpreter); VerifyNullableUShortShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableUShortShift(ushort? a, int b, bool left, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(int))) ); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f()); e = Expression.Lambda<Func<ushort?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort?)(left ? a << b : a >> b)), f()); } private static void VerifyShortShift(short a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyShortShift(a, b, true, useInterpreter); VerifyShortShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyShortShift(short a, int b, bool left, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int))) ); Func<short> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short)(left ? a << b : a >> b)), f()); Expression<Func<short?>> en = Expression.Lambda<Func<short?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(int?))) ); Func<short?> fn = en.Compile(useInterpreter); Assert.Equal(unchecked((short)(left ? a << b : a >> b)), fn()); } private static void VerifyNullableShortShift(short? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableShortShift(a, b, true, useInterpreter); VerifyNullableShortShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableShortShift(short? a, int b, bool left, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(int))) ); Func<short?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f()); e = Expression.Lambda<Func<short?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(unchecked((short?)(left ? a << b : a >> b)), f()); } private static void VerifyUIntShift(uint a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyUIntShift(a, b, true, useInterpreter); VerifyUIntShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyUIntShift(uint a, int b, bool left, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int))) ); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); Expression<Func<uint?>> en = Expression.Lambda<Func<uint?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(int?))) ); Func<uint?> fn = en.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, fn()); } private static void VerifyNullableUIntShift(uint? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableUIntShift(a, b, true, useInterpreter); VerifyNullableUIntShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableUIntShift(uint? a, int b, bool left, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(int))) ); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); e = Expression.Lambda<Func<uint?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyIntShift(int a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyIntShift(a, b, true, useInterpreter); VerifyIntShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyIntShift(int a, int b, bool left, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))) ); Func<int> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); Expression<Func<int?>> en = Expression.Lambda<Func<int?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int?))) ); Func<int?> fn = en.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, fn()); } private static void VerifyNullableIntShift(int? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableIntShift(a, b, true, useInterpreter); VerifyNullableIntShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableIntShift(int? a, int b, bool left, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int))) ); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); e = Expression.Lambda<Func<int?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyULongShift(ulong a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyULongShift(a, b, true, useInterpreter); VerifyULongShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyULongShift(ulong a, int b, bool left, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int))) ); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); Expression<Func<ulong?>> en = Expression.Lambda<Func<ulong?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(int?))) ); Func<ulong?> fn = en.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, fn()); } private static void VerifyNullableULongShift(ulong? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableULongShift(a, b, true, useInterpreter); VerifyNullableULongShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableULongShift(ulong? a, int b, bool left, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(int))) ); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); e = Expression.Lambda<Func<ulong?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyLongShift(long a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyLongShift(a, b, true, useInterpreter); VerifyLongShift(a, b, false, useInterpreter); } VerifyNullShift(a, true, useInterpreter); VerifyNullShift(a, false, useInterpreter); } private static void VerifyLongShift(long a, int b, bool left, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int))) ); Func<long> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); Expression<Func<long?>> en = Expression.Lambda<Func<long?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(int?))) ); Func<long?> fn = en.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, fn()); } private static void VerifyNullableLongShift(long? a, bool useInterpreter) { foreach (var b in s_shifts) { VerifyNullableLongShift(a, b, true, useInterpreter); VerifyNullableLongShift(a, b, false, useInterpreter); } VerifyNullableNullShift(a, true, useInterpreter); VerifyNullableNullShift(a, false, useInterpreter); } private static void VerifyNullableLongShift(long? a, int b, bool left, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(int))) : Expression.RightShift( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(int))) ); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); e = Expression.Lambda<Func<long?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(int?))) ); f = e.Compile(useInterpreter); Assert.Equal(left ? a << b : a >> b, f()); } private static void VerifyNullShift<T>(T a, bool left, bool useInterpreter) where T : struct { Expression<Func<T?>> e = Expression.Lambda<Func<T?>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(T)), Expression.Default(typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(T)), Expression.Default(typeof(int?))) ); Func<T?> f = e.Compile(useInterpreter); Assert.Null(f()); } private static void VerifyNullableNullShift<T>(T a, bool left, bool useInterpreter) { Expression<Func<T>> e = Expression.Lambda<Func<T>>( left ? Expression.LeftShift( Expression.Constant(a, typeof(T)), Expression.Default(typeof(int?))) : Expression.RightShift( Expression.Constant(a, typeof(T)), Expression.Default(typeof(int?))) ); Func<T> f = e.Compile(useInterpreter); Assert.Null(f()); } #endregion [Fact] public static void CannotReduceLeft() { Expression exp = Expression.LeftShift(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void CannotReduceRight() { Expression exp = Expression.RightShift(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void LeftThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.LeftShift(null, Expression.Constant(""))); } [Fact] public static void LeftThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.LeftShift(Expression.Constant(""), null)); } [Fact] public static void RightThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.RightShift(null, Expression.Constant(""))); } [Fact] public static void RightThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.RightShift(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void LeftThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.LeftShift(value, Expression.Constant(1))); } [Fact] public static void LeftThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.LeftShift(Expression.Constant(1), value)); } [Fact] public static void RightThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.RightShift(value, Expression.Constant(1))); } [Fact] public static void RightThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.RightShift(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e1 = Expression.LeftShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a << b)", e1.ToString()); BinaryExpression e2 = Expression.RightShift(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a >> b)", e2.ToString()); } [Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string))] public static void IncorrectLHSTypes(Type type) { DefaultExpression lhs = Expression.Default(type); ConstantExpression rhs = Expression.Constant(0); Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs)); Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs)); } [Theory, InlineData(typeof(E)), InlineData(typeof(El)), InlineData(typeof(string)), InlineData(typeof(long)), InlineData(typeof(short)), InlineData(typeof(uint))] public static void IncorrectRHSTypes(Type type) { ConstantExpression lhs = Expression.Constant(0); DefaultExpression rhs = Expression.Default(type); Assert.Throws<InvalidOperationException>(() => Expression.LeftShift(lhs, rhs)); Assert.Throws<InvalidOperationException>(() => Expression.RightShift(lhs, rhs)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using NuGet; using Splat; using Squirrel; using Squirrel.Tests.TestHelpers; using Xunit; namespace Squirrel.Tests { public class FakeUrlDownloader : IFileDownloader { public Task<byte[]> DownloadUrl(string url) { return Task.FromResult(new byte[0]); } public async Task DownloadFile(string url, string targetFile, Action<int> progress) { } } public class ApplyReleasesTests : IEnableLogger { [Fact] public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); // NB: We execute the Squirrel-aware apps, so we need to give // them a minute to settle or else the using statement will // try to blow away a running process await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8); Assert.Contains("firstrun", text); } } } [Fact] public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8); Assert.Contains("updated|0.2.0", text); } } [Fact] public async Task RunningUpgradeAppTwiceDoesntCrash() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); // NB: The 2nd time we won't have any updates to apply. We should just do nothing! using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); } } [Fact] public async Task FullUninstallRemovesAllVersions() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullUninstall(); } Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); Assert.False(Directory.Exists(Path.Combine(tempDir, "theApp"))); } } [Fact] public void WhenNoNewReleasesAreAvailableTheListIsEmpty() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var package = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", package), Path.Combine(packages, package)); var aGivenPackage = Path.Combine(packages, package); var baseEntry = ReleaseEntry.GenerateFromFile(aGivenPackage); var updateInfo = UpdateInfo.Create(baseEntry, new[] { baseEntry }, "dontcare"); Assert.Empty(updateInfo.ReleasesToApply); } } [Fact] public void ThrowsWhenOnlyDeltaReleasesAreAvailable() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var baseFile = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", baseFile), Path.Combine(packages, baseFile)); var basePackage = Path.Combine(packages, baseFile); var baseEntry = ReleaseEntry.GenerateFromFile(basePackage); var deltaFile = "Squirrel.Core.1.1.0.0-delta.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", deltaFile), Path.Combine(packages, deltaFile)); var deltaPackage = Path.Combine(packages, deltaFile); var deltaEntry = ReleaseEntry.GenerateFromFile(deltaPackage); Assert.Throws<Exception>( () => UpdateInfo.Create(baseEntry, new[] { deltaEntry }, "dontcare")); } } [Fact] public async Task ApplyReleasesWithOneReleaseFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task ApplyReleaseWhichRemovesAFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.2.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.2.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.2.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var removedFile = Path.Combine("sub", "Ionic.Zip.dll"); var deployedPath = Path.Combine(rootDirectory, removedFile); File.Exists(deployedPath).ShouldBeFalse(); } } [Fact] public async Task ApplyReleaseWhichMovesAFileToADifferentDirectory() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.3.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.3.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.3.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var oldFile = Path.Combine(rootDirectory, "sub", "Ionic.Zip.dll"); File.Exists(oldFile).ShouldBeFalse(); var newFile = Path.Combine(rootDirectory, "other", "Ionic.Zip.dll"); File.Exists(newFile).ShouldBeTrue(); } } [Fact] public async Task ApplyReleasesWithDeltaReleases() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-delta.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { deltaEntry, latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(deltaEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task CreateFullPackagesFromDeltaSmokeTest() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg" }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(tempDir, "theApp", "packages", x))); var urlDownloader = new FakeUrlDownloader(); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.1.0.0-delta.nupkg")); var resultObs = (Task<ReleaseEntry>)fixture.GetType().GetMethod("createFullPackagesFromDeltas", BindingFlags.NonPublic | BindingFlags.Instance) .Invoke(fixture, new object[] { new[] {deltaEntry}, baseEntry }); var result = await resultObs; var zp = new ZipPackage(Path.Combine(tempDir, "theApp", "packages", result.Filename)); zp.Version.ToString().ShouldEqual("1.1.0.0"); } } [Fact] public async Task CreateShortcutsRoundTrip() { string remotePkgPath; string path; using (Utility.WithTempDirectory(out path)) { using (Utility.WithTempDirectory(out remotePkgPath)) using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) { IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath); await mgr.FullInstall(); } var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp")); fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot, false, null, null); // NB: COM is Weird. Thread.Sleep(1000); fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot); // NB: Squirrel-Aware first-run might still be running, slow // our roll before blowing away the temp path Thread.Sleep(1000); } } [Fact] public async Task GetShortcutsSmokeTest() { string remotePkgPath; string path; using (Utility.WithTempDirectory(out path)) { using (Utility.WithTempDirectory(out remotePkgPath)) using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) { IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath); await mgr.FullInstall(); } var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp")); var result = fixture.GetShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup, null); Assert.Equal(3, result.Keys.Count); // NB: Squirrel-Aware first-run might still be running, slow // our roll before blowing away the temp path Thread.Sleep(1000); } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Linq; using System.Web.UI.WebControls; using Adxstudio.Xrm.Account; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Web; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk; using Site.Pages; namespace Site.Areas.Government.Pages { public partial class CitizenProfile : PortalPage { private const string _userFetchXmlFormat = @" <fetch mapping=""logical""> <entity name=""contact""> <all-attributes /> <filter type=""and""> <condition attribute=""contactid"" operator=""eq"" value=""{0}""/> </filter> </entity> </fetch>"; public bool ShowMarketingOptionsPanel { get { var showMarketingSetting = ServiceContext.GetSiteSettingValueByName(Website, "Profile/ShowMarketingOptionsPanel") ?? "false"; return showMarketingSetting.ToLower() == "true"; } } public bool ForceRegistration { get { var siteSetting = ServiceContext.GetSiteSettingValueByName(Website, "Profile/ForceSignUp") ?? "false"; return siteSetting.ToLower() == "true"; } } protected void Page_Load(object sender, EventArgs e) { RedirectToLoginIfAnonymous(); if (ForceRegistration && !ServiceContext.ValidateProfileSuccessfullySaved(Contact)) { MissingFieldsMessage.Visible = true; } if (ShowMarketingOptionsPanel) { MarketingOptionsPanel.Visible = true; } ProfileDataSource.FetchXml = _userFetchXmlFormat.FormatWith(Contact.Id); ProfileAlertInstructions.Visible = Contact.GetAttributeValue<bool?>("adx_profilealert") ?? false; if (IsPostBack) { return; } var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == Contact.Id); if (contact == null) { throw new ApplicationException(string.Format("Couldn't retrieve contact record with contactid equal to {0}.", Contact.Id)); } if (ShowMarketingOptionsPanel) { marketEmail.Checked = !contact.GetAttributeValue<bool>("donotemail"); marketFax.Checked = !contact.GetAttributeValue<bool>("donotfax"); marketPhone.Checked = !contact.GetAttributeValue<bool>("donotphone"); marketMail.Checked = !contact.GetAttributeValue<bool>("donotpostalmail"); } PopulateMarketingLists(); } protected void SubmitButton_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } MissingFieldsMessage.Visible = false; var contact = XrmContext.MergeClone(Contact); ManageLists(XrmContext, contact); ProfileFormView.UpdateItem(); var returnUrl = Request["returnurl"]; if (!string.IsNullOrWhiteSpace(returnUrl)) { Context.RedirectAndEndResponse(returnUrl); } } protected void OnItemUpdating(object sender, CrmEntityFormViewUpdatingEventArgs e) { e.Values["adx_profilemodifiedon"] = DateTime.UtcNow; e.Values["adx_profilealert"] = ProfileAlertInstructions.Visible = false; if (ShowMarketingOptionsPanel) { e.Values["donotemail"] = !marketEmail.Checked; e.Values["donotbulkemail"] = !marketEmail.Checked; e.Values["donotfax"] = !marketFax.Checked; e.Values["donotphone"] = !marketPhone.Checked; e.Values["donotpostalmail"] = !marketMail.Checked; } } protected void OnItemUpdated(object sender, EventArgs args) { ConfirmationMessage.Visible = true; } public bool IsListChecked(object listoption) { var list = (Entity)listoption; if (Request.IsAuthenticated) { var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == Contact.Id); return contact != null && contact.GetRelatedEntities(XrmContext, new Relationship("listcontact_association")) .Any(l => l.GetAttributeValue<Guid>("listid") == list.Id); } return false; } public void ManageLists(OrganizationServiceContext context, Entity contact) { foreach (var item in MarketingListsListView.Items) { if (item == null) { continue; } var listViewItem = item; var hiddenListId = (HiddenField)listViewItem.FindControl("ListID"); if (hiddenListId == null) { continue; } var listId = new Guid(hiddenListId.Value); var ml = context.CreateQuery("list").First(m => m.GetAttributeValue<Guid>("listid") == listId); var listCheckBox = (CheckBox)item.FindControl("ListCheckbox"); if (listCheckBox == null) { continue; } var contactLists = contact.GetRelatedEntities(XrmContext, new Relationship("listcontact_association")).ToList(); var inList = contactLists.Any(list => list.GetAttributeValue<Guid>("listid") == ml.Id); if (listCheckBox.Checked && !inList) { context.AddMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid")); } else if (!listCheckBox.Checked && inList) { context.RemoveMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid")); } } } protected void PopulateMarketingLists() { if (Website == null) { MarketingLists.Visible = false; return; } var website = XrmContext.CreateQuery("adx_website").FirstOrDefault(w => w.GetAttributeValue<Guid>("adx_websiteid") == Website.Id); if (website == null) { MarketingLists.Visible = false; return; } // Note: Marketing Lists with 'Dynamic' Type (i.e. value of 1 or true) do not support manually adding members if (website.GetRelatedEntities(XrmContext, new Relationship("adx_website_list")).All(l => l.GetAttributeValue<bool>("type"))) { MarketingLists.Visible = false; return; } MarketingListsListView.DataSource = website.GetRelatedEntities(XrmContext, new Relationship("adx_website_list")).Where(l => l.GetAttributeValue<bool>("type") == false); MarketingListsListView.DataBind(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmProfileSEPSRes : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { if (Session["CPSEPC"].ToString() == "frmProfileSEProcs") { lblProfilesName.Text = "Business Profile for: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Service Delivered: " + Session["ServiceName"].ToString(); lblDeliverableName.Text = "Deliverable: " + Session["EventsName"].ToString(); lblProfileName.Text = "Clients/Stakeholders: " + Session["ProfileName"].ToString(); lblContents1.Text = "You may now identify the various types of impacts for the client/stakeholder" + " indicated above."; } else { lblTitle.Text = "EcoSys: Service Models"; lblContents1.Text = "You may now identify the various types of impacts for the client/stakeholder" + " indicated above."; } lblProcessName.Text = "Process: " + Session["ProcessName"].ToString(); loadData(); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand); } #endregion private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; if (Session["CPSEPC"].ToString() == "frmProfileSEProcs") { cmd.CommandText = "wms_RetrievePSEPCImpact"; cmd.Parameters.Add("@PSEPClientsId", SqlDbType.Int); cmd.Parameters["@PSEPClientsId"].Value = Session["PSEPClientsId"].ToString(); } else if (Session["CPSEPC"].ToString() == "frmProcs") { cmd.CommandText = "wms_RetrieveProcCImpact"; cmd.Parameters.Add("@ProcClientsId", SqlDbType.Int); cmd.Parameters["@ProcClientsId"].Value = Session["ProcClientsId"].ToString(); } cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "PCImpact"); Session["ds"] = ds; DataGrid1.DataSource = ds; DataGrid1.DataBind(); assignValues(); /* cmd.CommandText="eps_RetrieveProfileSEPSRes"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Session["ProfileSEPStepTypesId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"ProfileSEPSRes"); Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); assignValues();*/ } private void assignValues() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tbDesc = (TextBox)(i.Cells[2].FindControl("txtDesc")); if (i.Cells[4].Text == "&nbsp;") { tbDesc.Text=null; } else { tbDesc.Text = i.Cells[4].Text; } } } private void updateGrid() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tbDesc = (TextBox)(i.Cells[2].FindControl("txtDesc")); SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; if (Session["CPSEPC"].ToString() == "frmProfileSEProcs") { cmd.CommandText="wms_UpdatePSEPCImpactDesc"; } else { cmd.CommandText = "wms_UpdateProcCImpactDesc"; //lblContents1.Text = "Heah" + Int32.Parse(i.Cells[0].Text) + "PP" + tbDesc.Text; } cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@Desc", SqlDbType.VarChar); cmd.Parameters ["@Desc"].Value=tbDesc.Text; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters ["@Id"].Value=Int32.Parse(i.Cells[0].Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } protected void btnExit_Click(object sender, System.EventArgs e) { updateGrid(); Exit(); } private void Exit() { Response.Redirect(strURL + Session["CPSEPCI"].ToString() + ".aspx?"); } private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Remove") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; if (Session["CPSEPC"].ToString() == "frmProfileSEProcs") { cmd.CommandText="wms_DeletePSEPClientImpact"; } else if (Session["CPSEPC"].ToString() == "frmProcs") { cmd.CommandText = "wms_DeleteProcClientImpact"; } cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } } protected void btnAllTypes_Click(object sender, System.EventArgs e) { updateGrid(); Session["CallerRTA"]="frmProfileSEPSRes"; Response.Redirect (strURL + "frmResourceTypesAll.aspx?"); } protected void btnAdd_Click(object sender, EventArgs e) { updateGrid(); Session["CEventsAll"] = "frmPSEPClientImpact"; Response.Redirect(strURL + "frmEventsAll.aspx?"); } } }
using KERBALISM.KsmGui; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using TMPro; using UnityEngine; using UnityEngine.UI; using static KERBALISM.ScienceDB; using KSP.Localization; namespace KERBALISM { public class ExperimentSubjectList : KsmGuiVerticalLayout { public KsmGuiToggle KnownSubjectsToggle {get; private set;} public List<BodyContainer> BodyContainers = new List<BodyContainer>(); public ExperimentSubjectList(KsmGuiBase parent, ExperimentInfo expInfo) : base(parent) { KnownSubjectsToggle = new KsmGuiToggle(this, Local.SCIENCEARCHIVE_Showonlyknownsubjects, true, ToggleKnownSubjects, null, -1, 21);//"Show only known subjects" KsmGuiBase listHeader = new KsmGuiBase(this); listHeader.SetLayoutElement(true, false, -1, 16); listHeader.AddImageComponentWithColor(KsmGuiStyle.boxColor); KsmGuiText rndHeaderText = new KsmGuiText(listHeader, Local.SCIENCEARCHIVE_RnD, Local.SCIENCEARCHIVE_RnD_desc, TextAlignmentOptions.Left);//"RnD""Science points\nretrieved in RnD" rndHeaderText.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Science); rndHeaderText.TextComponent.fontStyle = FontStyles.Bold; rndHeaderText.TopTransform.SetAnchorsAndPosition(TextAnchor.MiddleLeft, TextAnchor.MiddleLeft, 10, 0); rndHeaderText.TopTransform.SetSizeDelta(50, 16); KsmGuiText flightHeaderText = new KsmGuiText(listHeader, Local.SCIENCEARCHIVE_Flight, Local.SCIENCEARCHIVE_Flight_desc, TextAlignmentOptions.Left);//"Flight""Science points\ncollected in all vessels" flightHeaderText.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Science); flightHeaderText.TextComponent.fontStyle = FontStyles.Bold; flightHeaderText.TopTransform.SetAnchorsAndPosition(TextAnchor.MiddleLeft, TextAnchor.MiddleLeft, 60, 0); flightHeaderText.TopTransform.SetSizeDelta(50, 16); KsmGuiText valueHeaderText = new KsmGuiText(listHeader, Local.SCIENCEARCHIVE_Value, Local.SCIENCEARCHIVE_Value_desc, TextAlignmentOptions.Left);//"Value""Remaining science value\naccounting for data retrieved in RnD\nand collected in flight" valueHeaderText.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Science); valueHeaderText.TextComponent.fontStyle = FontStyles.Bold; valueHeaderText.TopTransform.SetAnchorsAndPosition(TextAnchor.MiddleLeft, TextAnchor.MiddleLeft, 110, 0); valueHeaderText.TopTransform.SetSizeDelta(50, 16); KsmGuiText completedHeaderText = new KsmGuiText(listHeader, Local.SCIENCEARCHIVE_Completed, Local.SCIENCEARCHIVE_Completed_desc, TextAlignmentOptions.Left);//"Completed""How many times the subject\nhas been retrieved in RnD" completedHeaderText.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Yellow); completedHeaderText.TextComponent.fontStyle = FontStyles.Bold; completedHeaderText.TopTransform.SetAnchorsAndPosition(TextAnchor.MiddleLeft, TextAnchor.MiddleLeft, 160, 0); completedHeaderText.TopTransform.SetSizeDelta(100, 16); KsmGuiVerticalScrollView scrollView = new KsmGuiVerticalScrollView(this); scrollView.SetLayoutElement(true, true, 320, -1, -1, 250); scrollView.ContentGroup.padding = new RectOffset(0, 5, 5, 5); BodiesSituationsBiomesSubject subjects = GetSubjectsForExperiment(expInfo); if (subjects != null) { foreach (ObjectPair<int, SituationsBiomesSubject> bodySubjects in GetSubjectsForExperiment(expInfo)) { CelestialBody body = FlightGlobals.Bodies[bodySubjects.Key]; BodyContainer bodyEntry = new BodyContainer(scrollView, body, bodySubjects.Value); BodyContainers.Add(bodyEntry); } } SetUpdateCoroutine(new KsmGuiUpdateCoroutine(Update)); ForceExecuteCoroutine(); ToggleKnownSubjects(true); } public void ToggleKnownSubjects(bool onlyKnown) { foreach (BodyContainer body in BodyContainers) { if (onlyKnown && !body.isKnown) { body.Enabled = false; continue; } body.Enabled = true; body.ToggleBody(body.isKnown); foreach (SituationContainer situation in body.SubjectsContainer.Situations) { situation.Enabled = (onlyKnown && situation.isKnown) || !onlyKnown; foreach (SubjectLine subject in situation.SubjectLines) { subject.Enabled = (onlyKnown && subject.isKnown) || !onlyKnown; } } } RebuildLayout(); } private IEnumerator Update() { foreach (BodyContainer body in BodyContainers) { body.isKnown = false; foreach (SituationContainer situation in body.SubjectsContainer.Situations) { // check if unknown (non-DB) subjects have been created if (situation.DBLinesCount() != situation.SubjectLines.Count) situation.UpdateLines(); situation.isKnown = false; foreach (SubjectLine subject in situation.SubjectLines) { if (subject.SubjectData.ScienceCollectedTotal > 0.0) { subject.isKnown = true; situation.isKnown |= true; body.isKnown |= true; } if (KnownSubjectsToggle.IsOn && subject.Enabled != subject.isKnown) { if (!body.SubjectsContainer.IsInstantiated) body.SubjectsContainer.InstantiateUIObjects(); subject.Enabled = subject.isKnown; RebuildLayout(); } subject.UpdateText(); } if (KnownSubjectsToggle.IsOn && body.SubjectsContainer.IsInstantiated && situation.Enabled != situation.isKnown) { situation.Enabled = situation.isKnown; RebuildLayout(); } // only do 1 situation per update yield return null; } if (KnownSubjectsToggle.IsOn && body.Enabled != body.isKnown) { body.Enabled = body.isKnown; RebuildLayout(); } } yield break; } public class BodyContainer: KsmGuiVerticalLayout { public bool isKnown; public SubjectsContainer SubjectsContainer { get; private set; } KsmGuiIconButton bodyToggle; public BodyContainer(KsmGuiBase parent, CelestialBody body, SituationsBiomesSubject situationsAndSubjects) : base(parent) { KsmGuiHeader header = new KsmGuiHeader(this, body.name, KsmGuiStyle.boxColor); header.TextObject.TextComponent.fontStyle = FontStyles.Bold; header.TextObject.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Orange); header.TextObject.TextComponent.alignment = TextAlignmentOptions.Left; bodyToggle = new KsmGuiIconButton(header, Textures.KsmGuiTexHeaderArrowsUp, ToggleBody); bodyToggle.SetIconColor(Lib.Kolor.Orange); bodyToggle.MoveAsFirstChild(); SubjectsContainer = new SubjectsContainer(this, situationsAndSubjects); } public void ToggleBody() { ToggleBody(!SubjectsContainer.Enabled); } public void ToggleBody(bool enable) { if (enable) SubjectsContainer.InstantiateUIObjects(); SubjectsContainer.Enabled = enable; bodyToggle.SetIconTexture(enable ? Textures.KsmGuiTexHeaderArrowsUp : Textures.KsmGuiTexHeaderArrowsDown); RebuildLayout(); } } public class SubjectsContainer : KsmGuiVerticalLayout { public List<SituationContainer> Situations { get; private set; } = new List<SituationContainer>(); public bool IsInstantiated { get; private set; } = false; public SubjectsContainer(BodyContainer parent, SituationsBiomesSubject situationsSubjects) : base(parent) { foreach (ObjectPair<ScienceSituation, BiomesSubject> situation in situationsSubjects) { Situations.Add(new SituationContainer(situation)); } } public void InstantiateUIObjects() { if (IsInstantiated || Situations.Count == 0) return; IsInstantiated = true; foreach (SituationContainer situationContainer in Situations) { situationContainer.InstantiateUIObjects(this); } } public void DestroyUIObjects() { if (IsInstantiated) { IsInstantiated = false; foreach (SituationContainer situationContainer in Situations) { situationContainer.DestroyUIObjects(); } } } } public class SituationContainer { public bool isKnown; KsmGuiText situationText; public bool IsInstantiated => situationText != null; private ObjectPair<ScienceSituation, BiomesSubject> situationSubjects; public bool Enabled { get => situationText != null ? situationText.Enabled : false; set { if (situationText != null) situationText.Enabled = value; } } public List<SubjectLine> SubjectLines { get; private set; } = new List<SubjectLine>(); public SituationContainer(ObjectPair<ScienceSituation, BiomesSubject> situationSubjects) { this.situationSubjects = situationSubjects; foreach (ObjectPair<int, List<SubjectData>> subjects in situationSubjects.Value) { foreach (SubjectData subjectData in subjects.Value) { SubjectLines.Add(new SubjectLine(subjectData)); } } } public int DBLinesCount() { int count = 0; foreach (ObjectPair<int, List<SubjectData>> subjects in situationSubjects.Value) count += subjects.Value.Count; return count; } public void UpdateLines() { SubjectLines.Clear(); foreach (ObjectPair<int, List<SubjectData>> subjects in situationSubjects.Value) { foreach (SubjectData subjectData in subjects.Value) { SubjectLines.Add(new SubjectLine(subjectData)); } } } public void InstantiateUIObjects(SubjectsContainer parent) { isKnown = false; if (SubjectLines.Count == 0) return; situationText = new KsmGuiText(parent, SubjectLines[0].SubjectData.Situation.ScienceSituationTitle); situationText.TopTransform.SetAnchorsAndPosition(TextAnchor.MiddleLeft, TextAnchor.MiddleLeft, 5); situationText.TopTransform.SetSizeDelta(150, 14); situationText.TextComponent.color = Lib.KolorToColor(Lib.Kolor.Yellow); situationText.TextComponent.fontStyle = FontStyles.Bold; foreach (SubjectLine subjectLine in SubjectLines) { subjectLine.InstantiateText(parent); if (subjectLine.SubjectData.ScienceCollectedTotal > 0.0) { subjectLine.isKnown = true; isKnown |= true; } } } public void DestroyUIObjects() { if (situationText != null) { situationText.TopObject.DestroyGameObject(); situationText = null; } foreach (SubjectLine subjectLine in SubjectLines) subjectLine.DestroyText(); } } public class SubjectLine { public bool isKnown; public SubjectData SubjectData { get; private set; } KsmGuiText subjectText; public bool Enabled { get => subjectText != null ? subjectText.Enabled : false; set { if (subjectText != null) subjectText.Enabled = value; } } public SubjectLine(SubjectData subject) { SubjectData = subject; } public void InstantiateText(SubjectsContainer parent) { subjectText = new KsmGuiText(parent, GetText(), null, TextAlignmentOptions.TopLeft, false); subjectText.SetLayoutElement(true, false, -1, 14); } public void DestroyText() { if (subjectText != null) { subjectText.TopObject.DestroyGameObject(); subjectText = null; } } public void UpdateText() { if (subjectText != null) subjectText.Text = GetText(); } public string GetText() { return Lib.BuildString ( "<pos=10>", Lib.Color(Math.Round(SubjectData.ScienceRetrievedInKSC, 1).ToString("0.0;--;--"), Lib.Kolor.Science, true), "<pos=60>", Lib.Color(Math.Round(SubjectData.ScienceCollectedInFlight, 1).ToString("+0.0;--;--"), Lib.Kolor.Science, true), "<pos=110>", Lib.Color(Math.Round(SubjectData.ScienceRemainingTotal, 1).ToString("0.0;--;--"), Lib.Kolor.Science, true), "<pos=160>", Lib.Color(Math.Round(SubjectData.PercentRetrieved, 1).ToString("0.0x;--;--"), Lib.Kolor.Yellow, true), "<pos=200>", SubjectData.BiomeTitle ); } } } }
using AVFoundation; using CoreGraphics; using CoreMedia; using Foundation; using Stencil.Native.Core; using Stencil.Native.iOS.Core.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UIKit; namespace Stencil.Native.iOS.Core { public static class _IOSExtensions { #region Controllers public static UIViewController GetRootVisibleController(this UIApplication uiApplication) { if (uiApplication != null) { return uiApplication.KeyWindow.RootViewController.GetVisibleController(); } return null; } public static UIViewController GetVisibleController(this UIViewController rootViewController) { if (rootViewController == null) { return null; } if (rootViewController is UITabBarController) { return ((UITabBarController)rootViewController).SelectedViewController.GetVisibleController(); } else if (rootViewController is UINavigationController) { return ((UINavigationController)rootViewController).VisibleViewController.GetVisibleController(); } else if (rootViewController.PresentedViewController != null) { return rootViewController.PresentedViewController.GetVisibleController(); } else { return rootViewController; } } [Obsolete("Use the UIRefreshControlDelayed", true)] public static void BeginRefreshingWithBugFix(this UIRefreshControl refreshControl, UIScrollView tableViewToAdjust) { CoreUtility.ExecuteMethod("BeginRefreshingWithBugFix", delegate () { if (refreshControl != null) { refreshControl.BeginRefreshing(); if (tableViewToAdjust.ContentOffset.Y == 0) { UIView.Animate(.25, delegate () { tableViewToAdjust.ContentOffset = new CGPoint(0, -refreshControl.Frame.Size.Height); }); } } }); } public static UIRefreshControlDelayed InjectRefreshControl(this UITableViewController tableViewController, EventHandler handler) { return CoreUtility.ExecuteFunction("InjectRefreshControl", delegate () { UIRefreshControlDelayed refreshControl = new UIRefreshControlDelayed(); refreshControl.ScrollView = tableViewController.TableView; refreshControl.AddTarget(handler, UIControlEvent.ValueChanged); tableViewController.RefreshControl = refreshControl; return refreshControl; }); } public static UIRefreshControlDelayed InjectRefreshControl(this UIViewController viewController, UITableView tableView, EventHandler handler) { return CoreUtility.ExecuteFunction("InjectRefreshControl", delegate () { UITableViewController tableViewController = new UITableViewController(); viewController.AddChildViewController(tableViewController); tableViewController.TableView = tableView; UIRefreshControlDelayed refreshControl = new UIRefreshControlDelayed(); refreshControl.ScrollView = tableView; refreshControl.AddTarget(handler, UIControlEvent.ValueChanged); tableViewController.RefreshControl = refreshControl; refreshControl.TintColor = UIColor.Black; refreshControl.TintColorDidChange(); return refreshControl; }); } public static UIRefreshControl InjectRefreshControl(this UIViewController viewController, UICollectionView collectionView, EventHandler handler) { return CoreUtility.ExecuteFunction("InjectRefreshControl", delegate () { UIRefreshControlDelayed refreshControl = new UIRefreshControlDelayed(); refreshControl.ScrollView = collectionView; refreshControl.AddTarget(handler, UIControlEvent.ValueChanged); collectionView.AddSubview(refreshControl); collectionView.AlwaysBounceVertical = true; return refreshControl; }); } public static void RemoveRefreshControl(this UITableViewController tableViewController, UIRefreshControl control, EventHandler handler) { CoreUtility.ExecuteMethod("RemoveRefreshControl", delegate () { control.RemoveTarget(handler, UIControlEvent.ValueChanged); if (tableViewController.RefreshControl == control) { tableViewController.RefreshControl = null; } }); } #endregion #region Hacky Device Sizing Methods private static readonly Lazy<CGRect> _mainScreenBounds = new Lazy<CGRect>(() => UIScreen.MainScreen.Bounds); public static CGRect MainScreenBounds { get { return _mainScreenBounds.Value; } } public static bool IsIPhone6Plus() { return (MainScreenBounds.Height == 736); } public static bool IsIPhone6() { return (MainScreenBounds.Height == 667); } public static bool IsIPhone5() { return (MainScreenBounds.Height == 568); } public static bool IsIPhone4() { return (MainScreenBounds.Height == 480); } /// <summary> /// Converts from storyboard basic width of 320 to current device metric. /// Assumes the width is constrained by left/right /// Essentially only good for text sizing routines /// </summary> public static float SizingScaleFix(this int width) { if (IsIPhone6Plus()) { // (414 - 320) = 94 return width + 94f; } else if (IsIPhone6()) { // (375 - 320) = 55 return width + 55f; } return width; } /// <summary> /// Converts from storyboard basic width of 320 to current device metric. /// Assumes the width is constrained by left/right /// Essentially only good for text sizing routines /// </summary> public static float SizingScaleFix(this nfloat width, int countOfItems = 1) { if (IsIPhone6Plus()) { // (414 - 320) = 94 return (float)(width + (94f / countOfItems)); } else if (IsIPhone6()) { // (375 - 320) = 55 return (float)(width + (55f / countOfItems)); } return (float)width; } #endregion #region Navigation /// <summary> /// Pushes to current root nav controller, presents if one was not found. /// </summary> public static bool PushToRootNavigationController(this IViewPlatform platform, UIViewController controller, bool animated) { return CoreUtility.ExecuteFunction("PushToRootNavigationController", delegate () { UINavigationController navController = platform.GetRootNavigationController(); if (navController != null) { navController.PushViewController(controller, animated); return true; } else { BaseUIViewController rootBaseController = platform.GetRootViewController() as BaseUIViewController; if (rootBaseController != null) { rootBaseController.PresentViewControllerWithDisposeOnReturn(controller, animated, null); return true; } UIViewController rootController = platform.GetRootViewController(); if (rootController != null) { rootController.PresentViewController(controller, animated, null); return true; } } return false; }); } #endregion #region Layout public static void SetDefaultInsets(this UITableViewCell cell) { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { cell.PreservesSuperviewLayoutMargins = false; cell.LayoutMargins = UIEdgeInsets.Zero; } cell.SeparatorInset = new UIEdgeInsets(0, 15, 0, 15); } public static void RemoveInsets(this UITableViewCell cell) { if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { cell.PreservesSuperviewLayoutMargins = false; cell.LayoutMargins = UIEdgeInsets.Zero; } else { cell.SeparatorInset = UIEdgeInsets.Zero; } } public static void SetNavigationBarTranslucent(this UIViewController viewController, bool translucent) { if (viewController != null && viewController.NavigationController != null) { SetNavigationBarTranslucent(viewController.NavigationController, translucent); } } public static void SetNavigationBarTranslucent(this UINavigationController navigationController, bool translucent) { if (navigationController != null && navigationController.NavigationBar != null) { if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { navigationController.NavigationBar.Translucent = translucent; } } } public static void HideNavigationBarHairLine(this UIViewController viewController) { if (viewController != null && viewController.NavigationController != null) { HideNavigationBarHairLine(viewController.NavigationController); } } public static void HideNavigationBarHairLine(this UINavigationController navigationController) { if (navigationController != null && navigationController.NavigationBar != null) { UIView hairline = FindHairLine(navigationController.NavigationBar); if (hairline != null) { hairline.Hidden = true; } } } private static UIView FindHairLine(UIView view) { if (view is UIImageView && view.Bounds.Size.Height <= 1f) { return view; } foreach (var item in view.Subviews) { UIView found = FindHairLine(item); if (found != null) { return found; } } return null; } #endregion #region Fonts public static void DebugFontNames() { foreach (var item in UIFont.FamilyNames) { foreach (var font in UIFont.FontNamesForFamilyName(item)) { Console.WriteLine(font); } } /* NSArray *fontNames; NSInteger indFamily, indFont; for (indFamily=0; indFamily<[familyNames count]; ++indFamily) { NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]); fontNames = [[NSArray alloc] initWithArray: [UIFont fontNamesForFamilyName: [familyNames objectAtIndex:indFamily]]]; for (indFont=0; indFont<[fontNames count]; ++indFont) { NSLog(@" Font name: %@", [fontNames objectAtIndex:indFont]); } [fontNames release]; } [familyNames release]; */ } public static void AddUrlsForText(this NSMutableAttributedString attributedString, UIFont font, UIColor linkColor, string allText, string linkText, string destinationUrl) { CoreUtility.ExecuteMethod("AddUrlsForText", delegate () { int ix = allText.IndexOf(linkText, StringComparison.OrdinalIgnoreCase); while (ix >= 0) { NSRange foundRange = new NSRange(ix, linkText.Length); if (foundRange.Location >= 0) { attributedString.SetAttributes(new UIStringAttributes() { Font = font, ForegroundColor = linkColor }, foundRange); attributedString.AddAttribute(new NSString("handle"), new NSString(destinationUrl), foundRange); } int nextIX = allText.Substring(ix + linkText.Length).IndexOf(linkText, StringComparison.OrdinalIgnoreCase); if (nextIX >= 0) { ix = ix + linkText.Length + nextIX; } else { ix = -1; } } }); } #endregion #region Collections public static NSMutableDictionary ToNSDictionary(this Dictionary<string, string> dictionary) { NSMutableDictionary result = new NSMutableDictionary(); if (dictionary != null) { foreach (var item in dictionary) { result.Add(NSObject.FromObject(item.Key), NSObject.FromObject(item.Value)); } } return result; } #endregion #region Coloring private static Dictionary<string, UIColor> _colorCache = new Dictionary<string, UIColor>(StringComparer.OrdinalIgnoreCase); public static UIColor ConvertHexToColor(this string hexColor) { if (_colorCache.ContainsKey(hexColor)) { return _colorCache[hexColor]; } if (!string.IsNullOrEmpty(hexColor)) { string hexaColor = hexColor.Replace("#", ""); if (hexaColor.Length == 3) { hexaColor = hexaColor + hexaColor; } if (hexaColor.Length == 6) { hexaColor = "FF" + hexaColor; } hexaColor = hexaColor.ToUpper(); if (hexaColor.Length == 8) { if (_colorCache.ContainsKey(hexaColor)) { return _colorCache[hexaColor]; } UIColor result = UIColor.FromRGBA( Convert.ToByte(hexaColor.Substring(2, 2), 16), Convert.ToByte(hexaColor.Substring(4, 2), 16), Convert.ToByte(hexaColor.Substring(6, 2), 16), Convert.ToByte(hexaColor.Substring(0, 2), 16) ); _colorCache[hexaColor] = result; _colorCache[hexColor] = result; return result; } } return UIColor.White; } public static UIColor ConvertHexToColor(this string hexColor, double alphaOf1) { if (_colorCache.ContainsKey(hexColor + alphaOf1.ToString())) { return _colorCache[hexColor + alphaOf1.ToString()]; } if (!string.IsNullOrEmpty(hexColor)) { string hexaColor = hexColor.Replace("#", ""); if (hexaColor.Length == 3) { hexaColor = hexaColor + hexaColor; } if (hexaColor.Length == 6) { hexaColor = "FF" + hexaColor; } hexaColor = hexaColor.ToUpper(); if (hexaColor.Length == 8) { UIColor result = UIColor.FromRGBA( Convert.ToByte(hexaColor.Substring(2, 2), 16), Convert.ToByte(hexaColor.Substring(4, 2), 16), Convert.ToByte(hexaColor.Substring(6, 2), 16), Convert.ToByte((int)(255 * alphaOf1)) ); _colorCache[hexColor + alphaOf1.ToString()] = result; return result; } } return UIColor.White; } #endregion #region Exceptions public static Exception ConvertToException(this NSError error) { if (error != null) { string message = string.Empty; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Error Code: {0}\r\n", error.Code.ToString()); sb.AppendFormat("Description: {0}\r\n", error.LocalizedDescription); var userInfo = error.UserInfo; for (int i = 0; i < userInfo.Keys.Length; i++) { sb.AppendFormat("[{0}]: {1}\r\n", userInfo.Keys[i].ToString(), userInfo.Values[i].ToString()); } message = sb.ToString(); return new Exception(message); } return null; } #endregion #region Drawing public static float ToRadians(this double val) { return (float)((Math.PI / 180) * val); } public static nfloat ToRadians(this nfloat degree) { return (degree * (nfloat)Math.PI) / 180.0f; } public static CGPoint GetMidpointTo(this CGPoint self, CGPoint target) { return new CGPoint ( (self.X + target.X) / 2f, (self.Y + target.Y) / 2f ); } public static UIImage ScaledTo(this UIImage image, CGSize size) { UIGraphics.BeginImageContextWithOptions(size, true, 0f); //draw image.Draw(new CGRect(0.0f, 0.0f, size.Width, size.Height)); //capture resultant image UIImage result = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); //return image return result; } public static UIImage ScaledToFit(this UIImage image, CGSize size) { nfloat aspect = image.Size.Width / image.Size.Height; if (size.Width / aspect <= size.Height) { return image.ScaledTo(new CGSize(size.Width, size.Width / aspect)); } else { return image.ScaledTo(new CGSize(size.Height * aspect, size.Height)); } } public static UIImage ScaledToFill(this UIImage image, CGSize size) { nfloat aspect = image.Size.Width / image.Size.Height; if (size.Width / aspect > size.Height) { return image.ScaledTo(new CGSize(size.Width, size.Width / aspect)); } else { return image.ScaledTo(new CGSize(size.Height * aspect, size.Height)); } } public static UIImage ScaledToFillAndCenter(this UIImage image, CGSize imageSize) { UIImage sizedImage = image.ScaledToFill(imageSize); CGPoint offset = new CGPoint((imageSize.Width - sizedImage.Size.Width) / 2, (imageSize.Height - sizedImage.Size.Height) / 2); UIGraphics.BeginImageContextWithOptions(imageSize, true, 0f); sizedImage.Draw(offset); UIImage result = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return result; } public static UIImage CroppedToSize(this UIImage image, CGSize imageSize, CGPoint offset, bool mirror) { UIGraphics.BeginImageContextWithOptions(imageSize, true, 0f); image.Draw(offset); UIImage result = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (mirror) { UIImageOrientation imageOrientation = UIImageOrientation.Up; switch (result.Orientation) { case UIImageOrientation.Down: imageOrientation = UIImageOrientation.DownMirrored; break; case UIImageOrientation.DownMirrored: imageOrientation = UIImageOrientation.Down; break; case UIImageOrientation.Left: imageOrientation = UIImageOrientation.LeftMirrored; break; case UIImageOrientation.LeftMirrored: imageOrientation = UIImageOrientation.Left; break; case UIImageOrientation.Right: imageOrientation = UIImageOrientation.RightMirrored; break; case UIImageOrientation.RightMirrored: imageOrientation = UIImageOrientation.Right; break; case UIImageOrientation.Up: imageOrientation = UIImageOrientation.UpMirrored; break; case UIImageOrientation.UpMirrored: imageOrientation = UIImageOrientation.Up; break; default: break; } result = new UIImage(result.CGImage, result.CurrentScale, imageOrientation); } return result; } #endregion #region Videos public static UIImage GetVideoThumbnail(this AVAsset asset) { return CoreUtility.ExecuteFunction("GetVideoThumbnail", delegate () { AVAssetImageGenerator generator = new AVAssetImageGenerator(asset); generator.AppliesPreferredTrackTransform = true; CMTime ignoreTime = new CMTime(); NSError error = null; CGImage image = generator.CopyCGImageAtTime(new CMTime(1, 1), out ignoreTime, out error); if (error != null) { Container.Track.LogError(error.ConvertToException(), "GetVideoThumbnail"); } return new UIImage(image); }); } #endregion #region Date Methods private static DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime ToDateTime(this NSDate date) { var utcDateTime = reference.AddSeconds(date.SecondsSinceReferenceDate); var dateTime = utcDateTime.ToLocalTime(); return dateTime; } public static NSDate ToNSDate(this DateTime datetime) { var utcDateTime = datetime.ToUniversalTime(); var date = NSDate.FromTimeIntervalSinceReferenceDate((utcDateTime - reference).TotalSeconds); return date; } #endregion } }
using DevExpress.Mvvm.Native; using System; using System.Collections.Generic; using System.Linq; namespace DevExpress.Mvvm { public enum ViewInjectionMode { Default, Persistent } public class ViewInjectionManager : IViewInjectionManager { #region Static const string Exception1 = "Cannot register services with the same RegionName"; const string Exception2 = "Cannot inject item with this key, because it already exists in this region."; static IViewInjectionManager _defaultInstance = new ViewInjectionManager(ViewInjectionMode.Default); static IViewInjectionManager _default; public static IViewInjectionManager Default { get { return _default ?? _defaultInstance; } set { _default = value; } } static IViewInjectionManager _persistentManager = new ViewInjectionManager(ViewInjectionMode.Persistent); public static IViewInjectionManager PersistentManager { get { return _persistentManager; } } #endregion public virtual void RegisterService(IViewInjectionService service) { ServiceManager.Add(service); QueueManager.UpdateQueues(); } public virtual void UnregisterService(IViewInjectionService service) { ServiceManager.Remove(service); if(Mode == ViewInjectionMode.Persistent) { foreach(object vm in service.ViewModels.ToList()) service.Remove(vm); } } public IViewInjectionService GetService(string regionName) { return ServiceManager.FindService(x => x.RegionName == regionName); } public virtual void Inject(string regionName, object key, Func<object> viewModelFactory, string viewName, Type viewType) { bool isInjected = InjectCore(regionName, key, viewModelFactory, viewName, viewType); if(Mode == ViewInjectionMode.Persistent) QueueManager.PutToPersistentInjectionQueue(regionName, key, viewModelFactory, viewName, viewType); else if(!isInjected) QueueManager.PutToInjectionQueue(regionName, key, viewModelFactory, viewName, viewType); QueueManager.UpdateQueues(); } protected bool InjectCore(string regionName, object key, Func<object> factory, string viewName, Type viewType) { var service = GetService(regionName); if(service != null) { if(Mode == ViewInjectionMode.Persistent && service.GetViewModel(key) != null) return true; service.Inject(key, factory(), viewName, viewType); return true; } return false; } public virtual void Remove(string regionName, object key) { QueueManager.RemoveFromQueues(regionName, key); var service = GetService(regionName); if(service != null) service.Remove(service.GetViewModel(key)); } public virtual void Navigate(string regionName, object key) { if(!NavigateCore(regionName, key)) QueueManager.PutToNavigationQueue(regionName, key); } protected bool NavigateCore(string regionName, object key) { var service = GetService(regionName); if(service == null) return false; object vm = service.GetViewModel(key); if(vm != null) { service.SelectedViewModel = vm; return true; } return false; } public void RegisterNavigatedEventHandler(object viewModel, Action eventHandler) { Messenger.Register<NavigatedMessage>(viewModel, viewModel.GetHashCode(), false, eventHandler); } public void RegisterNavigatedAwayEventHandler(object viewModel, Action eventHandler) { Messenger.Register<NavigatedAwayMessage>(viewModel, viewModel.GetHashCode(), false, eventHandler); } public void RegisterViewModelClosingEventHandler(object viewModel, Action<ViewModelClosingEventArgs> eventHandler) { Messenger.Register<ViewModelClosingEventArgs>(viewModel, viewModel.GetHashCode(), false, eventHandler); } public void UnregisterNavigatedEventHandler(object viewModel, Action eventHandler = null) { Messenger.Unregister<NavigatedMessage>(viewModel, viewModel.GetHashCode(), eventHandler); } public void UnregisterNavigatedAwayEventHandler(object viewModel, Action eventHandler = null) { Messenger.Unregister<NavigatedAwayMessage>(viewModel, viewModel.GetHashCode(), eventHandler); } public void UnregisterViewModelClosingEventHandler(object viewModel, Action<ViewModelClosingEventArgs> eventHandler = null) { Messenger.Unregister<ViewModelClosingEventArgs>(viewModel, viewModel.GetHashCode(), eventHandler); } public void RaiseNavigatedEvent(object viewModel) { Messenger.Send<NavigatedMessage>(new NavigatedMessage(), viewModel.GetHashCode()); } public void RaiseNavigatedAwayEvent(object viewModel) { Messenger.Send<NavigatedAwayMessage>(new NavigatedAwayMessage(), viewModel.GetHashCode()); } public void RaiseViewModelClosingEvent(ViewModelClosingEventArgs e) { Messenger.Send<ViewModelClosingEventArgs>(e, e.ViewModel.GetHashCode()); } protected ViewInjectionMode Mode { get; private set; } public ViewInjectionManager(ViewInjectionMode mode) { Mode = mode; ServiceManager = new ServiceManagerHelper(); QueueManager = new QueueManagerHelper(this); Messenger = new MessengerEx(); } ServiceManagerHelper ServiceManager; QueueManagerHelper QueueManager; MessengerEx Messenger; #region Inner Classes class ServiceManagerHelper { readonly List<WeakReference> ServiceReferences = new List<WeakReference>(); void UpdateServiceReferences() { List<WeakReference> referencesToDelete = new List<WeakReference>(); foreach(var reference in ServiceReferences) if(!reference.IsAlive) referencesToDelete.Add(reference); foreach(var reference in referencesToDelete) ServiceReferences.Remove(reference); } WeakReference GetServiceReference(IViewInjectionService service) { UpdateServiceReferences(); return ServiceReferences.FirstOrDefault(x => x.Target == service); } public void Add(IViewInjectionService service) { if(service == null || string.IsNullOrEmpty(service.RegionName)) return; if(GetServiceReference(service) != null) return; if(FindService(x => x.RegionName == service.RegionName) != null) throw new InvalidOperationException(Exception1); ServiceReferences.Add(new WeakReference(service)); } public void Remove(IViewInjectionService service) { if(service == null) return; var serviceReference = GetServiceReference(service); if(serviceReference == null) return; ServiceReferences.Remove(serviceReference); } public IViewInjectionService FindService(Func<IViewInjectionService, bool> predicate) { UpdateServiceReferences(); var reference = ServiceReferences.FirstOrDefault(x => predicate((IViewInjectionService)x.Target)); return reference != null ? (IViewInjectionService)reference.Target : null; } public IEnumerable<IViewInjectionService> FindAllServices(Func<IViewInjectionService, bool> predicate) { List<IViewInjectionService> res = new List<IViewInjectionService>(); UpdateServiceReferences(); var references = ServiceReferences.FindAll(x => predicate((IViewInjectionService)x.Target)); foreach(var reference in references) res.Add((IViewInjectionService)reference.Target); return res; } } class QueueManagerHelper { ViewInjectionManager Owner; public QueueManagerHelper(ViewInjectionManager owner) { Owner = owner; } public void PutToInjectionQueue(string regionName, object key, Func<object> factory, string viewName, Type viewType) { InjectionQueue.Add(new InjectionItem(regionName, key, factory, viewName, viewType)); } public void PutToPersistentInjectionQueue(string regionName, object key, Func<object> factory, string viewName, Type viewType) { foreach(InjectionItem item in PersistentInjectionQueue) { if(item.RegionName == regionName && object.Equals(item.Key, key)) throw new InvalidOperationException("Exception2"); } PersistentInjectionQueue.Add(new InjectionItem(regionName, key, factory, viewName, viewType)); } public void PutToNavigationQueue(string regionName, object key) { NavigationQueue.Add(new NavigationItem(regionName, key)); } public void RemoveFromQueues(string regionName, object key) { var injectionItem = InjectionQueue.FirstOrDefault(x => x.RegionName == regionName && object.Equals(x.Key, key)); injectionItem.Do(x => InjectionQueue.Remove(x)); var persistentInjectionItem = PersistentInjectionQueue.FirstOrDefault(x => x.RegionName == regionName && object.Equals(x.Key, key)); persistentInjectionItem.Do(x => PersistentInjectionQueue.Remove(x)); var navigationItem = NavigationQueue.FirstOrDefault(x => x.RegionName == regionName && object.Equals(x.Key, key)); navigationItem.Do(x => NavigationQueue.Remove(x)); } public void UpdateQueues() { ProcessQueue(InjectionQueue, x => Owner.InjectCore(x.RegionName, x.Key, x.Factory, x.ViewName, x.ViewType)); ProcessQueue(PersistentInjectionQueue, x => { Owner.InjectCore(x.RegionName, x.Key, x.Factory, x.ViewName, x.ViewType); return false; }); ProcessQueue(NavigationQueue, x => Owner.NavigateCore(x.RegionName, x.Key)); } void ProcessQueue<T>(IList<T> queue, Func<T, bool> processAction) { List<T> processedItems = new List<T>(); foreach(T item in queue.ToList()) if(processAction(item)) processedItems.Add(item); foreach(T processedItem in processedItems) queue.Remove(processedItem); } readonly List<InjectionItem> InjectionQueue = new List<InjectionItem>(); readonly List<InjectionItem> PersistentInjectionQueue = new List<InjectionItem>(); readonly List<NavigationItem> NavigationQueue = new List<NavigationItem>(); class InjectionItem { public string RegionName { get; private set; } public object Key { get; private set; } public Func<object> Factory { get; private set; } public string ViewName { get; private set; } public Type ViewType { get; private set; } public InjectionItem(string regionName, object key, Func<object> factory, string viewName, Type viewType) { RegionName = regionName; Key = key; Factory = factory; ViewName = viewName; ViewType = viewType; } } class NavigationItem { public readonly string RegionName; public readonly object Key; public NavigationItem(string regionName, object key) { RegionName = regionName; Key = key; } } } class MessengerEx : Messenger { public MessengerEx() : base(false, ActionReferenceType.WeakReference) { } public void Register<TMessage>(object recipient, object token, bool receiveInheritedMessages, Action action) { IActionInvoker actionInvoker = CreateActionInvoker<TMessage>(recipient, action); RegisterCore(token, receiveInheritedMessages, typeof(TMessage), actionInvoker); RequestCleanup(); } public void Unregister<TMessage>(object recipient, object token, Action action) { UnregisterCore(recipient, token, action, typeof(TMessage)); } IActionInvoker CreateActionInvoker<TMessage>(object recipient, Action action) { #if !NETFX_CORE if(action.Method.IsStatic) #else if(action.GetMethodInfo().IsStatic) #endif return new StrongReferenceActionInvoker(recipient, action); #if SILVERLIGHT if(ShouldStoreActionItself(action)) return new SLWeakReferenceActionInvoker(recipient, action); #endif return new WeakReferenceActionInvoker(recipient, action); } #if SILVERLIGHT static bool ShouldStoreActionItself(Delegate action) { if(!action.Method.IsPublic) return true; if(action.Target != null && !action.Target.GetType().IsPublic && !action.Target.GetType().IsNestedPublic) return true; var name = action.Method.Name; if(name.Contains("<") && name.Contains(">")) return true; return false; } #endif } class NavigatedMessage { } class NavigatedAwayMessage { } #endregion } }
// nVLC // // Author: Roman Ginzburg // // nVLC is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // nVLC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // ======================================================================== using System; using System.Runtime.InteropServices; namespace LibVlcWrapper { [StructLayout(LayoutKind.Sequential)] public struct libvlc_log_message_t { public UInt32 sizeof_msg; public Int32 i_severity; public IntPtr psz_type; public IntPtr psz_name; public IntPtr psz_header; public IntPtr psz_message; } [StructLayout(LayoutKind.Sequential)] public struct libvlc_media_stats_t { /* Input */ public int i_read_bytes; public float f_input_bitrate; /* Demux */ public int i_demux_read_bytes; public float f_demux_bitrate; public int i_demux_corrupted; public int i_demux_discontinuity; /* Decoders */ public int i_decoded_video; public int i_decoded_audio; /* Video Output */ public int i_displayed_pictures; public int i_lost_pictures; /* Audio output */ public int i_played_abuffers; public int i_lost_abuffers; /* Stream output */ public int i_sent_packets; public int i_sent_bytes; public float f_send_bitrate; } [StructLayout(LayoutKind.Explicit)] public struct libvlc_media_track_info_t { [FieldOffset(0)] public UInt32 i_codec; [FieldOffset(4)] public int i_id; [FieldOffset(8)] public libvlc_track_type_t i_type; [FieldOffset(12)] public int i_profile; [FieldOffset(16)] public int i_level; [FieldOffset(20)] public audio audio; [FieldOffset(20)] public video video; } [StructLayout(LayoutKind.Sequential)] public struct audio { public int i_channels; public int i_rate; } [StructLayout(LayoutKind.Sequential)] public struct video { public int i_height; public int i_width; } [StructLayout(LayoutKind.Explicit)] public struct libvlc_event_t { [FieldOffset(0)] public libvlc_event_e type; [FieldOffset(4)] public IntPtr p_obj; [FieldOffset(8)] public media_meta_changed media_meta_changed; [FieldOffset(8)] public media_subitem_added media_subitem_added; [FieldOffset(8)] public media_duration_changed media_duration_changed; [FieldOffset(8)] public media_parsed_changed media_parsed_changed; [FieldOffset(8)] public media_freed media_freed; [FieldOffset(8)] public media_state_changed media_state_changed; [FieldOffset(8)] public media_player_position_changed media_player_position_changed; [FieldOffset(8)] public media_player_time_changed media_player_time_changed; [FieldOffset(8)] public media_player_title_changed media_player_title_changed; [FieldOffset(8)] public media_player_seekable_changed media_player_seekable_changed; [FieldOffset(8)] public media_player_pausable_changed media_player_pausable_changed; [FieldOffset(8)] public media_list_item_added media_list_item_added; [FieldOffset(8)] public media_list_will_add_item media_list_will_add_item; [FieldOffset(8)] public media_list_item_deleted media_list_item_deleted; [FieldOffset(8)] public media_list_will_delete_item media_list_will_delete_item; [FieldOffset(8)] public media_list_player_next_item_set media_list_player_next_item_set; [FieldOffset(8)] public media_player_snapshot_taken media_player_snapshot_taken; [FieldOffset(8)] public media_player_length_changed media_player_length_changed; [FieldOffset(8)] public vlm_media_event vlm_media_event; [FieldOffset(8)] public media_player_media_changed media_player_media_changed; } /* media descriptor */ [StructLayout(LayoutKind.Sequential)] public struct media_meta_changed { public libvlc_meta_t meta_type; } [StructLayout(LayoutKind.Sequential)] public struct media_subitem_added { public IntPtr new_child; } [StructLayout(LayoutKind.Sequential)] public struct media_duration_changed { public long new_duration; } [StructLayout(LayoutKind.Sequential)] public struct media_parsed_changed { public int new_status; } [StructLayout(LayoutKind.Sequential)] public struct media_freed { public IntPtr md; } [StructLayout(LayoutKind.Sequential)] public struct media_state_changed { public libvlc_state_t new_state; } /* media instance */ [StructLayout(LayoutKind.Sequential)] public struct media_player_position_changed { public float new_position; } [StructLayout(LayoutKind.Sequential)] public struct media_player_time_changed { public long new_time; } [StructLayout(LayoutKind.Sequential)] public struct media_player_title_changed { public int new_title; } [StructLayout(LayoutKind.Sequential)] public struct media_player_seekable_changed { public int new_seekable; } [StructLayout(LayoutKind.Sequential)] public struct media_player_pausable_changed { public int new_pausable; } /* media list */ [StructLayout(LayoutKind.Sequential)] public struct media_list_item_added { public IntPtr item; public int index; } [StructLayout(LayoutKind.Sequential)] public struct media_list_will_add_item { public IntPtr item; public int index; } [StructLayout(LayoutKind.Sequential)] public struct media_list_item_deleted { public IntPtr item; public int index; } [StructLayout(LayoutKind.Sequential)] public struct media_list_will_delete_item { public IntPtr item; public int index; } /* media list player */ [StructLayout(LayoutKind.Sequential)] public struct media_list_player_next_item_set { public IntPtr item; } /* snapshot taken */ [StructLayout(LayoutKind.Sequential)] public struct media_player_snapshot_taken { public IntPtr psz_filename; } /* Length changed */ [StructLayout(LayoutKind.Sequential)] public struct media_player_length_changed { public long new_length; } /* VLM media */ [StructLayout(LayoutKind.Sequential)] public struct vlm_media_event { public IntPtr psz_media_name; public IntPtr psz_instance_name; } /* Extra MediaPlayer */ [StructLayout(LayoutKind.Sequential)] public struct media_player_media_changed { public IntPtr new_media; } [StructLayout(LayoutKind.Sequential)] public struct libvlc_module_description_t { public IntPtr psz_name; public IntPtr psz_shortname; public IntPtr psz_longname; public IntPtr psz_help; public IntPtr p_next; } }
/* * 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.Data; using System.IO; using System.Reflection; using OpenSim.Framework; using log4net; using OpenMetaverse; using Npgsql; using NpgsqlTypes; namespace OpenSim.Data.PGSQL { /// <summary> /// A management class for the MS SQL Storage Engine /// </summary> public class PGSQLManager { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Connection string for ADO.net /// </summary> private readonly string connectionString; /// <summary> /// Initialize the manager and set the connectionstring /// </summary> /// <param name="connection"></param> public PGSQLManager(string connection) { connectionString = connection; InitializeMonoSecurity(); } public void InitializeMonoSecurity() { if (!Util.IsPlatformMono) { if (AppDomain.CurrentDomain.GetData("MonoSecurityPostgresAdded") == null) { AppDomain.CurrentDomain.SetData("MonoSecurityPostgresAdded", "true"); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(ResolveEventHandlerMonoSec); } } } private System.Reflection.Assembly ResolveEventHandlerMonoSec(object sender, ResolveEventArgs args) { Assembly MyAssembly = null; if (args.Name.Substring(0, args.Name.IndexOf(",")) == "Mono.Security") { MyAssembly = Assembly.LoadFrom("lib/NET/Mono.Security.dll"); } //Return the loaded assembly. return MyAssembly; } /// <summary> /// Type conversion to a SQLDbType functions /// </summary> /// <param name="type"></param> /// <returns></returns> internal NpgsqlDbType DbtypeFromType(Type type) { if (type == typeof(string)) { return NpgsqlDbType.Varchar; } if (type == typeof(double)) { return NpgsqlDbType.Double; } if (type == typeof(Single)) { return NpgsqlDbType.Double; } if (type == typeof(int)) { return NpgsqlDbType.Integer; } if (type == typeof(bool)) { return NpgsqlDbType.Boolean; } if (type == typeof(UUID)) { return NpgsqlDbType.Uuid; } if (type == typeof(byte)) { return NpgsqlDbType.Smallint; } if (type == typeof(sbyte)) { return NpgsqlDbType.Integer; } if (type == typeof(Byte[])) { return NpgsqlDbType.Bytea; } if (type == typeof(uint) || type == typeof(ushort)) { return NpgsqlDbType.Integer; } if (type == typeof(ulong)) { return NpgsqlDbType.Bigint; } if (type == typeof(DateTime)) { return NpgsqlDbType.Timestamp; } return NpgsqlDbType.Varchar; } internal NpgsqlDbType DbtypeFromString(Type type, string PGFieldType) { if (PGFieldType == "") { return DbtypeFromType(type); } if (PGFieldType == "character varying") { return NpgsqlDbType.Varchar; } if (PGFieldType == "double precision") { return NpgsqlDbType.Double; } if (PGFieldType == "integer") { return NpgsqlDbType.Integer; } if (PGFieldType == "smallint") { return NpgsqlDbType.Smallint; } if (PGFieldType == "boolean") { return NpgsqlDbType.Boolean; } if (PGFieldType == "uuid") { return NpgsqlDbType.Uuid; } if (PGFieldType == "bytea") { return NpgsqlDbType.Bytea; } return DbtypeFromType(type); } /// <summary> /// Creates value for parameter. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> private static object CreateParameterValue(object value) { Type valueType = value.GetType(); if (valueType == typeof(UUID)) //TODO check if this works { return ((UUID) value).Guid; } if (valueType == typeof(UUID)) { return ((UUID)value).Guid; } if (valueType == typeof(bool)) { return (bool)value; } if (valueType == typeof(Byte[])) { return value; } if (valueType == typeof(int)) { return value; } return value; } /// <summary> /// Create value for parameter based on PGSQL Schema /// </summary> /// <param name="value"></param> /// <param name="PGFieldType"></param> /// <returns></returns> internal static object CreateParameterValue(object value, string PGFieldType) { if (PGFieldType == "uuid") { UUID uidout; UUID.TryParse(value.ToString(), out uidout); return uidout; } if (PGFieldType == "integer") { int intout; int.TryParse(value.ToString(), out intout); return intout; } if (PGFieldType == "boolean") { return (value.ToString() == "true"); } if (PGFieldType == "timestamp with time zone") { return (DateTime)value; } if (PGFieldType == "timestamp without time zone") { return (DateTime)value; } return CreateParameterValue(value); } /// <summary> /// Create a parameter for a command /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterObject">parameter object.</param> /// <returns></returns> internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject) { return CreateParameter(parameterName, parameterObject, false); } /// <summary> /// Creates the parameter for a command. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterObject">parameter object.</param> /// <param name="parameterOut">if set to <c>true</c> parameter is a output parameter</param> /// <returns></returns> internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject, bool parameterOut) { //Tweak so we dont always have to add : sign if (parameterName.StartsWith(":")) parameterName = parameterName.Replace(":",""); //HACK if object is null, it is turned into a string, there are no nullable type till now if (parameterObject == null) parameterObject = ""; NpgsqlParameter parameter = new NpgsqlParameter(parameterName, DbtypeFromType(parameterObject.GetType())); if (parameterOut) { parameter.Direction = ParameterDirection.Output; } else { parameter.Direction = ParameterDirection.Input; parameter.Value = CreateParameterValue(parameterObject); } return parameter; } /// <summary> /// Create a parameter with PGSQL schema type /// </summary> /// <param name="parameterName"></param> /// <param name="parameterObject"></param> /// <param name="PGFieldType"></param> /// <returns></returns> internal NpgsqlParameter CreateParameter(string parameterName, object parameterObject, string PGFieldType) { //Tweak so we dont always have to add : sign if (parameterName.StartsWith(":")) parameterName = parameterName.Replace(":", ""); //HACK if object is null, it is turned into a string, there are no nullable type till now if (parameterObject == null) parameterObject = ""; NpgsqlParameter parameter = new NpgsqlParameter(parameterName, DbtypeFromString(parameterObject.GetType(), PGFieldType)); parameter.Direction = ParameterDirection.Input; parameter.Value = CreateParameterValue(parameterObject, PGFieldType); return parameter; } /// <summary> /// Checks if we need to do some migrations to the database /// </summary> /// <param name="migrationStore">migrationStore.</param> public void CheckMigration(string migrationStore) { using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) { connection.Open(); Assembly assem = GetType().Assembly; PGSQLMigration migration = new PGSQLMigration(connection, assem, migrationStore); migration.Update(); } } /// <summary> /// Returns the version of this DB provider /// </summary> /// <returns>A string containing the DB provider</returns> public string getVersion() { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } }
using System; using System.Collections; using System.Drawing; using System.IO; using System.Web; using CookComputing.Blogger; using CookComputing.MetaWeblog; using CookComputing.XmlRpc; using Umbraco.Core.IO; using umbraco.BusinessLogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.media; using umbraco.cms.businesslogic.property; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.presentation.channels.businesslogic; using Post = CookComputing.MetaWeblog.Post; using System.Collections.Generic; using System.Web.Security; using umbraco.IO; using Umbraco.Core; namespace umbraco.presentation.channels { public abstract class UmbracoMetaWeblogAPI : XmlRpcService, IMetaWeblog { internal readonly MediaFileSystem _fs; protected UmbracoMetaWeblogAPI() { _fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>(); } [XmlRpcMethod("blogger.deletePost", Description = "Deletes a post.")] [return: XmlRpcReturnValue(Description = "Always returns true.")] public bool deletePost( string appKey, string postid, string username, string password, [XmlRpcParameter( Description = "Where applicable, this specifies whether the blog " + "should be republished after the post has been deleted.")] bool publish) { if (validateUser(username, password)) { Channel userChannel = new Channel(username); new Document(int.Parse(postid)) .delete(); return true; } return false; } public object editPost( string postid, string username, string password, Post post, bool publish) { if (validateUser(username, password)) { Channel userChannel = new Channel(username); Document doc = new Document(Convert.ToInt32(postid)); doc.Text = HttpContext.Current.Server.HtmlDecode(post.title); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") doc.getProperty(userChannel.FieldExcerptAlias).Value = removeLeftUrl(post.mt_excerpt); if (UmbracoSettings.TidyEditorContent) doc.getProperty(userChannel.FieldDescriptionAlias).Value = library.Tidy(removeLeftUrl(post.description), false); else doc.getProperty(userChannel.FieldDescriptionAlias).Value = removeLeftUrl(post.description); updateCategories(doc, post, userChannel); if (publish) { doc.SaveAndPublish(new User(username)); } return true; } else { return false; } } private void updateCategories(Document doc, Post post, Channel userChannel) { if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); String[] categories = post.categories; string categoryValue = ""; interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { tags.RemoveTagsFromNode(doc.Id); for (int i = 0; i < categories.Length; i++) { tags.AddTagToNode(doc.Id, categories[i]); } //If the IUseTags provider manually set the property value to something on the IData interface then we should persist this //code commented as for some reason, even though the IUseTags control is setting IData.Value it is null here //could be a cache issue, or maybe it's a different instance of the IData or something, rather odd //doc.getProperty(userChannel.FieldCategoriesAlias).Value = categoryType.DataTypeDefinition.DataType.Data.Value; //Instead, set the document property to CSV of the tags - this WILL break custom editors for tags which don't adhere to the //pseudo standard that the .Value of the property contains CSV tags. doc.getProperty(userChannel.FieldCategoriesAlias).Value = string.Join(",", categories); } else { for (int i = 0; i < categories.Length; i++) { PreValue pv = new PreValue(categoryType.DataTypeDefinition.Id, categories[i]); categoryValue += pv.Id + ","; } if (categoryValue.Length > 0) categoryValue = categoryValue.Substring(0, categoryValue.Length - 1); doc.getProperty(userChannel.FieldCategoriesAlias).Value = categoryValue; } } } public CategoryInfo[] getCategories( string blogid, string username, string password) { if (validateUser(username, password)) { Channel userChannel = new Channel(username); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { // Find the propertytype via the document type ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); // check if the datatype uses tags or prevalues CategoryInfo[] returnedCategories = null; interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { List<interfaces.ITag> alltags = tags.GetAllTags(); if (alltags != null) { returnedCategories = new CategoryInfo[alltags.Count]; int counter = 0; foreach (interfaces.ITag t in alltags) { CategoryInfo ci = new CategoryInfo(); ci.title = t.TagCaption; ci.categoryid = t.Id.ToString(); ci.description = ""; ci.rssUrl = ""; ci.htmlUrl = ""; returnedCategories[counter] = ci; counter++; } } else { returnedCategories = new CategoryInfo[0]; } } else { SortedList categories = PreValues.GetPreValues(categoryType.DataTypeDefinition.Id); returnedCategories = new CategoryInfo[categories.Count]; IDictionaryEnumerator ide = categories.GetEnumerator(); int counter = 0; while (ide.MoveNext()) { PreValue category = (PreValue)ide.Value; CategoryInfo ci = new CategoryInfo(); ci.title = category.Value; ci.categoryid = category.Id.ToString(); ci.description = ""; ci.rssUrl = ""; ci.htmlUrl = ""; returnedCategories[counter] = ci; counter++; } } return returnedCategories; } } throw new ArgumentException("Categories doesn't work for this channel, they might not have been activated. Contact your umbraco administrator."); } public static interfaces.IUseTags UseTags(PropertyType categoryType) { if (typeof(interfaces.IUseTags).IsAssignableFrom(categoryType.DataTypeDefinition.DataType.DataEditor.GetType())) { interfaces.IUseTags tags = (interfaces.IUseTags)categoryType.DataTypeDefinition.DataType.DataEditor as interfaces.IUseTags; return tags; } return null; } public Post getPost( string postid, string username, string password) { if (validateUser(username, password)) { Channel userChannel = new Channel(username); Document d = new Document(int.Parse(postid)); Post p = new Post(); p.title = d.Text; p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") p.mt_excerpt = d.getProperty(userChannel.FieldExcerptAlias).Value.ToString(); // Categories if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && d.getProperty(userChannel.FieldCategoriesAlias).Value != null && d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString() != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } p.postid = postid; p.permalink = library.NiceUrl(d.Id); p.dateCreated = d.CreateDateTime; p.link = p.permalink; return p; } else throw new ArgumentException(string.Format("Error retriving post with id: '{0}'", postid)); } public Post[] getRecentPosts( string blogid, string username, string password, int numberOfPosts) { if (validateUser(username, password)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else { if (u.StartNodeId == -1) { rootDoc = Document.GetRootDocuments()[0]; } else { rootDoc = new Document(u.StartNodeId); } } //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, numberOfPosts, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; Post p = new Post(); p.dateCreated = d.CreateDateTime; p.userid = username; p.title = d.Text; p.permalink = library.NiceUrl(d.Id); p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); p.link = library.NiceUrl(d.Id); p.postid = d.Id.ToString(); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && d.getProperty(userChannel.FieldCategoriesAlias).Value != null && d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString() != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") p.mt_excerpt = d.getProperty(userChannel.FieldExcerptAlias).Value.ToString(); blogPostsObjects.Add(p); } return (Post[])blogPostsObjects.ToArray(typeof(Post)); } else { return null; } } protected ArrayList findBlogPosts(Channel userChannel, Document d, String userName, ref int count, int max, bool fullTree) { ArrayList list = new ArrayList(); ContentType ct = d.ContentType; if (ct.Alias.Equals(userChannel.DocumentTypeAlias) & (count < max)) { list.Add(d); count = count + 1; } if (d.Children != null && d.Children.Length > 0 && fullTree) { //store children array here because iterating over an Array object is very inneficient. var c = d.Children; foreach (Document child in c) { if (count < max) { list.AddRange(findBlogPosts(userChannel, child, userName, ref count, max, true)); } } } return list; } public string newPost( string blogid, string username, string password, Post post, bool publish) { if (validateUser(username, password)) { Channel userChannel = new Channel(username); User u = new User(username); Document doc = Document.MakeNew(HttpContext.Current.Server.HtmlDecode(post.title), DocumentType.GetByAlias(userChannel.DocumentTypeAlias), u, userChannel.StartNode); // Excerpt if (userChannel.FieldExcerptAlias != null && userChannel.FieldExcerptAlias != "") doc.getProperty(userChannel.FieldExcerptAlias).Value = removeLeftUrl(post.mt_excerpt); // Description if (UmbracoSettings.TidyEditorContent) doc.getProperty(userChannel.FieldDescriptionAlias).Value = library.Tidy(removeLeftUrl(post.description), false); else doc.getProperty(userChannel.FieldDescriptionAlias).Value = removeLeftUrl(post.description); // Categories updateCategories(doc, post, userChannel); // check release date if (post.dateCreated.Year > 0001) { publish = false; doc.ReleaseDate = post.dateCreated; } if (publish) { doc.SaveAndPublish(new User(username)); } return doc.Id.ToString(); } else throw new ArgumentException("Error creating post"); } protected MediaObjectInfo newMediaObjectLogicForWord( string blogid, string username, string password, FileData file) { UrlData ud = newMediaObjectLogic(blogid, username, password, file); MediaObjectInfo moi = new MediaObjectInfo(); moi.url = ud.url; return moi; } protected UrlData newMediaObjectLogic( string blogid, string username, string password, FileData file) { if (validateUser(username, password)) { User u = new User(username); Channel userChannel = new Channel(username); UrlData fileUrl = new UrlData(); if (userChannel.ImageSupport) { Media rootNode; if (userChannel.MediaFolder > 0) rootNode = new Media(userChannel.MediaFolder); else rootNode = new Media(u.StartMediaId); // Create new media Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id); Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty); var filename = file.name.Replace("/", "_"); var relativeFilePath = _fs.GetRelativePath(fileObject.Id, filename); fileObject.Value = _fs.GetUrl(relativeFilePath); fileUrl.url = fileObject.Value.ToString(); if (!fileUrl.url.StartsWith("http")) { var protocol = GlobalSettings.UseSSL ? "https" : "http"; fileUrl.url = protocol + "://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + fileUrl.url; } _fs.AddFile(relativeFilePath, new MemoryStream(file.bits)); // Try updating standard file values try { string orgExt = ""; // Size if (m.getProperty(Constants.Conventions.Media.Bytes) != null) m.getProperty(Constants.Conventions.Media.Bytes).Value = file.bits.Length; // Extension if (m.getProperty(Constants.Conventions.Media.Extension) != null) { orgExt = ((string) file.name.Substring(file.name.LastIndexOf(".") + 1, file.name.Length - file.name.LastIndexOf(".") - 1)); m.getProperty(Constants.Conventions.Media.Extension).Value = orgExt.ToLower(); } // Width and Height // Check if image and then get sizes, make thumb and update database if (m.getProperty(Constants.Conventions.Media.Width) != null && m.getProperty(Constants.Conventions.Media.Height) != null && ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0) { int fileWidth; int fileHeight; var stream = _fs.OpenFile(relativeFilePath); Image image = Image.FromStream(stream); fileWidth = image.Width; fileHeight = image.Height; stream.Close(); try { m.getProperty(Constants.Conventions.Media.Width).Value = fileWidth.ToString(); m.getProperty(Constants.Conventions.Media.Height).Value = fileHeight.ToString(); } catch { } } } catch { } return fileUrl; } else throw new ArgumentException( "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support."); } return new UrlData(); } private static bool validateUser(string username, string password) { return Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].ValidateUser(username, password); } [XmlRpcMethod("blogger.getUsersBlogs", Description = "Returns information on all the blogs a given user " + "is a member.")] public BlogInfo[] getUsersBlogs( string appKey, string username, string password) { if (validateUser(username, password)) { BlogInfo[] blogs = new BlogInfo[1]; User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); BlogInfo bInfo = new BlogInfo(); bInfo.blogName = userChannel.Name; bInfo.blogid = rootDoc.Id.ToString(); bInfo.url = library.NiceUrlWithDomain(rootDoc.Id, true); blogs[0] = bInfo; return blogs; } throw new ArgumentException(string.Format("No data found for user with username: '{0}'", username)); } private string removeLeftUrl(string text) { return text.Replace(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority), ""); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace FileDialogs { /// <summary> /// A custom combo box that can display icons for each item. /// </summary> [ToolboxItem(false)] internal class LookInComboBox : ComboBox { #region Member Fields // The width of the indent of the ComboItems private int m_indentWidth = 10; // The item for the browser's current selected directory private LookInComboBoxItem m_currentItem; #endregion #region Construction public LookInComboBox() { DrawMode = DrawMode.OwnerDrawFixed; DrawItem += ComboBox_DrawItem; DropDown += ComboBox_DropDown; MouseWheel += ComboBox_MouseWheel; } #endregion #region Methods /// <summary> /// This method will change the currentItem field once a new item is selected /// </summary> protected override void OnSelectedIndexChanged(EventArgs e) { if (SelectedIndex >= 0) m_currentItem = SelectedItem as LookInComboBoxItem; base.OnSelectedIndexChanged(e); } /// <summary> /// This method will draw the items of the DropDownList. It will draw the icon, the text and /// with the indent that goes with the item /// </summary> private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == -1) // The combo box contains no items and the item is the editing portion { if (m_currentItem == null) return; Brush backBrush = new SolidBrush(SystemColors.Window); e.Graphics.FillRectangle(backBrush, e.Bounds); backBrush.Dispose(); int imageYOffset = (e.Bounds.Height - m_currentItem.Icon.Height) / 2; Point imagePoint = new Point( e.Bounds.Left + 2, e.Bounds.Top + imageYOffset); Size textSize = TextRenderer.MeasureText(m_currentItem.Text, e.Font); int textYOffset = (e.Bounds.Height - textSize.Height) / 2; Point textPoint = new Point( e.Bounds.Left + m_currentItem.Icon.Width + 5, e.Bounds.Top + textYOffset); textSize.Height += textYOffset; Rectangle textRect = new Rectangle(textPoint, textSize); bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); if (selected) { Brush selectedBrush = new SolidBrush(SystemColors.Highlight); e.Graphics.FillRectangle(selectedBrush, textRect); selectedBrush.Dispose(); } if (((e.State & DrawItemState.Focus) == DrawItemState.Focus) && ((e.State & DrawItemState.NoFocusRect) != DrawItemState.NoFocusRect)) { ControlPaint.DrawFocusRectangle(e.Graphics, textRect, e.ForeColor, e.BackColor); } e.Graphics.DrawIcon(selected ? m_currentItem.SelectedIcon : m_currentItem.Icon, imagePoint.X, imagePoint.Y); TextRenderer.DrawText(e.Graphics, m_currentItem.Text, e.Font, textPoint, e.ForeColor); } else { LookInComboBoxItem item = (LookInComboBoxItem)Items[e.Index]; Brush backBrush = new SolidBrush(SystemColors.Window); e.Graphics.FillRectangle(backBrush, e.Bounds); backBrush.Dispose(); int indentOffset = m_indentWidth * item.Indent; if ((e.State & DrawItemState.ComboBoxEdit) == DrawItemState.ComboBoxEdit) indentOffset = 0; int imageYOffset = (e.Bounds.Height - item.Icon.Height) / 2; Point imagePoint = new Point( e.Bounds.Left + indentOffset + 2, e.Bounds.Top + imageYOffset); Size textSize = TextRenderer.MeasureText(item.Text, e.Font); int textYOffset = (e.Bounds.Height - textSize.Height) / 2; Point textPoint = new Point( e.Bounds.Left + item.Icon.Width + indentOffset + 5, e.Bounds.Top + textYOffset); textSize.Height += textYOffset; Rectangle textRect = new Rectangle(textPoint, textSize); bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); if (selected) { Brush selectedBrush = new SolidBrush(SystemColors.Highlight); e.Graphics.FillRectangle(selectedBrush, textRect); selectedBrush.Dispose(); } if (((e.State & DrawItemState.Focus) == DrawItemState.Focus) && ((e.State & DrawItemState.NoFocusRect) != DrawItemState.NoFocusRect)) { ControlPaint.DrawFocusRectangle(e.Graphics, textRect, e.ForeColor, e.BackColor); } e.Graphics.DrawIcon(selected ? item.SelectedIcon : item.Icon, imagePoint.X, imagePoint.Y); TextRenderer.DrawText(e.Graphics, item.Text, e.Font, textPoint, e.ForeColor); } } /// <summary> /// This method will make sure that when the ComboBox is dropped down, the width of the DropDownList /// will be sufficient to fit all items /// </summary> private void ComboBox_DropDown(object sender, EventArgs e) { // Calculate drop down width int ddWidth = 0; Graphics g = CreateGraphics(); foreach (LookInComboBoxItem item in Items) { int itemWidth = g.MeasureString(item.Text, Font).ToSize().Width + item.Icon.Width + m_indentWidth * item.Indent + (Items.Count > MaxDropDownItems ? SystemInformation.VerticalScrollBarWidth : 0); if (itemWidth > ddWidth) ddWidth = itemWidth; } DropDownWidth = (ddWidth > Width) ? ddWidth : Width; // Calculate drop down height int ddHeight = Items.Count * ItemHeight + 2; Rectangle comboRect = RectangleToScreen(ClientRectangle); if (comboRect.Bottom + ddHeight > Screen.PrimaryScreen.WorkingArea.Height) ddHeight = Screen.PrimaryScreen.WorkingArea.Height - comboRect.Bottom; DropDownHeight = ((ddHeight - 2) / ItemHeight) * ItemHeight + 2; } protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_CTLCOLORLISTBOX) { Rectangle comboRect = RectangleToScreen(ClientRectangle); int ddX = comboRect.Left; int ddY = comboRect.Bottom; if (ddX < 0) ddX = 0; else if (ddX + DropDownWidth > Screen.PrimaryScreen.WorkingArea.Width) ddX = Screen.PrimaryScreen.WorkingArea.Width - DropDownWidth; NativeMethods.User32.SetWindowPos( new HandleRef(null, m.LParam), NativeMethods.NullHandleRef, ddX, ddY, 0, 0, NativeMethods.SWP_NOSIZE); } base.WndProc(ref m); } private void ComboBox_MouseWheel(object sender, MouseEventArgs e) { ((HandledMouseEventArgs)e).Handled = true; } #endregion #region Properties [Browsable(false)] public LookInComboBoxItem CurrentItem { get { return m_currentItem; } set { m_currentItem = value; } } #endregion } internal class LookInComboBoxItem { #region Member Fields // The text, PIDL and indent that goes with the ComboBoxItem private string m_text; private IntPtr m_pidl; private int m_indent; // The icon that has to be drawn for this ComboBoxItem private Icon m_icon; private Icon m_selectedIcon; #endregion #region Construction public LookInComboBoxItem(string text, IntPtr pidl, int indent) { m_text = text; m_pidl = pidl; m_indent = indent; m_icon = ShellImageList.GetIcon(ShellImageList.GetIconIndex(pidl, false, false), ShellImageListSize.Small); m_selectedIcon = ShellImageList.GetIcon(ShellImageList.GetIconIndex(pidl, true, false), ShellImageListSize.Small); } #endregion #region Methods public override string ToString() { return m_text; } #endregion #region Properties public IntPtr PIDL { get { return m_pidl; } } public int Indent { get { return m_indent; } } public Icon Icon { get { return m_icon; } } public Icon SelectedIcon { get { return m_selectedIcon; } } public string Text { get { return m_text; } } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public abstract class MarshalSpec { // // Constructor Methods // internal static MarshalSpec Create( ArrayReader reader ) { NativeTypes kind = (NativeTypes)reader.ReadCompressedUInt32(); switch(kind) { case NativeTypes.BOOLEAN : case NativeTypes.I1 : case NativeTypes.U1 : case NativeTypes.I2 : case NativeTypes.U2 : case NativeTypes.I4 : case NativeTypes.U4 : case NativeTypes.I8 : case NativeTypes.U8 : case NativeTypes.R4 : case NativeTypes.R8 : case NativeTypes.CURRENCY : case NativeTypes.BSTR : case NativeTypes.LPSTR : case NativeTypes.LPWSTR : case NativeTypes.LPTSTR : case NativeTypes.IUNKNOWN : case NativeTypes.IDISPATCH : case NativeTypes.STRUCT : case NativeTypes.INTF : case NativeTypes.INT : case NativeTypes.UINT : case NativeTypes.BYVALSTR : case NativeTypes.ANSIBSTR : case NativeTypes.TBSTR : case NativeTypes.VARIANTBOOL: case NativeTypes.FUNC : case NativeTypes.ASANY : case NativeTypes.LPSTRUCT : case NativeTypes.ERROR : case NativeTypes.MAX : { Signature.CheckEndOfSignature( reader ); return new MarshalSpecNative( kind ); } case NativeTypes.SAFEARRAY: { VariantTypes elemType; if(reader.IsEOF) { elemType = VariantTypes.VT_EMPTY; } else { elemType = (VariantTypes)reader.ReadCompressedUInt32(); } // APPCOMPACT: Some system assemblies add an extra byte to the marshalling spec. //Signature.CheckEndOfSignature( reader ); return new MarshalSpecSafeArray( elemType ); } case NativeTypes.FIXEDSYSSTRING: { uint elemCount = reader.ReadCompressedUInt32(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecFixedString( elemCount ); } case NativeTypes.FIXEDARRAY: { uint elemCount = reader.ReadCompressedUInt32(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecFixedArray( elemCount ); } case NativeTypes.CUSTOMMARSHALER: { String guid = reader.ReadCompressedString(); String unmanagedType = reader.ReadCompressedString(); String managedType = reader.ReadCompressedString(); String cookie = reader.ReadCompressedString(); Signature.CheckEndOfSignature( reader ); return new MarshalSpecCustom( guid, unmanagedType, managedType, cookie ); } case NativeTypes.ARRAY: { NativeTypes elemType = (NativeTypes)reader.ReadCompressedUInt32(); uint paramNumber = (reader.IsEOF ? 0 : reader.ReadCompressedUInt32()); uint extras = (reader.IsEOF ? 0 : reader.ReadCompressedUInt32()); // APPCOMPACT: Some system assemblies add an extra byte to the marshalling spec. //Signature.CheckEndOfSignature( reader ); return new MarshalSpecArray( elemType, paramNumber, extras ); } default: { throw new Exception( "Unknown marshal spec kind " + kind ); } } } public override abstract String ToString(); } public class MarshalSpecNative : MarshalSpec { // // State // private readonly NativeTypes m_kind; // // Constructor Methods // public MarshalSpecNative( NativeTypes kind ) { m_kind = kind; } // // Access Methods // public NativeTypes Kind { get { return m_kind; } } public override String ToString() { return "MarshalSpecNative(" + m_kind + ")"; } } public class MarshalSpecSafeArray : MarshalSpec { // // State // private readonly VariantTypes m_elemType; // // Constructor Methods // public MarshalSpecSafeArray( VariantTypes elemType ) { m_elemType = elemType; } // // Access Methods // public VariantTypes ElementType { get { return m_elemType; } } public override String ToString() { return "MarshalSpecSafeArray(" + m_elemType + ")"; } } public class MarshalSpecFixedString : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedString( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedString(" + m_elemCount + ")"; } } public class MarshalSpecFixedArray : MarshalSpec { // // State // private readonly uint m_elemCount; // // Constructor Methods // public MarshalSpecFixedArray( uint elemCount ) { m_elemCount = elemCount; } // // Access Methods // public uint ElementCount { get { return m_elemCount; } } public override String ToString() { return "MarshalSpecFixedArray(" + m_elemCount + ")"; } } public class MarshalSpecCustom : MarshalSpec { // // State // private readonly String m_guid; private readonly String m_unmanagedType; private readonly String m_managedType; private readonly String m_cookie; // // Constructor Methods // public MarshalSpecCustom( String guid , String unmanagedType , String managedType , String cookie ) { m_guid = guid; m_unmanagedType = unmanagedType; m_managedType = managedType; m_cookie = cookie; } // // Access Methods // public String Guid { get { return m_guid; } } public String UnmanagedType { get { return m_unmanagedType; } } public String ManagedType { get { return m_managedType; } } public String Cookie { get { return m_cookie; } } public override String ToString() { return "MarshalSpecCustom(" + m_guid + "," + m_managedType + "->" + m_unmanagedType + "," + m_cookie + ")"; } } public class MarshalSpecArray : MarshalSpec { // // State // private readonly NativeTypes m_elemType; private readonly uint m_paramNumber; private readonly uint m_extras; // // Constructor Methods // public MarshalSpecArray( NativeTypes elemType , uint paramNumber , uint extras ) { m_elemType = elemType; m_paramNumber = paramNumber; m_extras = extras; } // // Access Methods // public NativeTypes ElementType { get { return m_elemType; } } public uint ParameterNumber { get { return m_paramNumber; } } public uint ExtraCount { get { return m_extras; } } public override String ToString() { return "MarshalSpecArray(" + m_elemType + "," + m_paramNumber + "," + m_extras + ")"; } } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGFlexDirectionTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGFlexDirectionTest { [Test] public void Test_flex_direction_column_no_height() { YogaNode root = new YogaNode(); root.Width = 100; YogaNode root_child0 = new YogaNode(); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(30f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(30f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_flex_direction_row_no_width() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(30f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(20f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(30f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(20f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_flex_direction_column() { YogaNode root = new YogaNode(); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_flex_direction_row() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(20f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(80f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(70f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_flex_direction_column_reverse() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.ColumnReverse; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Height = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Height = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(90f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(80f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(70f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(90f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(80f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(10f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(70f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(10f, root_child2.LayoutHeight); } [Test] public void Test_flex_direction_row_reverse() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.RowReverse; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 10; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(); root_child2.Width = 10; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(80f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(70f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(10f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); Assert.AreEqual(20f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(10f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; using Orleans.Configuration; namespace Orleans.Providers { /// <summary> /// Adapter factory for in memory stream provider. /// This factory acts as the adapter and the adapter factory. The events are stored in an in-memory grain that /// behaves as an event queue, this provider adapter is primarily used for testing /// </summary> public class MemoryAdapterFactory<TSerializer> : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache where TSerializer : class, IMemoryMessageBodySerializer { private readonly StreamCacheEvictionOptions cacheOptions; private readonly StreamStatisticOptions statisticOptions; private readonly HashRingStreamQueueMapperOptions queueMapperOptions; private readonly IGrainFactory grainFactory; private readonly ITelemetryProducer telemetryProducer; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private readonly TSerializer serializer; private IStreamQueueMapper streamQueueMapper; private ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain> queueGrains; private IObjectPool<FixedSizeBuffer> bufferPool; private BlockPoolMonitorDimensions blockPoolMonitorDimensions; private IStreamFailureHandler streamFailureHandler; private TimePurgePredicate purgePredicate; /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name { get; } /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction => StreamProviderDirection.ReadWrite; /// <summary> /// Creates a failure handler for a partition. /// </summary> protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; } /// <summary> /// Create a cache monitor to report cache related metrics /// Return a ICacheMonitor /// </summary> protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory; /// <summary> /// Create a block pool monitor to monitor block pool related metrics /// Return a IBlockPoolMonitor /// </summary> protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory; /// <summary> /// Create a monitor to monitor QueueAdapterReceiver related metrics /// Return a IQueueAdapterReceiverMonitor /// </summary> protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory; public MemoryAdapterFactory(string providerName, StreamCacheEvictionOptions cacheOptions, StreamStatisticOptions statisticOptions, HashRingStreamQueueMapperOptions queueMapperOptions, IServiceProvider serviceProvider, IGrainFactory grainFactory, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = providerName; this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions)); this.cacheOptions = cacheOptions ?? throw new ArgumentNullException(nameof(cacheOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentException(nameof(statisticOptions)); this.grainFactory = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.logger = loggerFactory.CreateLogger<ILogger<MemoryAdapterFactory<TSerializer>>>(); this.serializer = MemoryMessageBodySerializerFactory<TSerializer>.GetOrCreateSerializer(serviceProvider); } /// <summary> /// Factory initialization. /// </summary> public void Init() { this.queueGrains = new ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain>(); if (CacheMonitorFactory == null) this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer); if (this.BlockPoolMonitorFactory == null) this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer); if (this.ReceiverMonitorFactory == null) this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer); this.purgePredicate = new TimePurgePredicate(this.cacheOptions.DataMinTimeInCache, this.cacheOptions.DataMaxAgeInCache); this.streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name); } private void CreateBufferPoolIfNotCreatedYet() { if (this.bufferPool == null) { // 1 meg block size pool this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}"); var oneMb = 1 << 20; var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb); this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval); } } /// <summary> /// Create queue adapter. /// </summary> /// <returns></returns> public Task<IQueueAdapter> CreateAdapter() { return Task.FromResult<IQueueAdapter>(this); } /// <summary> /// Create queue message cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Create queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { return streamQueueMapper; } /// <summary> /// Creates a queue receiver for the specified queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { var dimensions = new ReceiverMonitorDimensions(queueId.ToString()); var receiverLogger = this.loggerFactory.CreateLogger($"{typeof(MemoryAdapterReceiver<TSerializer>).FullName}.{this.Name}.{queueId}"); var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer); IQueueAdapterReceiver receiver = new MemoryAdapterReceiver<TSerializer>(GetQueueGrain(queueId), receiverLogger, this.serializer, receiverMonitor); return receiver; } /// <summary> /// Writes a set of events to the queue as a single batch associated with the provided streamId. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamId"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public async Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { try { var queueId = streamQueueMapper.GetQueueForStream(streamId); ArraySegment<byte> bodyBytes = serializer.Serialize(new MemoryMessageBody(events.Cast<object>(), requestContext)); var messageData = MemoryMessageData.Create(streamId, bodyBytes); IMemoryStreamQueueGrain queueGrain = GetQueueGrain(queueId); await queueGrain.Enqueue(messageData); } catch (Exception exc) { logger.LogError((int)ProviderErrorCode.MemoryStreamProviderBase_QueueMessageBatchAsync, exc, "Exception thrown in MemoryAdapterFactory.QueueMessageBatchAsync."); throw; } } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { //move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side. CreateBufferPoolIfNotCreatedYet(); var logger = this.loggerFactory.CreateLogger($"{typeof(MemoryPooledCache<TSerializer>).FullName}.{this.Name}.{queueId}"); var monitor = this.CacheMonitorFactory(new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId), this.telemetryProducer); return new MemoryPooledCache<TSerializer>(bufferPool, purgePredicate, logger, this.serializer, monitor, this.statisticOptions.StatisticMonitorWriteInterval); } /// <summary> /// Acquire delivery failure handler for a queue /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler())); } /// <summary> /// Generate a deterministic Guid from a queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private Guid GenerateDeterministicGuid(QueueId queueId) { // provider name hash code int providerNameGuidHash = (int)JenkinsHash.ComputeHash(this.Name); // get queueId hash code uint queueIdHash = queueId.GetUniformHashCode(); byte[] queIdHashByes = BitConverter.GetBytes(queueIdHash); short s1 = BitConverter.ToInt16(queIdHashByes, 0); short s2 = BitConverter.ToInt16(queIdHashByes, 2); // build guid tailing 8 bytes from providerNameGuidHash and queIdHashByes. var tail = new List<byte>(); tail.AddRange(BitConverter.GetBytes(providerNameGuidHash)); tail.AddRange(queIdHashByes); // make guid. // - First int is provider name hash // - Two shorts from queue Id hash // - 8 byte tail from provider name hash and queue Id hash. return new Guid(providerNameGuidHash, s1, s2, tail.ToArray()); } /// <summary> /// Get a MemoryStreamQueueGrain instance by queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private IMemoryStreamQueueGrain GetQueueGrain(QueueId queueId) { return queueGrains.GetOrAdd(queueId, id => grainFactory.GetGrain<IMemoryStreamQueueGrain>(GenerateDeterministicGuid(id))); } public static MemoryAdapterFactory<TSerializer> Create(IServiceProvider services, string name) { var cachePurgeOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name); var factory = ActivatorUtilities.CreateInstance<MemoryAdapterFactory<TSerializer>>(services, name, cachePurgeOptions, statisticOptions, queueMapperOptions); factory.Init(); return factory; } } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.TypeSystem; using System.Collections.Generic; using System.Linq; namespace Bridge.Translator { public class LambdaBlock : AbstractMethodBlock { public LambdaBlock(IEmitter emitter, LambdaExpression lambdaExpression) : this(emitter, lambdaExpression.Parameters, lambdaExpression.Body, lambdaExpression, lambdaExpression.IsAsync) { } public LambdaBlock(IEmitter emitter, AnonymousMethodExpression anonymousMethodExpression) : this(emitter, anonymousMethodExpression.Parameters, anonymousMethodExpression.Body, anonymousMethodExpression, anonymousMethodExpression.IsAsync) { } public LambdaBlock(IEmitter emitter, IEnumerable<ParameterDeclaration> parameters, AstNode body, AstNode context, bool isAsync) : base(emitter, context) { this.Emitter = emitter; this.Parameters = parameters; this.Body = body; this.Context = context; this.IsAsync = isAsync; } public bool IsAsync { get; set; } public IEnumerable<ParameterDeclaration> Parameters { get; set; } public AstNode Body { get; set; } public AstNode Context { get; set; } protected bool PreviousIsAync { get; set; } protected List<string> PreviousAsyncVariables { get; set; } protected IAsyncBlock PreviousAsyncBlock { get; set; } public bool ReplaceAwaiterByVar { get; set; } protected override void DoEmit() { if (this.Emitter.TempVariables == null) { this.ResetLocals(); } var oldReplaceJump = this.Emitter.ReplaceJump; this.Emitter.ReplaceJump = false; var rr = this.Emitter.Resolver.ResolveNode(this.Context, this.Emitter); if (this.Context is Expression) { var conversion = this.Emitter.Resolver.Resolver.GetConversion((Expression)this.Context); if (conversion.IsAnonymousFunctionConversion) { var type = this.Emitter.Resolver.Resolver.GetExpectedType((Expression)this.Context); if (type.FullName == typeof(System.Linq.Expressions.Expression).FullName && type.TypeParameterCount == 1) { var expr = new ExpressionTreeBuilder(this.Emitter.Resolver.Compilation, this.Emitter, this.Context.GetParent<SyntaxTree>(), this).BuildExpressionTree((LambdaResolveResult)rr); this.Write(expr); return; } } } var oldParentVariables = this.Emitter.ParentTempVariables; if (this.Emitter.ParentTempVariables == null) { this.Emitter.ParentTempVariables = new Dictionary<string, bool>(this.Emitter.TempVariables); } else { this.Emitter.ParentTempVariables = new Dictionary<string, bool>(this.Emitter.ParentTempVariables); foreach (var item in this.Emitter.TempVariables) { this.Emitter.ParentTempVariables.Add(item.Key, item.Value); } } var oldVars = this.Emitter.TempVariables; this.Emitter.TempVariables = new Dictionary<string, bool>(); this.PreviousIsAync = this.Emitter.IsAsync; this.Emitter.IsAsync = this.IsAsync; this.PreviousAsyncVariables = this.Emitter.AsyncVariables; this.Emitter.AsyncVariables = null; this.PreviousAsyncBlock = this.Emitter.AsyncBlock; this.Emitter.AsyncBlock = null; this.ReplaceAwaiterByVar = this.Emitter.ReplaceAwaiterByVar; this.Emitter.ReplaceAwaiterByVar = false; this.EmitLambda(this.Parameters, this.Body, this.Context); this.Emitter.IsAsync = this.PreviousIsAync; this.Emitter.AsyncVariables = this.PreviousAsyncVariables; this.Emitter.AsyncBlock = this.PreviousAsyncBlock; this.Emitter.ReplaceAwaiterByVar = this.ReplaceAwaiterByVar; this.Emitter.TempVariables = oldVars; this.Emitter.ParentTempVariables = oldParentVariables; this.Emitter.ReplaceJump = oldReplaceJump; } internal static Statement GetOuterLoop(AstNode context) { Statement loop = null; context.GetParent(node => { bool stopSearch = false; if (node is ForStatement || node is ForeachStatement || node is DoWhileStatement || node is WhileStatement) { loop = (Statement)node; } else if (node is EntityDeclaration || node is LambdaExpression || node is AnonymousMethodExpression) { stopSearch = true; } return stopSearch; }); return loop; } internal static IVariable[] GetCapturedLoopVariables(IEmitter emitter, AstNode context, IEnumerable<ParameterDeclaration> parameters, bool excludeReadOnly = false) { var loop = LambdaBlock.GetOuterLoop(context); if (loop == null) { return null; } var loopVariablesAnalyzer = new LoopVariablesAnalyzer(emitter, excludeReadOnly); loopVariablesAnalyzer.Analyze(loop); var captureAnalyzer = new CaptureAnalyzer(emitter); captureAnalyzer.Analyze(context, parameters.Select(p => p.Name)); return captureAnalyzer.UsedVariables.Where(v => loopVariablesAnalyzer.Variables.Contains(v)).ToArray(); } private string[] GetCapturedLoopVariablesNames() { var capturedVariables = LambdaBlock.GetCapturedLoopVariables(this.Emitter, this.Context, this.Parameters); if (capturedVariables == null) { return null; } List<string> names = new List<string>(); foreach (var capturedVariable in capturedVariables) { if (this.Emitter.LocalsMap != null && this.Emitter.LocalsMap.ContainsKey(capturedVariable)) { names.Add(this.RemoveReferencePart(this.Emitter.LocalsMap[capturedVariable])); } else if (this.Emitter.LocalsNamesMap != null && this.Emitter.LocalsNamesMap.ContainsKey(capturedVariable.Name)) { names.Add(this.RemoveReferencePart(this.Emitter.LocalsNamesMap[capturedVariable.Name])); } else { names.Add(capturedVariable.Name); } } return names.ToArray(); } private string RemoveReferencePart(string name) { if (name.EndsWith(".v")) { name = name.Remove(name.Length - 2); } return name; } protected virtual void EmitLambda(IEnumerable<ParameterDeclaration> parameters, AstNode body, AstNode context) { var rr = this.Emitter.Resolver.ResolveNode(context, this.Emitter); var oldLifting = this.Emitter.ForbidLifting; this.Emitter.ForbidLifting = false; var noLiftingRule = this.Emitter.Rules.Lambda == LambdaRule.Plain; CaptureAnalyzer analyzer = null; if (!noLiftingRule) { analyzer = new CaptureAnalyzer(this.Emitter); analyzer.Analyze(this.Body, this.Parameters.Select(p => p.Name)); } var oldLevel = this.Emitter.Level; if (!noLiftingRule && analyzer.UsedVariables.Count == 0) { this.Emitter.ResetLevel(); Indent(); } IAsyncBlock asyncBlock = null; this.PushLocals(); if (this.IsAsync) { if (context is LambdaExpression) { asyncBlock = new AsyncBlock(this.Emitter, (LambdaExpression)context); } else { asyncBlock = new AsyncBlock(this.Emitter, (AnonymousMethodExpression)context); } asyncBlock.InitAsyncBlock(); } else if (YieldBlock.HasYield(body)) { this.IsAsync = true; if (context is LambdaExpression) { asyncBlock = new GeneratorBlock(this.Emitter, (LambdaExpression)context); } else { asyncBlock = new GeneratorBlock(this.Emitter, (AnonymousMethodExpression)context); } asyncBlock.InitAsyncBlock(); } var prevMap = this.BuildLocalsMap(); var prevNamesMap = this.BuildLocalsNamesMap(); this.AddLocals(parameters, body); bool block = body is BlockStatement; this.Write(""); var savedThisCount = this.Emitter.ThisRefCounter; var capturedVariables = this.GetCapturedLoopVariablesNames(); var hasCapturedVariables = capturedVariables != null && capturedVariables.Length > 0; if (hasCapturedVariables) { this.Write("(function ($me, "); this.Write(string.Join(", ", capturedVariables) + ") "); this.BeginBlock(); this.Write("return "); } var savedPos = this.Emitter.Output.Length; this.WriteFunction(); this.EmitMethodParameters(parameters, null, context); this.WriteSpace(); int pos = 0; if (!block && !this.IsAsync) { this.BeginBlock(); pos = this.Emitter.Output.Length; } bool isSimpleLambda = body.Parent is LambdaExpression && !block && !this.IsAsync; if (isSimpleLambda) { this.ConvertParamsToReferences(parameters); var lrr = rr as LambdaResolveResult; if (lrr == null || lrr.ReturnType.Kind != TypeKind.Void) { this.WriteReturn(true); } } if (this.IsAsync) { asyncBlock.Emit(true); } else { body.AcceptVisitor(this.Emitter); } if (isSimpleLambda) { this.WriteSemiColon(); } if (!block && !this.IsAsync) { this.WriteNewLine(); this.EndBlock(); } if (!block && !this.IsAsync) { this.EmitTempVars(pos); } if (!noLiftingRule && analyzer.UsedVariables.Count == 0) { if (!this.Emitter.ForbidLifting) { var name = "f" + (this.Emitter.NamedFunctions.Count + 1); var code = this.Emitter.Output.ToString().Substring(savedPos); var codeForComare = this.RemoveTokens(code); var pair = this.Emitter.NamedFunctions.FirstOrDefault(p => { if (this.Emitter.AssemblyInfo.SourceMap.Enabled) { return this.RemoveTokens(p.Value) == codeForComare; } return p.Value == code; }); if (pair.Key != null && pair.Value != null) { name = pair.Key; } else { this.Emitter.NamedFunctions.Add(name, code); } this.Emitter.Output.Remove(savedPos, this.Emitter.Output.Length - savedPos); this.Emitter.Output.Insert(savedPos, JS.Vars.D_ + "." + BridgeTypes.ToJsName(this.Emitter.TypeInfo.Type, this.Emitter, true) + "." + name); } this.Emitter.ResetLevel(oldLevel); } this.Emitter.ForbidLifting = oldLifting; var methodDeclaration = this.Body.GetParent<MethodDeclaration>(); var thisCaptured = this.Emitter.ThisRefCounter > savedThisCount || this.IsAsync && methodDeclaration != null && !methodDeclaration.HasModifier(Modifiers.Static); if (thisCaptured) { this.Emitter.Output.Insert(savedPos, JS.Funcs.BRIDGE_BIND + (hasCapturedVariables ? "($me, " : "(this, ")); this.WriteCloseParentheses(); } if (hasCapturedVariables) { this.WriteSemiColon(true); this.EndBlock(); this.Write(")("); this.Write("this, "); this.Write(string.Join(", ", capturedVariables)); this.Write(")"); } this.PopLocals(); this.ClearLocalsMap(prevMap); this.ClearLocalsNamesMap(prevNamesMap); } } }
// Contains code from bplusdotnet project (BSD License) by Aaron Watters, Copyright 2004: http://bplusdotnet.sourceforge.net/ using System; using System.Collections.Generic; using System.Text; namespace McBits.LanguageLib.BPTree { public class BPNode<TValue> { private const byte NonLeaf = 0; private const byte Leaf = 1; internal const byte Free = 2; private long[] _childBufferIds; private string[] _childKeys; // true if the materialized node needs to be persisted. private bool _dirty; private int _indexInParent = -1; private BPNode<TValue>[] _materializedChildNodes; // tree containing this node private BPTreeBase<TValue> _owner; // if non-root reference to the parent node containing this node private BPNode<TValue> _parent; // the maximum number of children to each node. private int _size; public bool IsLeaf; // buffer number of this node public long MyBufferId = BPTreeBase<TValue>.NullBufferId; /// <summary> /// Create a new BplusNode and install in parent if parent is not null. /// </summary> /// <param name="owner">tree containing the node</param> /// <param name="parent">parent node (if provided)</param> /// <param name="indexInParent">location in parent if provided</param> /// <param name="isLeaf"></param> public BPNode(BPTreeBase<TValue> owner, BPNode<TValue> parent, int indexInParent, bool isLeaf) { IsLeaf = isLeaf; _owner = owner; _parent = parent; _size = owner.BackingNodeSize; _dirty = true; Clear(); if (parent == null || indexInParent < 0) return; if (indexInParent > _size) throw new BPTreeException("Parent index too large"); // key info, etc, set elsewhere _parent._materializedChildNodes[indexInParent] = this; MyBufferId = _parent._childBufferIds[indexInParent]; _indexInParent = indexInParent; } public BPNode<TValue> FirstChild() { var result = MaterializeNodeAtIndex(0); if (result == null) throw new BPTreeException("No first child"); return result; } public long MakeRoot() { _parent = null; _indexInParent = -1; if (MyBufferId == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("No root seek allocated to new root"); return MyBufferId; } public void FreeBuffers() { if (MyBufferId != BPTreeBase<TValue>.NullBufferId) { // Free now or on commit if (_owner.FreeBuffersOnAbort.Contains(MyBufferId)) { _owner.FreeBuffersOnAbort.Remove(MyBufferId); _owner.DeallocateBuffer(MyBufferId); } else if (!_owner.FreeBuffersOnCommit.Contains(MyBufferId)) _owner.FreeBuffersOnCommit.Add(MyBufferId); } // don't do it twice... MyBufferId = BPTreeBase<TValue>.NullBufferId; } public void SerializationCheck() { var a = new BPNode<TValue>(_owner, null, -1, false); for (int i = 0; i < _size; ++i) { long j = i * 0xf0f0f0f0f0f0f01; a._childBufferIds[i] = j; a._childKeys[i] = "k" + i; } a._childBufferIds[_size] = 7; a.TestRebuffer(); a.IsLeaf = true; for (int i = 0; i < _size; ++i) { long j = -i * 0x3e3e3e3e3e3e666; a._childBufferIds[i] = j; a._childKeys[i] = "key" + i; } a._childBufferIds[_size] = -9097; a.TestRebuffer(); } private void TestRebuffer() { bool isLeaf = IsLeaf; var childBufferIds = (long[]) _childBufferIds.Clone(); var childKeys = (string[]) _childKeys.Clone(); var buffer = new byte[_owner.BufferSize]; Dump(buffer); Clear(); Load(buffer); for (int i = 0; i < _size; ++i) { if (_childBufferIds[i] != childBufferIds[i]) throw new BPTreeException("Didn't get back bufferId " + i + " got " + _childBufferIds[i] + " not " + childBufferIds[i]); if (!_childKeys[i].Equals(childKeys[i])) throw new BPTreeException("Didn't get back key " + i + " got " + _childKeys[i] + " not " + childKeys[i]); } if (_childBufferIds[_size] != childBufferIds[_size]) throw new BPTreeException("Didn't get back bufferId " + _size + " got " + _childBufferIds[_size] + " not " + childBufferIds[_size]); if (IsLeaf != isLeaf) throw new BPTreeException("IsLeaf should be " + isLeaf + " got " + IsLeaf); } public string SanityCheck(Dictionary<object, object> visited) { if (visited == null) visited = new Dictionary<object, object>(); if (visited.ContainsKey(this)) throw new BPTreeException("Node visited twice " + MyBufferId); visited[this] = MyBufferId; if (MyBufferId != BPTreeBase<TValue>.NullBufferId) { if (visited.ContainsKey(MyBufferId)) throw new BPTreeException("Buffer number seen twice " + MyBufferId); visited[MyBufferId] = this; } if (_parent != null) { if (_parent.IsLeaf) throw new BPTreeException("Parent is leaf"); _parent.MaterializeNodeAtIndex(_indexInParent); if (_parent._materializedChildNodes[_indexInParent] != this) throw new BPTreeException("Incorrect index in parent"); // since not at root there should be at least size/2 keys int limit = _size / 2; if (IsLeaf) limit--; for (int i = 0; i < limit; ++i) { if (_childKeys[i] == null) throw new BPTreeException("Null child in first half"); } } string result = _childKeys[0]; if (!IsLeaf) { MaterializeNodeAtIndex(0); result = _materializedChildNodes[0].SanityCheck(visited); for (int i = 0; i < _size; ++i) { if (_childKeys[i] == null) break; MaterializeNodeAtIndex(i + 1); string least = _materializedChildNodes[i + 1].SanityCheck(visited); if (least == null) throw new BPTreeException("Null least in child doesn't match node entry " + _childKeys[i]); if (!least.Equals(_childKeys[i])) throw new BPTreeException("Least in child " + least + " doesn't match node entry " + _childKeys[i]); } } // look for duplicate keys string lastkey = _childKeys[0]; for (int i = 1; i < _size; ++i) { if (_childKeys[i] == null) break; if (lastkey.Equals(_childKeys[i])) throw new BPTreeException("Duplicate key in node " + lastkey); lastkey = _childKeys[i]; } return result; } private void Destroy() { // make sure the structure is useless, it should no longer be used. _owner = null; _parent = null; _size = -100; _childBufferIds = null; _childKeys = null; _materializedChildNodes = null; MyBufferId = BPTreeBase<TValue>.NullBufferId; _indexInParent = -100; _dirty = false; } public int SizeInUse() { int sizeInUse = 0; for (int i = 0; i < _size && _childKeys[i] != null; ++i) { ++sizeInUse; } return sizeInUse; } public static BPNode<TValue> BinaryRoot(BPNode<TValue> leftNode, string key, BPNode<TValue> rightNode, BPTreeBase<TValue> owner) { var newRoot = new BPNode<TValue>(owner, null, -1, false); newRoot._childKeys[0] = key; leftNode.Reparent(newRoot, 0); rightNode.Reparent(newRoot, 1); // new root is stored elsewhere return newRoot; } private void Reparent(BPNode<TValue> newParent, int parentIndex) { // keys and existing parent structure must be updated elsewhere. _parent = newParent; _indexInParent = parentIndex; newParent._childBufferIds[parentIndex] = MyBufferId; newParent._materializedChildNodes[parentIndex] = this; // parent is no longer terminal _owner.ForgetTerminalNode(_parent); } private void Clear() { _childBufferIds = new long[_size + 1]; _childKeys = new string[_size]; _materializedChildNodes = new BPNode<TValue>[_size + 1]; for (int i = 0; i <= _size; ++i) { _childBufferIds[i] = BPTreeBase<TValue>.NullBufferId; } // this is now a terminal node _owner.RecordTerminalNode(this); } /// <summary> /// Find first index in self associated with a key same or greater than CompareKey /// </summary> /// <param name="compareKey">CompareKey</param> /// <param name="lookPastOnly">if true and this is a leaf then look for a greater value</param> /// <returns>lowest index of same or greater key or this.Size if no greater key.</returns> private int FindAtOrNextPosition(string compareKey, bool lookPastOnly) { int insertPosition = 0; if (IsLeaf && !lookPastOnly) { // look for exact match or greater or null while (insertPosition < _size && _childKeys[insertPosition] != null && _owner.Compare(_childKeys[insertPosition], compareKey) < 0) { ++insertPosition; } } else { // look for greater or null only while (insertPosition < _size && _childKeys[insertPosition] != null && _owner.Compare(_childKeys[insertPosition], compareKey) <= 0) { ++insertPosition; } } return insertPosition; } /// <summary> /// Find the first key below atIndex, or if no such node traverse to the next key to the right. /// If no such key exists, return nulls. /// </summary> /// <param name="atIndex">where to look in this node</param> /// <param name="foundInLeaf">leaf where found</param> /// <param name="keyFound">key value found</param> private void TraverseToFollowingKey(int atIndex, out BPNode<TValue> foundInLeaf, out string keyFound) { foundInLeaf = null; keyFound = null; bool lookInParent = IsLeaf ? (atIndex >= _size) || (_childKeys[atIndex] == null) : (atIndex > _size) || (atIndex > 0 && _childKeys[atIndex - 1] == null); if (lookInParent) { // if it's anywhere it's in the next child of parent if (_parent == null || _indexInParent < 0) return; _parent.TraverseToFollowingKey(_indexInParent + 1, out foundInLeaf, out keyFound); return; // no such following key } if (IsLeaf) { // leaf, we found it. foundInLeaf = this; keyFound = _childKeys[atIndex]; } // nonleaf, look in child (if there is one) else if (atIndex == 0 || _childKeys[atIndex - 1] != null) { var child = MaterializeNodeAtIndex(atIndex); child.TraverseToFollowingKey(0, out foundInLeaf, out keyFound); } } public bool FindMatch(string compareKey, out long valueFound) { valueFound = 0; // dummy value on failure BPNode<TValue> leaf; int position = FindAtOrNextPositionInLeaf(compareKey, out leaf, false); if (position >= leaf._size) return false; string key = leaf._childKeys[position]; if ((key == null) || _owner.Compare(key, compareKey) != 0) return false; valueFound = leaf._childBufferIds[position]; return true; } public string FindNextKey(string compareKey) { BPNode<TValue> leaf; int position = FindAtOrNextPositionInLeaf(compareKey, out leaf, true); if (position < leaf._size && leaf._childKeys[position] != null) return leaf._childKeys[position]; // try to traverse to the right. BPNode<TValue> newleaf; string result; leaf.TraverseToFollowingKey(leaf._size, out newleaf, out result); return result; } /// <summary> /// Find near-index of comparekey in leaf under this node. /// </summary> /// <param name="compareKey">the key to look for</param> /// <param name="inLeaf">the leaf where found</param> /// <param name="lookPastOnly">If true then only look for a greater value, not an exact match.</param> /// <returns>index of match in leaf</returns> private int FindAtOrNextPositionInLeaf(string compareKey, out BPNode<TValue> inLeaf, bool lookPastOnly) { int myposition = FindAtOrNextPosition(compareKey, lookPastOnly); if (IsLeaf) { inLeaf = this; return myposition; } long childBufferId = _childBufferIds[myposition]; if (childBufferId == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("can't search null subtree"); var child = MaterializeNodeAtIndex(myposition); return child.FindAtOrNextPositionInLeaf(compareKey, out inLeaf, lookPastOnly); } private BPNode<TValue> MaterializeNodeAtIndex(int myposition) { if (IsLeaf) throw new BPTreeException("cannot materialize child for leaf"); long childBufferId = _childBufferIds[myposition]; if (childBufferId == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("can't search null subtree at position " + myposition + " in " + MyBufferId); // is it already materialized? var result = _materializedChildNodes[myposition]; if (result != null) return result; // otherwise read it in... result = new BPNode<TValue>(_owner, this, myposition, true); // dummy isLeaf value result.LoadFromBuffer(childBufferId); _materializedChildNodes[myposition] = result; // no longer terminal _owner.ForgetTerminalNode(this); return result; } public void LoadFromBuffer(long bufferId) { var rawdata = new byte[_owner.BufferSize]; _owner.BackingBuffers.ReadBuffer(bufferId, rawdata, 0, rawdata.Length); Load(rawdata); _dirty = false; MyBufferId = bufferId; // it's terminal until a child is materialized _owner.RecordTerminalNode(this); } public long DumpToFreshBuffer() { long oldBufferId = MyBufferId; long freshBufferId = _owner.AllocateBuffer(); // dumping this.indexInParent from oldBufferId to freshBufferId DumpToBuffer(freshBufferId); if (oldBufferId != BPTreeBase<TValue>.NullBufferId) { if (_owner.FreeBuffersOnAbort.Contains(oldBufferId)) { // free it now _owner.FreeBuffersOnAbort.Remove(oldBufferId); _owner.DeallocateBuffer(oldBufferId); } else // free on commit if (!_owner.FreeBuffersOnCommit.Contains(oldBufferId)) _owner.FreeBuffersOnCommit.Add(oldBufferId); } if (!_owner.FreeBuffersOnAbort.Contains(freshBufferId)) _owner.FreeBuffersOnAbort.Add(freshBufferId); return freshBufferId; } private void DumpToBuffer(long bufferId) { var rawdata = new byte[_owner.BufferSize]; Dump(rawdata); _owner.BackingBuffers.WriteBuffer(bufferId, rawdata, 0, rawdata.Length); _dirty = false; MyBufferId = bufferId; if (_parent == null || _indexInParent < 0 || _parent._childBufferIds[_indexInParent] == bufferId) return; if (_parent._materializedChildNodes[_indexInParent] != this) throw new BPTreeException("invalid parent connection " + _parent.MyBufferId + " at " + _indexInParent); _parent._childBufferIds[_indexInParent] = bufferId; _parent.Soil(); } private void ReParentAllChildren() { for (int i = 0; i <= _size; ++i) { var thisnode = _materializedChildNodes[i]; if (thisnode != null) thisnode.Reparent(this, i); } } /// <summary> /// Delete entry for key /// </summary> /// <param name="key">key to delete</param> /// <param name="mergeMe">true if the node is less than half full after deletion</param> /// <returns>null unless the smallest key under this node has changed in which case it returns the smallest key.</returns> public string Delete(string key, out bool mergeMe) { mergeMe = false; // assumption string result = null; if (IsLeaf) return DeleteLeaf(key, out mergeMe); int deleteposition = FindAtOrNextPosition(key, false); long deleteBufferId = _childBufferIds[deleteposition]; if (deleteBufferId == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("key not followed by buffer number in non-leaf (del)"); // del in subtree var deleteChild = MaterializeNodeAtIndex(deleteposition); bool mergeChild; string delresult = deleteChild.Delete(key, out mergeChild); // delete succeeded... now fix up the child node if needed. Soil(); // redundant ? // bizarre special case for 2-3 or 3-4 trees -- empty leaf if (delresult != null && _owner.Compare(delresult, key) == 0) // delresult.Equals(key) { if (_size > 3) throw new BPTreeException("assertion error: delete returned delete key for too large node size: " + _size); // junk this leaf and shift everything over if (deleteposition == 0) result = _childKeys[deleteposition]; else if (deleteposition == _size) _childKeys[deleteposition - 1] = null; else _childKeys[deleteposition - 1] = _childKeys[deleteposition]; if (result != null && _owner.Compare(result, key) == 0) // result.Equals(key) { // I'm not sure this ever happens MaterializeNodeAtIndex(1); result = _materializedChildNodes[1].LeastKey(); } deleteChild.FreeBuffers(); for (int i = deleteposition; i < _size - 1; ++i) { _childKeys[i] = _childKeys[i + 1]; _materializedChildNodes[i] = _materializedChildNodes[i + 1]; _childBufferIds[i] = _childBufferIds[i + 1]; } _childKeys[_size - 1] = null; if (deleteposition < _size) { _materializedChildNodes[_size - 1] = _materializedChildNodes[_size]; _childBufferIds[_size - 1] = _childBufferIds[_size]; } _materializedChildNodes[_size] = null; _childBufferIds[_size] = BPTreeBase<TValue>.NullBufferId; mergeMe = (SizeInUse() < _size / 2); ReParentAllChildren(); return result; } // smallest key may have changed. if (deleteposition == 0) result = delresult; // update key array if needed else if (delresult != null && deleteposition > 0) { if (_owner.Compare(delresult, key) != 0) // !delresult.Equals(key) _childKeys[deleteposition - 1] = delresult; } if (mergeChild) result = MergeChild(ref mergeMe, deleteposition, deleteChild, result); return result; } // Extracted from Delete() private string MergeChild(ref bool mergeMe, int deletePosition, BPNode<TValue> deleteChild, string result) { // if the child needs merging... do it int leftindex, rightindex; BPNode<TValue> leftNode; BPNode<TValue> rightNode; if (deletePosition == 0) { // merge with next leftindex = deletePosition; rightindex = deletePosition + 1; leftNode = deleteChild; //keyBetween = this.ChildKeys[deleteposition]; rightNode = MaterializeNodeAtIndex(rightindex); } else { // merge with previous leftindex = deletePosition - 1; rightindex = deletePosition; leftNode = MaterializeNodeAtIndex(leftindex); //keyBetween = this.ChildKeys[deleteBufferId-1]; rightNode = deleteChild; } string keyBetween = _childKeys[leftindex]; string rightLeastKey; bool deleteRight; Merge(leftNode, keyBetween, rightNode, out rightLeastKey, out deleteRight); // delete the right node if needed. if (deleteRight) { for (int i = rightindex; i < _size; ++i) { _childKeys[i - 1] = _childKeys[i]; _childBufferIds[i] = _childBufferIds[i + 1]; _materializedChildNodes[i] = _materializedChildNodes[i + 1]; } _childKeys[_size - 1] = null; _materializedChildNodes[_size] = null; _childBufferIds[_size] = BPTreeBase<TValue>.NullBufferId; ReParentAllChildren(); rightNode.FreeBuffers(); // does this node need merging? if (SizeInUse() < _size / 2) mergeMe = true; } else // update the key entry _childKeys[rightindex - 1] = rightLeastKey; return result; } private string LeastKey() { string result; if (IsLeaf) result = _childKeys[0]; else { MaterializeNodeAtIndex(0); result = _materializedChildNodes[0].LeastKey(); } if (result == null) throw new BPTreeException("no key found"); return result; } public static void Merge(BPNode<TValue> left, string keyBetween, BPNode<TValue> right, out string rightLeastKey, out bool deleteRight) { // merging right.myBufferId (keyBetween) left.myBufferId rightLeastKey = null; // only if DeleteRight if (left.IsLeaf || right.IsLeaf) { rightLeastKey = MergeLeaves(left, right, out deleteRight); return; } // merge non-leaves deleteRight = false; var allkeys = new string[left._size * 2 + 1]; var allseeks = new long[left._size * 2 + 2]; var allMaterialized = new BPNode<TValue>[left._size * 2 + 2]; if (left._childBufferIds[0] == BPTreeBase<TValue>.NullBufferId || right._childBufferIds[0] == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("cannot merge empty non-leaf with non-leaf"); int index = 0; allseeks[0] = left._childBufferIds[0]; allMaterialized[0] = left._materializedChildNodes[0]; for (int i = 0; i < left._size; ++i) { if (left._childKeys[i] == null) break; allkeys[index] = left._childKeys[i]; allseeks[index + 1] = left._childBufferIds[i + 1]; allMaterialized[index + 1] = left._materializedChildNodes[i + 1]; ++index; } allkeys[index] = keyBetween; ++index; allseeks[index] = right._childBufferIds[0]; allMaterialized[index] = right._materializedChildNodes[0]; int rightcount = 0; for (int i = 0; i < right._size && right._childKeys[i] != null; ++i) { allkeys[index] = right._childKeys[i]; allseeks[index + 1] = right._childBufferIds[i + 1]; allMaterialized[index + 1] = right._materializedChildNodes[i + 1]; ++index; ++rightcount; } // if it will all fit in one node if (index <= left._size) { // deciding to forget "+right.myBufferId+" into "+left.myBufferId); deleteRight = true; for (int i = 0; i < index; ++i) { left._childKeys[i] = allkeys[i]; left._childBufferIds[i] = allseeks[i]; left._materializedChildNodes[i] = allMaterialized[i]; } left._childBufferIds[index] = allseeks[index]; left._materializedChildNodes[index] = allMaterialized[index]; left.ReParentAllChildren(); left.Soil(); right.FreeBuffers(); return; } // otherwise split the content between the nodes left.Clear(); right.Clear(); left.Soil(); right.Soil(); int leftcontent = index / 2; int rightcontent = index - leftcontent - 1; int outputIndex = 0; for (int i = 0; i < leftcontent; ++i) { left._childKeys[i] = allkeys[outputIndex]; left._childBufferIds[i] = allseeks[outputIndex]; left._materializedChildNodes[i] = allMaterialized[outputIndex]; ++outputIndex; } rightLeastKey = allkeys[outputIndex]; left._childBufferIds[outputIndex] = allseeks[outputIndex]; left._materializedChildNodes[outputIndex] = allMaterialized[outputIndex]; ++outputIndex; rightcount = 0; for (int i = 0; i < rightcontent; ++i) { right._childKeys[i] = allkeys[outputIndex]; right._childBufferIds[i] = allseeks[outputIndex]; right._materializedChildNodes[i] = allMaterialized[outputIndex]; ++outputIndex; ++rightcount; } right._childBufferIds[rightcount] = allseeks[outputIndex]; right._materializedChildNodes[rightcount] = allMaterialized[outputIndex]; left.ReParentAllChildren(); right.ReParentAllChildren(); } public static string MergeLeaves(BPNode<TValue> left, BPNode<TValue> right, out bool deleteRight) { if (!left.IsLeaf || !right.IsLeaf) throw new BPTreeException("can't merge leaf with non-leaf"); var allkeys = new string[left._size * 2]; var allseeks = new long[left._size * 2]; int index = 0; FillKeysAndSeeks(left, allkeys, allseeks, ref index); FillKeysAndSeeks(right, allkeys, allseeks, ref index); int newindex = 0; left.Clear(); left.Soil(); if (index > left._size) { deleteRight = false; right.Clear(); right.Soil(); int rightcontent = index / 2; int leftcontent = index - rightcontent; DumpKeysAndSeeks(left, leftcontent, allkeys, allseeks, ref newindex); DumpKeysAndSeeks(right, rightcontent, allkeys, allseeks, ref newindex); } else { deleteRight = true; DumpKeysAndSeeks(left, index, allkeys, allseeks, ref newindex); right.FreeBuffers(); } return right._childKeys[0]; } // Extracted from MergeLeaves private static void DumpKeysAndSeeks(BPNode<TValue> left, int count, IReadOnlyList<string> keys, IReadOnlyList<long> seeks, ref int offset) { for (int i = 0; i < count; ++i) { left._childKeys[i] = keys[offset]; left._childBufferIds[i] = seeks[offset]; ++offset; } } // Extracted from MergeLeaves private static void FillKeysAndSeeks(BPNode<TValue> node, IList<string> keys, IList<long> seeks, ref int offset) { for (int i = 0; i < node._size && node._childKeys[i] != null; ++i) { keys[offset] = node._childKeys[i]; seeks[offset] = node._childBufferIds[i]; ++offset; } } public string DeleteLeaf(string key, out bool mergeMe) { mergeMe = false; bool found = false; int deletelocation = 0; foreach (string thiskey in _childKeys) { // use comparison, not equals, in case different strings sometimes compare same if (thiskey != null && _owner.Compare(thiskey, key) == 0) // thiskey.Equals(key) { found = true; break; } ++deletelocation; } if (!found) throw new BPTreeKeyMissing("cannot delete missing key: " + key); Soil(); // only keys are important... for (int i = deletelocation; i < _size - 1; ++i) { _childKeys[i] = _childKeys[i + 1]; _childBufferIds[i] = _childBufferIds[i + 1]; } _childKeys[_size - 1] = null; //this.MaterializedChildNodes[endlocation+1] = null; //this.ChildBufferIds[endlocation+1] = BPTreeLong.NULLBUFFERID; if (SizeInUse() < _size / 2) mergeMe = true; if (deletelocation != 0) return null; // this is only relevant for the case of 2-3 trees (empty leaf after deletion) return _childKeys[0] ?? key; } /// <summary> /// insert key/position entry in self /// </summary> /// <param name="key">Key to associate with the leaf</param> /// <param name="position">position associated with key in external structur</param> /// <param name="splitString">if not null then the smallest key in the new split leaf</param> /// <param name="splitNode">if not null then the node was split and this is the leaf to the right.</param> /// <returns>null unless the smallest key under this node has changed, in which case it returns the smallest key.</returns> public string Insert(string key, long position, out string splitString, out BPNode<TValue> splitNode) { splitString = null; splitNode = null; if (IsLeaf) return InsertLeaf(key, position, out splitString, out splitNode); int insertPosition = FindAtOrNextPosition(key, false); long insertBufferId = _childBufferIds[insertPosition]; if (insertBufferId == BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("key not followed by buffer number in non-leaf"); // insert in subtree var insertChild = MaterializeNodeAtIndex(insertPosition); BPNode<TValue> childSplit; string childSplitString; string childInsert = insertChild.Insert(key, position, out childSplitString, out childSplit); // if there was a split the node must expand if (childSplit != null) { // insert the child Soil(); // redundant -- a child will have a change so this node will need to be copied int newChildPosition = insertPosition + 1; bool dosplit = false; // if there is no free space we must do a split if (_childBufferIds[_size] != BPTreeBase<TValue>.NullBufferId) { dosplit = true; PrepareForSplit(); } // bubble over the current values to make space for new child for (int i = _childKeys.Length - 2; i >= newChildPosition - 1; i--) { int i1 = i + 1; int i2 = i1 + 1; _childKeys[i1] = _childKeys[i]; _childBufferIds[i2] = _childBufferIds[i1]; _materializedChildNodes[i2] = _materializedChildNodes[i1]; } // record the new child _childKeys[newChildPosition - 1] = childSplitString; childSplit.Reparent(this, newChildPosition); // split if needed if (dosplit) DoInsertionSplit(out splitString, out splitNode); // fix pointers in children ReParentAllChildren(); } // the smallest key may have changed if (insertPosition == 0) return childInsert; // no change in smallest key return null; } private void DoInsertionSplit(out string splitString, out BPNode<TValue> splitNode) { int splitpoint = _materializedChildNodes.Length / 2 - 1; splitString = _childKeys[splitpoint]; splitNode = new BPNode<TValue>(_owner, _parent, -1, IsLeaf); // make copy of expanded node structure var materialized = _materializedChildNodes; var bufferIds = _childBufferIds; var keys = _childKeys; // repair the expanded node _childKeys = new string[_size]; _materializedChildNodes = new BPNode<TValue>[_size + 1]; _childBufferIds = new long[_size + 1]; Clear(); Array.Copy(materialized, 0, _materializedChildNodes, 0, splitpoint + 1); Array.Copy(bufferIds, 0, _childBufferIds, 0, splitpoint + 1); Array.Copy(keys, 0, _childKeys, 0, splitpoint); // initialize the new node splitNode.Clear(); // redundant. int remainingKeys = _size - splitpoint; Array.Copy(materialized, splitpoint + 1, splitNode._materializedChildNodes, 0, remainingKeys + 1); Array.Copy(bufferIds, splitpoint + 1, splitNode._childBufferIds, 0, remainingKeys + 1); Array.Copy(keys, splitpoint + 1, splitNode._childKeys, 0, remainingKeys); // fix pointers in materialized children of splitnode splitNode.ReParentAllChildren(); // store the new node splitNode.DumpToFreshBuffer(); splitNode.CheckIfTerminal(); splitNode.Soil(); CheckIfTerminal(); } /// <summary> /// Check to see if this is a terminal node, if so record it, otherwise forget it /// </summary> private void CheckIfTerminal() { if (!IsLeaf) { for (int i = 0; i <= _size; ++i) { if (_materializedChildNodes[i] == null) continue; _owner.ForgetTerminalNode(this); return; } } _owner.RecordTerminalNode(this); } /// <summary> /// insert key/position entry in self (as leaf) /// </summary> /// <param name="key">Key to associate with the leaf</param> /// <param name="position">position associated with key in external structure</param> /// <param name="splitString">if not null then the smallest key in the new split leaf</param> /// <param name="splitNode">if not null then the node was split and this is the leaf to the right.</param> /// <returns>smallest key value in keys, or null if no change</returns> public string InsertLeaf(string key, long position, out string splitString, out BPNode<TValue> splitNode) { splitString = null; splitNode = null; bool doSplit = false; if (!IsLeaf) throw new BPTreeException("Bad call to InsertLeaf: this is not a leaf"); Soil(); int insertPosition = FindAtOrNextPosition(key, false); if (insertPosition >= _size) { doSplit = true; PrepareForSplit(); } // if it's already there then change the value at the current location (duplicate entries not supported). else if (_childKeys[insertPosition] == null || _owner.Compare(_childKeys[insertPosition], key) == 0) // this.ChildKeys[insertposition].Equals(key) { _childBufferIds[insertPosition] = position; _childKeys[insertPosition] = key; return insertPosition == 0 ? key : null; } // check for a null position int nullindex = insertPosition; while (nullindex < _childKeys.Length && _childKeys[nullindex] != null) { ++nullindex; } if (nullindex >= _childKeys.Length) { if (doSplit) throw new BPTreeException("Can't split twice"); //throw new BplusTreeException("no space in leaf"); doSplit = true; PrepareForSplit(); } // bubble in the new info XXXX THIS SHOULD BUBBLE BACKWARDS string nextkey = _childKeys[insertPosition]; long nextposition = _childBufferIds[insertPosition]; _childKeys[insertPosition] = key; _childBufferIds[insertPosition] = position; while (nextkey != null) { key = nextkey; position = nextposition; ++insertPosition; nextkey = _childKeys[insertPosition]; nextposition = _childBufferIds[insertPosition]; _childKeys[insertPosition] = key; _childBufferIds[insertPosition] = position; } // split if needed if (doSplit) DoLeafInsertionSplit(out splitString, out splitNode); if (insertPosition == 0) return key; // smallest key changed. return null; // no change in smallest key } // Extracted from InsertLeaf() private void DoLeafInsertionSplit(out string splitString, out BPNode<TValue> splitNode) { int splitpoint = _childKeys.Length / 2; int splitlength = _childKeys.Length - splitpoint; splitNode = new BPNode<TValue>(_owner, _parent, -1, IsLeaf); // copy the split info into the splitNode Array.Copy(_childBufferIds, splitpoint, splitNode._childBufferIds, 0, splitlength); Array.Copy(_childKeys, splitpoint, splitNode._childKeys, 0, splitlength); Array.Copy(_materializedChildNodes, splitpoint, splitNode._materializedChildNodes, 0, splitlength); splitString = splitNode._childKeys[0]; // archive the new node splitNode.DumpToFreshBuffer(); // store the node data temporarily var bufferIds = _childBufferIds; var keys = _childKeys; var nodes = _materializedChildNodes; // repair current node, copy in the other part of the split _childBufferIds = new long[_size + 1]; _childKeys = new string[_size]; _materializedChildNodes = new BPNode<TValue>[_size + 1]; Array.Copy(bufferIds, 0, _childBufferIds, 0, splitpoint); Array.Copy(keys, 0, _childKeys, 0, splitpoint); Array.Copy(nodes, 0, _materializedChildNodes, 0, splitpoint); for (int i = splitpoint; i < _childKeys.Length; ++i) { _childKeys[i] = null; _childBufferIds[i] = BPTreeBase<TValue>.NullBufferId; _materializedChildNodes[i] = null; } // store the new node _owner.RecordTerminalNode(splitNode); splitNode.Soil(); } /// <summary> /// Grow to this.size+1 in preparation for insertion and split /// </summary> private void PrepareForSplit() { int supersize = _size + 1; var positions = new long[supersize + 1]; var keys = new string[supersize]; var materialized = new BPNode<TValue>[supersize + 1]; Array.Copy(_childBufferIds, 0, positions, 0, _size + 1); positions[_size + 1] = BPTreeBase<TValue>.NullBufferId; Array.Copy(_childKeys, 0, keys, 0, _size); keys[_size] = null; Array.Copy(_materializedChildNodes, 0, materialized, 0, _size + 1); materialized[_size + 1] = null; _childBufferIds = positions; _childKeys = keys; _materializedChildNodes = materialized; } public void Load(byte[] buffer) { // load serialized data // indicator | seek position | [ key storage | seek position ]* Clear(); if (buffer.Length != _owner.BufferSize) throw new BPTreeException("bad buffer size " + buffer.Length + " should be " + _owner.BufferSize); byte indicator = buffer[0]; IsLeaf = false; if (indicator == Leaf) IsLeaf = true; else if (indicator != NonLeaf) throw new BPTreeException("bad indicator, not leaf or nonleaf in tree " + indicator); int index = 1; // get the first seek position _childBufferIds[0] = Bytes.ToInt64(buffer, index); var decode = Encoding.UTF8.GetDecoder(); index += Bytes.Long; int maxKeyLength = _owner.KeyLength; int maxKeyPayload = maxKeyLength - Bytes.Short; //this.NumberOfValidKids = 0; // get remaining key storages and seek positions string lastkey = ""; for (int keyIndex = 0; keyIndex < _size; ++keyIndex) { // decode and store a key short keylength = Bytes.ToInt16(buffer, index); if (keylength < -1 || keylength > maxKeyPayload) throw new BPTreeException("invalid keylength decoded"); index += Bytes.Short; string key = null; if (keylength == 0) key = ""; else if (keylength > 0) { int charCount = decode.GetCharCount(buffer, index, keylength); var ca = new char[charCount]; decode.GetChars(buffer, index, keylength, ca, 0); key = new string(ca); } _childKeys[keyIndex] = key; index += maxKeyPayload; // decode and store a seek position long seekPosition = Bytes.ToInt64(buffer, index); if (!IsLeaf) { if (key == null & seekPosition != BPTreeBase<TValue>.NullBufferId) throw new BPTreeException("key is null but position is not " + keyIndex); if (lastkey == null && key != null) throw new BPTreeException("null key followed by non-null key " + keyIndex); } lastkey = key; _childBufferIds[keyIndex + 1] = seekPosition; index += Bytes.Long; } } /// <summary> /// check that key is ok for node of this size (put here for locality of relevant code). /// </summary> /// <param name="key">key to check</param> /// <param name="owner">tree to contain node containing the key</param> /// <returns>true if key is ok</returns> public static bool KeyOk(string key, BPTreeBase<TValue> owner) { if (key == null) return false; var keyChars = key.ToCharArray(); int maxKeyPayload = owner.KeyLength - sizeof(short); var encoder = Encoding.UTF8.GetEncoder(); int charCount = encoder.GetByteCount(keyChars, 0, keyChars.Length, flush: true); return charCount <= maxKeyPayload; } public void Dump(byte[] buffer) { // indicator | seek position | [ key storage | seek position ]* if (buffer.Length != _owner.BufferSize) throw new BPTreeException("bad buffer size " + buffer.Length + " should be " + _owner.BufferSize); buffer[0] = NonLeaf; if (IsLeaf) buffer[0] = Leaf; int index = 1; // store first seek position Bytes.ToBuffer(_childBufferIds[0], buffer, index); index += Bytes.Long; var encode = Encoding.UTF8.GetEncoder(); // store remaining keys and seeks int maxKeyLength = _owner.KeyLength; int maxKeyPayload = maxKeyLength - Bytes.Short; string lastkey = ""; for (int keyIndex = 0; keyIndex < _size; ++keyIndex) { // store a key string theKey = _childKeys[keyIndex]; short charCount = -1; if (theKey != null) { var keyChars = theKey.ToCharArray(); charCount = (short) encode.GetByteCount(keyChars, 0, keyChars.Length, true); if (charCount > maxKeyPayload) throw new BPTreeException("string bytes to large for use as key " + charCount + ">" + maxKeyPayload); Bytes.ToBuffer(charCount, buffer, index); index += Bytes.Short; encode.GetBytes(keyChars, 0, keyChars.Length, buffer, index, true); } else { // null case (no string to read) Bytes.ToBuffer(charCount, buffer, index); index += Bytes.Short; } index += maxKeyPayload; // store a seek long seekPosition = _childBufferIds[keyIndex + 1]; if (theKey == null && seekPosition != BPTreeBase<TValue>.NullBufferId && !IsLeaf) throw new BPTreeException("null key paired with non-null location " + keyIndex); if (lastkey == null && theKey != null) throw new BPTreeException("null key followed by non-null key " + keyIndex); lastkey = theKey; Bytes.ToBuffer(seekPosition, buffer, index); index += Bytes.Long; } } /// <summary> /// Close the node: /// invalidate all children, store state if needed, remove materialized self from parent. /// </summary> public long Invalidate(bool destroyRoot) { long result = MyBufferId; if (!IsLeaf) { // need to invalidate kids for (int i = 0; i < _size + 1; ++i) { if (_materializedChildNodes[i] != null) // new buffer numbers are recorded automatically _childBufferIds[i] = _materializedChildNodes[i].Invalidate(true); } } // store if dirty if (_dirty) result = DumpToFreshBuffer(); // result = this.myBufferId; // remove from owner archives if present _owner.ForgetTerminalNode(this); // remove from parent if (_parent != null && _indexInParent >= 0) { _parent._materializedChildNodes[_indexInParent] = null; _parent._childBufferIds[_indexInParent] = result; // should be redundant _parent.CheckIfTerminal(); _indexInParent = -1; } // render all structures useless, just in case... if (destroyRoot) Destroy(); return result; } /// <summary> /// Mark this as dirty and all ancestors too. /// </summary> private void Soil() { if (_dirty) return; _dirty = true; if (_parent != null) _parent.Soil(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// CredentialResource /// </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; using Twilio.Types; namespace Twilio.Rest.Conversations.V1 { public class CredentialResource : Resource { public sealed class PushTypeEnum : StringEnum { private PushTypeEnum(string value) : base(value) {} public PushTypeEnum() {} public static implicit operator PushTypeEnum(string value) { return new PushTypeEnum(value); } public static readonly PushTypeEnum Apn = new PushTypeEnum("apn"); public static readonly PushTypeEnum Gcm = new PushTypeEnum("gcm"); public static readonly PushTypeEnum Fcm = new PushTypeEnum("fcm"); } private static Request BuildCreateRequest(CreateCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Conversations, "/v1/Credentials", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Add a new push notification credential to your account /// </summary> /// <param name="options"> Create Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Create(CreateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Add a new push notification credential to your account /// </summary> /// <param name="options"> Create Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> CreateAsync(CreateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Add a new push notification credential to your account /// </summary> /// <param name="type"> The type of push-notification service the credential is for. </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL encoded representation of the certificate. </param> /// <param name="privateKey"> [APN only] The URL encoded representation of the private key. </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs. </param> /// <param name="apiKey"> [GCM only] The API key for the project that was obtained from the Google Developer console /// for your GCM Service application credential. </param> /// <param name="secret"> [FCM only] The Server key of your project from Firebase console. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Create(CredentialResource.PushTypeEnum type, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new CreateCredentialOptions(type){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return Create(options, client); } #if !NET35 /// <summary> /// Add a new push notification credential to your account /// </summary> /// <param name="type"> The type of push-notification service the credential is for. </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL encoded representation of the certificate. </param> /// <param name="privateKey"> [APN only] The URL encoded representation of the private key. </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs. </param> /// <param name="apiKey"> [GCM only] The API key for the project that was obtained from the Google Developer console /// for your GCM Service application credential. </param> /// <param name="secret"> [FCM only] The Server key of your project from Firebase console. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> CreateAsync(CredentialResource.PushTypeEnum type, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new CreateCredentialOptions(type){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Conversations, "/v1/Credentials/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update an existing push notification credential on your account /// </summary> /// <param name="options"> Update Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Update(UpdateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update an existing push notification credential on your account /// </summary> /// <param name="options"> Update Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> UpdateAsync(UpdateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update an existing push notification credential on your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="type"> The type of push-notification service the credential is for. </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL encoded representation of the certificate. </param> /// <param name="privateKey"> [APN only] The URL encoded representation of the private key. </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs. </param> /// <param name="apiKey"> [GCM only] The API key for the project that was obtained from the Google Developer console /// for your GCM Service application credential. </param> /// <param name="secret"> [FCM only] The Server key of your project from Firebase console. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Update(string pathSid, CredentialResource.PushTypeEnum type = null, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new UpdateCredentialOptions(pathSid){Type = type, FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return Update(options, client); } #if !NET35 /// <summary> /// Update an existing push notification credential on your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="type"> The type of push-notification service the credential is for. </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL encoded representation of the certificate. </param> /// <param name="privateKey"> [APN only] The URL encoded representation of the private key. </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs. </param> /// <param name="apiKey"> [GCM only] The API key for the project that was obtained from the Google Developer console /// for your GCM Service application credential. </param> /// <param name="secret"> [FCM only] The Server key of your project from Firebase console. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> UpdateAsync(string pathSid, CredentialResource.PushTypeEnum type = null, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new UpdateCredentialOptions(pathSid){Type = type, FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Conversations, "/v1/Credentials/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Remove a push notification credential from your account /// </summary> /// <param name="options"> Delete Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static bool Delete(DeleteCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Remove a push notification credential from your account /// </summary> /// <param name="options"> Delete Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Remove a push notification credential from your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteCredentialOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Remove a push notification credential from your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteCredentialOptions(pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildFetchRequest(FetchCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Credentials/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a push notification credential from your account /// </summary> /// <param name="options"> Fetch Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Fetch(FetchCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a push notification credential from your account /// </summary> /// <param name="options"> Fetch Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> FetchAsync(FetchCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a push notification credential from your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchCredentialOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a push notification credential from your account /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchCredentialOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Credentials", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all push notification credentials on your account /// </summary> /// <param name="options"> Read Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static ResourceSet<CredentialResource> Read(ReadCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<CredentialResource>.FromJson("credentials", response.Content); return new ResourceSet<CredentialResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all push notification credentials on your account /// </summary> /// <param name="options"> Read Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<ResourceSet<CredentialResource>> ReadAsync(ReadCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<CredentialResource>.FromJson("credentials", response.Content); return new ResourceSet<CredentialResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all push notification credentials on your account /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static ResourceSet<CredentialResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCredentialOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all push notification credentials on your account /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<ResourceSet<CredentialResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCredentialOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<CredentialResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<CredentialResource> NextPage(Page<CredentialResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Conversations) ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<CredentialResource> PreviousPage(Page<CredentialResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Conversations) ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } /// <summary> /// Converts a JSON string into a CredentialResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CredentialResource object represented by the provided JSON </returns> public static CredentialResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CredentialResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The unique ID of the Account responsible for this credential. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The human-readable name of this credential. /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The type of push-notification service the credential is for. /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public CredentialResource.PushTypeEnum Type { get; private set; } /// <summary> /// [APN only] Whether to send the credential to sandbox APNs. /// </summary> [JsonProperty("sandbox")] public string Sandbox { get; private set; } /// <summary> /// The date that this resource was created. /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date that this resource was last updated. /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// An absolute URL for this credential. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private CredentialResource() { } } }
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// An immutable unordered hash set implementation. /// </summary> /// <typeparam name="T">The type of elements in the set.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] public sealed partial class ImmutableHashSet<T> : IImmutableSet<T>, IHashKeyCollection<T>, IReadOnlyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator> { /// <summary> /// An empty immutable hash set with the default comparer for <typeparamref name="T"/>. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0); /// <summary> /// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen. /// </summary> private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze(); /// <summary> /// The equality comparer used to hash the elements in the collection. /// </summary> private readonly IEqualityComparer<T> _equalityComparer; /// <summary> /// The number of elements in this collection. /// </summary> private readonly int _count; /// <summary> /// The sorted dictionary that this hash set wraps. The key is the hash code and the value is the bucket of all items that hashed to it. /// </summary> private readonly SortedInt32KeyNode<HashBucket> _root; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet{T}"/> class. /// </summary> /// <param name="equalityComparer">The equality comparer.</param> internal ImmutableHashSet(IEqualityComparer<T> equalityComparer) : this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0) { } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet{T}"/> class. /// </summary> /// <param name="root">The sorted set that this set wraps.</param> /// <param name="equalityComparer">The equality comparer used by this instance.</param> /// <param name="count">The number of elements in this collection.</param> private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, nameof(root)); Requires.NotNull(equalityComparer, nameof(equalityComparer)); root.Freeze(s_FreezeBucketAction); _root = root; _count = count; _equalityComparer = equalityComparer; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public ImmutableHashSet<T> Clear() { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty); return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(_equalityComparer); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public int Count { get { return _count; } } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool IsEmpty { get { return this.Count == 0; } } #region IHashKeyCollection<T> Properties /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public IEqualityComparer<T> KeyComparer { get { return _equalityComparer; } } #endregion #region IImmutableSet<T> Properties /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Clear() { return this.Clear(); } #endregion #region ICollection Properties /// <summary> /// See <see cref="ICollection"/>. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// See the <see cref="ICollection"/> interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal IBinaryTree Root { get { return _root; } } /// <summary> /// Gets a data structure that captures the current state of this map, as an input into a query or mutating function. /// </summary> private MutationInput Origin { get { return new MutationInput(this); } } #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Add(T item) { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Add(item, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public ImmutableHashSet<T> Remove(T item) { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Remove(item, this.Origin); return result.Finalize(this); } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> [Pure] public bool TryGetValue(T equalValue, out T actualValue) { int hashCode = _equalityComparer.GetHashCode(equalValue); HashBucket bucket; if (_root.TryGetValue(hashCode, out bucket)) { return bucket.TryExchange(equalValue, _equalityComparer, out actualValue); } actualValue = equalValue; return false; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); return this.Union(other, avoidWithComparer: false); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Intersect(other, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public ImmutableHashSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var result = Except(other, _equalityComparer, _root); return result.Finalize(this); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [Pure] public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null); var result = SymmetricExcept(other, this.Origin); return result.Finalize(this); } /// <summary> /// Checks whether a given sequence of items entirely describe the contents of this set. /// </summary> /// <param name="other">The sequence of items to check against this set.</param> /// <returns>A value indicating whether the sets are equal.</returns> [Pure] public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (object.ReferenceEquals(this, other)) { return true; } return SetEquals(other, this.Origin); } /// <summary> /// Determines whether the current set is a property (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of <paramref name="other"/>; otherwise, false.</returns> [Pure] public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); return IsProperSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a correct superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct superset of <paramref name="other"/>; otherwise, false.</returns> [Pure] public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); return IsProperSupersetOf(other, this.Origin); } /// <summary> /// Determines whether a set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of <paramref name="other"/>; otherwise, false.</returns> [Pure] public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); return IsSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of <paramref name="other"/>; otherwise, false.</returns> [Pure] public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); return IsSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and <paramref name="other"/> share at least one common element; otherwise, false.</returns> [Pure] public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); return Overlaps(other, this.Origin); } #endregion #region IImmutableSet<T> Methods /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Add(T item) { return this.Add(item); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Remove(T item) { return this.Remove(item); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return this.Union(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return this.Intersect(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return this.Except(other); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return this.SymmetricExcept(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool Contains(T item) { return Contains(item, this.Origin); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer) { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == _equalityComparer) { return this; } else { var result = new ImmutableHashSet<T>(equalityComparer); result = result.Union(this, avoidWithComparer: true); return result; } } #endregion #region ISet<T> Members /// <summary> /// See <see cref="ISet{T}"/> /// </summary> bool ISet<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } #endregion #region ICollection<T> members /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void ICollection<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.Clear() { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (T item in this) { array.SetValue(item, arrayIndex++); } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Static query and manipulator methods /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!Contains(item, origin)) { return false; } } return true; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Add(T item, MutationInput origin) { OperationResult result; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = origin.Root.GetValueOrDefault(hashCode); var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } var newRoot = UpdateRoot(origin.Root, hashCode, newBucket); Debug.Assert(result == OperationResult.SizeChanged); return new MutationResult(newRoot, 1 /*result == OperationResult.SizeChanged ? 1 : 0*/); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Remove(T item, MutationInput origin) { var result = OperationResult.NoChangeRequired; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; var newRoot = origin.Root; if (origin.Root.TryGetValue(hashCode, out bucket)) { var newBucket = bucket.Remove(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } newRoot = UpdateRoot(origin.Root, hashCode, newBucket); } return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Contains(T item, MutationInput origin) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.Contains(item, origin.EqualityComparer); } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Union(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); int count = 0; var newRoot = origin.Root; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = newRoot.GetValueOrDefault(hashCode); OperationResult result; var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { newRoot = UpdateRoot(newRoot, hashCode, newBucket); count++; } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Overlaps(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); if (origin.Root.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool SetEquals(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count != otherSet.Count) { return false; } int matches = 0; foreach (T item in otherSet) { if (!Contains(item, origin)) { return false; } matches++; } return matches == origin.Count; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } else { bool replacedExistingValue; return root.SetItem(hashCode, newBucket, EqualityComparer<HashBucket>.Default, out replacedExistingValue, out mutated); } } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); var newSet = SortedInt32KeyNode<HashBucket>.EmptyNode; int count = 0; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { var result = Add(item, new MutationInput(newSet, origin.EqualityComparer, count)); newSet = result.Root; count += result.Count; } } return new MutationResult(newSet, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(other, nameof(other)); Requires.NotNull(equalityComparer, nameof(equalityComparer)); Requires.NotNull(root, nameof(root)); int count = 0; var newRoot = root; foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { int hashCode = equalityComparer.GetHashCode(item); HashBucket bucket; if (newRoot.TryGetValue(hashCode, out bucket)) { OperationResult result; HashBucket newBucket = bucket.Remove(item, equalityComparer, out result); if (result == OperationResult.SizeChanged) { count--; newRoot = UpdateRoot(newRoot, hashCode, newBucket); } } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> [Pure] private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); var otherAsSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other); int count = 0; var result = SortedInt32KeyNode<HashBucket>.EmptyNode; foreach (T item in new NodeEnumerable(origin.Root)) { if (!otherAsSet.Contains(item)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } foreach (T item in otherAsSet) { if (!Contains(item, origin)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } return new MutationResult(result, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); if (origin.Root.IsEmpty) { return other.Any(); } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count >= otherSet.Count) { return false; } int matches = 0; bool extraFound = false; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } else { extraFound = true; } if (matches == origin.Count && extraFound) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); if (origin.Root.IsEmpty) { return false; } int matchCount = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { matchCount++; if (!Contains(item, origin)) { return false; } } return origin.Count > matchCount; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, nameof(other)); if (origin.Root.IsEmpty) { return true; } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); int matches = 0; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } } return matches == origin.Count; } #endregion /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="equalityComparer">The equality comparer.</param> /// <param name="count">The number of elements in the data structure.</param> /// <returns>The immutable collection.</returns> private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, nameof(root)); Requires.NotNull(equalityComparer, nameof(equalityComparer)); Requires.Range(count >= 0, nameof(count)); return new ImmutableHashSet<T>(root, equalityComparer, count); } /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param> /// <returns>The immutable collection.</returns> private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { return (root != _root) ? new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot) : this; } /// <summary> /// Bulk adds entries to the set. /// </summary> /// <param name="items">The entries to add.</param> /// <param name="avoidWithComparer"><c>true</c> when being called from <see cref="WithComparer"/> to avoid <see cref="T:System.StackOverflowException"/>.</param> [Pure] private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer) { Requires.NotNull(items, nameof(items)); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); // Some optimizations may apply if we're an empty set. if (this.IsEmpty && !avoidWithComparer) { // If the items being added actually come from an ImmutableHashSet<T>, // reuse that instance if possible. var other = items as ImmutableHashSet<T>; if (other != null) { return other.WithComparer(this.KeyComparer); } } var result = Union(items, this.Origin); return result.Finalize(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.ApplicationModels { internal class DefaultApplicationModelProvider : IApplicationModelProvider { private readonly MvcOptions _mvcOptions; private readonly IModelMetadataProvider _modelMetadataProvider; private readonly Func<ActionContext, bool> _supportsAllRequests; private readonly Func<ActionContext, bool> _supportsNonGetRequests; public DefaultApplicationModelProvider( IOptions<MvcOptions> mvcOptionsAccessor, IModelMetadataProvider modelMetadataProvider) { _mvcOptions = mvcOptionsAccessor.Value; _modelMetadataProvider = modelMetadataProvider; _supportsAllRequests = _ => true; _supportsNonGetRequests = context => !HttpMethods.IsGet(context.HttpContext.Request.Method); } /// <inheritdoc /> public int Order => -1000; /// <inheritdoc /> public void OnProvidersExecuting(ApplicationModelProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } foreach (var filter in _mvcOptions.Filters) { context.Result.Filters.Add(filter); } foreach (var controllerType in context.ControllerTypes) { var controllerModel = CreateControllerModel(controllerType); if (controllerModel == null) { continue; } context.Result.Controllers.Add(controllerModel); controllerModel.Application = context.Result; foreach (var propertyHelper in PropertyHelper.GetProperties(controllerType.AsType())) { var propertyInfo = propertyHelper.Property; var propertyModel = CreatePropertyModel(propertyInfo); if (propertyModel != null) { propertyModel.Controller = controllerModel; controllerModel.ControllerProperties.Add(propertyModel); } } foreach (var methodInfo in controllerType.AsType().GetMethods()) { var actionModel = CreateActionModel(controllerType, methodInfo); if (actionModel == null) { continue; } actionModel.Controller = controllerModel; controllerModel.Actions.Add(actionModel); foreach (var parameterInfo in actionModel.ActionMethod.GetParameters()) { var parameterModel = CreateParameterModel(parameterInfo); if (parameterModel != null) { parameterModel.Action = actionModel; actionModel.Parameters.Add(parameterModel); } } } } } /// <inheritdoc /> public void OnProvidersExecuted(ApplicationModelProviderContext context) { // Intentionally empty. } /// <summary> /// Creates a <see cref="ControllerModel"/> for the given <see cref="TypeInfo"/>. /// </summary> /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param> /// <returns>A <see cref="ControllerModel"/> for the given <see cref="TypeInfo"/>.</returns> internal ControllerModel CreateControllerModel(TypeInfo typeInfo) { if (typeInfo == null) { throw new ArgumentNullException(nameof(typeInfo)); } // For attribute routes on a controller, we want to support 'overriding' routes on a derived // class. So we need to walk up the hierarchy looking for the first class to define routes. // // Then we want to 'filter' the set of attributes, so that only the effective routes apply. var currentTypeInfo = typeInfo; var objectTypeInfo = typeof(object).GetTypeInfo(); IRouteTemplateProvider[] routeAttributes; do { routeAttributes = currentTypeInfo .GetCustomAttributes(inherit: false) .OfType<IRouteTemplateProvider>() .ToArray(); if (routeAttributes.Length > 0) { // Found 1 or more route attributes. break; } currentTypeInfo = currentTypeInfo.BaseType!.GetTypeInfo(); } while (currentTypeInfo != objectTypeInfo); var attributes = typeInfo.GetCustomAttributes(inherit: true); // This is fairly complicated so that we maintain referential equality between items in // ControllerModel.Attributes and ControllerModel.Attributes[*].Attribute. var filteredAttributes = new List<object>(); foreach (var attribute in attributes) { if (attribute is IRouteTemplateProvider) { // This attribute is a route-attribute, leave it out. } else { filteredAttributes.Add(attribute); } } filteredAttributes.AddRange(routeAttributes); attributes = filteredAttributes.ToArray(); var controllerModel = new ControllerModel(typeInfo, attributes); AddRange(controllerModel.Selectors, CreateSelectors(attributes)); controllerModel.ControllerName = typeInfo.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) ? typeInfo.Name.Substring(0, typeInfo.Name.Length - "Controller".Length) : typeInfo.Name; AddRange(controllerModel.Filters, attributes.OfType<IFilterMetadata>()); foreach (var routeValueProvider in attributes.OfType<IRouteValueProvider>()) { controllerModel.RouteValues.Add(routeValueProvider.RouteKey, routeValueProvider.RouteValue); } var apiVisibility = attributes.OfType<IApiDescriptionVisibilityProvider>().FirstOrDefault(); if (apiVisibility != null) { controllerModel.ApiExplorer.IsVisible = !apiVisibility.IgnoreApi; } var apiGroupName = attributes.OfType<IApiDescriptionGroupNameProvider>().FirstOrDefault(); if (apiGroupName != null) { controllerModel.ApiExplorer.GroupName = apiGroupName.GroupName; } // Controllers can implement action filter and result filter interfaces. We add // a special delegating filter implementation to the pipeline to handle it. // // This is needed because filters are instantiated before the controller. if (typeof(IAsyncActionFilter).GetTypeInfo().IsAssignableFrom(typeInfo) || typeof(IActionFilter).GetTypeInfo().IsAssignableFrom(typeInfo)) { controllerModel.Filters.Add(new ControllerActionFilter()); } if (typeof(IAsyncResultFilter).GetTypeInfo().IsAssignableFrom(typeInfo) || typeof(IResultFilter).GetTypeInfo().IsAssignableFrom(typeInfo)) { controllerModel.Filters.Add(new ControllerResultFilter()); } return controllerModel; } /// <summary> /// Creates a <see cref="PropertyModel"/> for the given <see cref="PropertyInfo"/>. /// </summary> /// <param name="propertyInfo">The <see cref="PropertyInfo"/>.</param> /// <returns>A <see cref="PropertyModel"/> for the given <see cref="PropertyInfo"/>.</returns> internal PropertyModel CreatePropertyModel(PropertyInfo propertyInfo) { if (propertyInfo == null) { throw new ArgumentNullException(nameof(propertyInfo)); } var attributes = propertyInfo.GetCustomAttributes(inherit: true); // BindingInfo for properties can be either specified by decorating the property with binding specific attributes. // ModelMetadata also adds information from the property's type and any configured IBindingMetadataProvider. var declaringType = propertyInfo.DeclaringType!; var modelMetadata = _modelMetadataProvider.GetMetadataForProperty(declaringType, propertyInfo.Name); var bindingInfo = BindingInfo.GetBindingInfo(attributes, modelMetadata); if (bindingInfo == null) { // Look for BindPropertiesAttribute on the handler type if no BindingInfo was inferred for the property. // This allows a user to enable model binding on properties by decorating the controller type with BindPropertiesAttribute. var bindPropertiesAttribute = declaringType.GetCustomAttribute<BindPropertiesAttribute>(inherit: true); if (bindPropertiesAttribute != null) { var requestPredicate = bindPropertiesAttribute.SupportsGet ? _supportsAllRequests : _supportsNonGetRequests; bindingInfo = new BindingInfo { RequestPredicate = requestPredicate, }; } } var propertyModel = new PropertyModel(propertyInfo, attributes) { PropertyName = propertyInfo.Name, BindingInfo = bindingInfo, }; return propertyModel; } /// <summary> /// Creates the <see cref="ActionModel"/> instance for the given action <see cref="MethodInfo"/>. /// </summary> /// <param name="typeInfo">The controller <see cref="TypeInfo"/>.</param> /// <param name="methodInfo">The action <see cref="MethodInfo"/>.</param> /// <returns> /// An <see cref="ActionModel"/> instance for the given action <see cref="MethodInfo"/> or /// <c>null</c> if the <paramref name="methodInfo"/> does not represent an action. /// </returns> internal ActionModel? CreateActionModel( TypeInfo typeInfo, MethodInfo methodInfo) { if (typeInfo == null) { throw new ArgumentNullException(nameof(typeInfo)); } if (methodInfo == null) { throw new ArgumentNullException(nameof(methodInfo)); } if (!IsAction(typeInfo, methodInfo)) { return null; } var attributes = methodInfo.GetCustomAttributes(inherit: true); var actionModel = new ActionModel(methodInfo, attributes); AddRange(actionModel.Filters, attributes.OfType<IFilterMetadata>()); var actionName = attributes.OfType<ActionNameAttribute>().FirstOrDefault(); if (actionName?.Name != null) { actionModel.ActionName = actionName.Name; } else { actionModel.ActionName = CanonicalizeActionName(methodInfo.Name); } var apiVisibility = attributes.OfType<IApiDescriptionVisibilityProvider>().FirstOrDefault(); if (apiVisibility != null) { actionModel.ApiExplorer.IsVisible = !apiVisibility.IgnoreApi; } var apiGroupName = attributes.OfType<IApiDescriptionGroupNameProvider>().FirstOrDefault(); if (apiGroupName != null) { actionModel.ApiExplorer.GroupName = apiGroupName.GroupName; } foreach (var routeValueProvider in attributes.OfType<IRouteValueProvider>()) { actionModel.RouteValues.Add(routeValueProvider.RouteKey, routeValueProvider.RouteValue); } // Now we need to determine the action selection info (cross-section of routes and constraints) // // For attribute routes on a action, we want to support 'overriding' routes on a // virtual method, but allow 'overriding'. So we need to walk up the hierarchy looking // for the first definition to define routes. // // Then we want to 'filter' the set of attributes, so that only the effective routes apply. var currentMethodInfo = methodInfo; IRouteTemplateProvider[] routeAttributes; while (true) { routeAttributes = currentMethodInfo .GetCustomAttributes(inherit: false) .OfType<IRouteTemplateProvider>() .ToArray(); if (routeAttributes.Length > 0) { // Found 1 or more route attributes. break; } // GetBaseDefinition returns 'this' when it gets to the bottom of the chain. var nextMethodInfo = currentMethodInfo.GetBaseDefinition(); if (currentMethodInfo == nextMethodInfo) { break; } currentMethodInfo = nextMethodInfo; } // This is fairly complicated so that we maintain referential equality between items in // ActionModel.Attributes and ActionModel.Attributes[*].Attribute. var applicableAttributes = new List<object>(routeAttributes.Length); foreach (var attribute in attributes) { if (attribute is IRouteTemplateProvider) { // This attribute is a route-attribute, leave it out. } else { applicableAttributes.Add(attribute); } } applicableAttributes.AddRange(routeAttributes); AddRange(actionModel.Selectors, CreateSelectors(applicableAttributes)); return actionModel; } private string CanonicalizeActionName(string actionName) { const string Suffix = "Async"; if (_mvcOptions.SuppressAsyncSuffixInActionNames && actionName.EndsWith(Suffix, StringComparison.Ordinal)) { actionName = actionName.Substring(0, actionName.Length - Suffix.Length); } return actionName; } /// <summary> /// Returns <c>true</c> if the <paramref name="methodInfo"/> is an action. Otherwise <c>false</c>. /// </summary> /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param> /// <param name="methodInfo">The <see cref="MethodInfo"/>.</param> /// <returns><c>true</c> if the <paramref name="methodInfo"/> is an action. Otherwise <c>false</c>.</returns> /// <remarks> /// Override this method to provide custom logic to determine which methods are considered actions. /// </remarks> internal bool IsAction(TypeInfo typeInfo, MethodInfo methodInfo) { if (typeInfo == null) { throw new ArgumentNullException(nameof(typeInfo)); } if (methodInfo == null) { throw new ArgumentNullException(nameof(methodInfo)); } // The SpecialName bit is set to flag members that are treated in a special way by some compilers // (such as property accessors and operator overloading methods). if (methodInfo.IsSpecialName) { return false; } if (methodInfo.IsDefined(typeof(NonActionAttribute))) { return false; } // Overridden methods from Object class, e.g. Equals(Object), GetHashCode(), etc., are not valid. if (methodInfo.GetBaseDefinition().DeclaringType == typeof(object)) { return false; } // Dispose method implemented from IDisposable is not valid if (IsIDisposableMethod(methodInfo)) { return false; } if (methodInfo.IsStatic) { return false; } if (methodInfo.IsAbstract) { return false; } if (methodInfo.IsConstructor) { return false; } if (methodInfo.IsGenericMethod) { return false; } return methodInfo.IsPublic; } /// <summary> /// Creates a <see cref="ParameterModel"/> for the given <see cref="ParameterInfo"/>. /// </summary> /// <param name="parameterInfo">The <see cref="ParameterInfo"/>.</param> /// <returns>A <see cref="ParameterModel"/> for the given <see cref="ParameterInfo"/>.</returns> internal ParameterModel CreateParameterModel(ParameterInfo parameterInfo) { if (parameterInfo == null) { throw new ArgumentNullException(nameof(parameterInfo)); } var attributes = parameterInfo.GetCustomAttributes(inherit: true); BindingInfo? bindingInfo; if (_modelMetadataProvider is ModelMetadataProvider modelMetadataProviderBase) { var modelMetadata = modelMetadataProviderBase.GetMetadataForParameter(parameterInfo); bindingInfo = BindingInfo.GetBindingInfo(attributes, modelMetadata); } else { // GetMetadataForParameter should only be used if the user has opted in to the 2.1 behavior. bindingInfo = BindingInfo.GetBindingInfo(attributes); } var parameterModel = new ParameterModel(parameterInfo, attributes) { ParameterName = parameterInfo.Name!, BindingInfo = bindingInfo, }; return parameterModel; } private IList<SelectorModel> CreateSelectors(IList<object> attributes) { // Route attributes create multiple selector models, we want to split the set of // attributes based on these so each selector only has the attributes that affect it. // // The set of route attributes are split into those that 'define' a route versus those that are // 'silent'. // // We need to define a selector for each attribute that 'defines' a route, and a single selector // for all of the ones that don't (if any exist). // // If the attribute that 'defines' a route is NOT an IActionHttpMethodProvider, then we'll include with // it, any IActionHttpMethodProvider that are 'silent' IRouteTemplateProviders. In this case the 'extra' // action for silent route providers isn't needed. // // Ex: // [HttpGet] // [AcceptVerbs("POST", "PUT")] // [HttpPost("Api/Things")] // public void DoThing() // // This will generate 2 selectors: // 1. [HttpPost("Api/Things")] // 2. [HttpGet], [AcceptVerbs("POST", "PUT")] // // Another example of this situation is: // // [Route("api/Products")] // [AcceptVerbs("GET", "HEAD")] // [HttpPost("api/Products/new")] // // This will generate 2 selectors: // 1. [AcceptVerbs("GET", "HEAD")] // 2. [HttpPost] // // Note that having a route attribute that doesn't define a route template _might_ be an error. We // don't have enough context to really know at this point so we just pass it on. var routeProviders = new List<IRouteTemplateProvider>(); var createSelectorForSilentRouteProviders = false; foreach (var attribute in attributes) { if (attribute is IRouteTemplateProvider routeTemplateProvider) { if (IsSilentRouteAttribute(routeTemplateProvider)) { createSelectorForSilentRouteProviders = true; } else { routeProviders.Add(routeTemplateProvider); } } } foreach (var routeProvider in routeProviders) { // If we see an attribute like // [Route(...)] // // Then we want to group any attributes like [HttpGet] with it. // // Basically... // // [HttpGet] // [HttpPost("Products")] // public void Foo() { } // // Is two selectors. And... // // [HttpGet] // [Route("Products")] // public void Foo() { } // // Is one selector. if (!(routeProvider is IActionHttpMethodProvider)) { createSelectorForSilentRouteProviders = false; break; } } var selectorModels = new List<SelectorModel>(); if (routeProviders.Count == 0 && !createSelectorForSilentRouteProviders) { // Simple case, all attributes apply selectorModels.Add(CreateSelectorModel(route: null, attributes: attributes)); } else { // Each of these routeProviders are the ones that actually have routing information on them // something like [HttpGet] won't show up here, but [HttpGet("Products")] will. foreach (var routeProvider in routeProviders) { var filteredAttributes = new List<object>(); foreach (var attribute in attributes) { if (ReferenceEquals(attribute, routeProvider)) { filteredAttributes.Add(attribute); } else if (InRouteProviders(routeProviders, attribute)) { // Exclude other route template providers // Example: // [HttpGet("template")] // [Route("template/{id}")] } else if ( routeProvider is IActionHttpMethodProvider && attribute is IActionHttpMethodProvider) { // Example: // [HttpGet("template")] // [AcceptVerbs("GET", "POST")] // // Exclude other http method providers if this route is an // http method provider. } else { filteredAttributes.Add(attribute); } } selectorModels.Add(CreateSelectorModel(routeProvider, filteredAttributes)); } if (createSelectorForSilentRouteProviders) { var filteredAttributes = new List<object>(); foreach (var attribute in attributes) { if (!InRouteProviders(routeProviders, attribute)) { filteredAttributes.Add(attribute); } } selectorModels.Add(CreateSelectorModel(route: null, attributes: filteredAttributes)); } } return selectorModels; } private static bool InRouteProviders(List<IRouteTemplateProvider> routeProviders, object attribute) { foreach (var rp in routeProviders) { if (ReferenceEquals(rp, attribute)) { return true; } } return false; } private static SelectorModel CreateSelectorModel(IRouteTemplateProvider? route, IList<object> attributes) { var selectorModel = new SelectorModel(); if (route != null) { selectorModel.AttributeRouteModel = new AttributeRouteModel(route); } AddRange(selectorModel.ActionConstraints, attributes.OfType<IActionConstraintMetadata>()); AddRange(selectorModel.EndpointMetadata, attributes); // Simple case, all HTTP method attributes apply var httpMethods = attributes .OfType<IActionHttpMethodProvider>() .SelectMany(a => a.HttpMethods) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); if (httpMethods.Length > 0) { selectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(httpMethods)); selectorModel.EndpointMetadata.Add(new HttpMethodMetadata(httpMethods)); } return selectorModel; } private bool IsIDisposableMethod(MethodInfo methodInfo) { // Ideally we do not want Dispose method to be exposed as an action. However there are some scenarios where a user // might want to expose a method with name "Dispose" (even though they might not be really disposing resources) // Example: A controller deriving from MVC's Controller type might wish to have a method with name Dispose, // in which case they can use the "new" keyword to hide the base controller's declaration. // Find where the method was originally declared var baseMethodInfo = methodInfo.GetBaseDefinition(); var declaringType = baseMethodInfo.DeclaringType; return (typeof(IDisposable).IsAssignableFrom(declaringType) && declaringType.GetInterfaceMap(typeof(IDisposable)).TargetMethods[0] == baseMethodInfo); } private bool IsSilentRouteAttribute(IRouteTemplateProvider routeTemplateProvider) { return routeTemplateProvider.Template == null && routeTemplateProvider.Order == null && routeTemplateProvider.Name == null; } private static void AddRange<T>(IList<T> list, IEnumerable<T> items) { foreach (var item in items) { list.Add(item); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Pointer Type to a EEType in the runtime. ** ** ===========================================================*/ using System; using System.Runtime; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { [StructLayout(LayoutKind.Sequential)] internal struct EETypePtr : IEquatable<EETypePtr> { private IntPtr _value; public EETypePtr(IntPtr value) { _value = value; } #if INPLACE_RUNTIME internal unsafe System.Runtime.EEType* ToPointer() { return (System.Runtime.EEType*)(void*)_value; } #endif public override bool Equals(Object obj) { if (obj is EETypePtr) { return this == (EETypePtr)obj; } return false; } public bool Equals(EETypePtr p) { return this == p; } public static bool operator ==(EETypePtr value1, EETypePtr value2) { if (value1.IsNull) return value2.IsNull; else if (value2.IsNull) return false; else return RuntimeImports.AreTypesEquivalent(value1, value2); } public static bool operator !=(EETypePtr value1, EETypePtr value2) { return !(value1 == value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return (int)Runtime.RuntimeImports.RhGetEETypeHash(this); } // // Faster version of Equals for use on EETypes that are known not to be null and where the "match" case is the hot path. // public bool FastEquals(EETypePtr other) { Debug.Assert(!this.IsNull); Debug.Assert(!other.IsNull); // Fast check for raw equality before making call to helper. if (this.RawValue == other.RawValue) return true; return RuntimeImports.AreTypesEquivalent(this, other); } // Caution: You cannot safely compare RawValue's as RH does NOT unify EETypes. Use the == or Equals() methods exposed by EETypePtr itself. internal IntPtr RawValue { get { return _value; } } internal bool IsNull { get { return _value == default(IntPtr); } } internal bool IsArray { get { return RuntimeImports.RhIsArray(this); } } internal bool IsSzArray { get { return IsArray && BaseSize == Array.SZARRAY_BASE_SIZE; } } internal bool IsPointer { get { RuntimeImports.RhEETypeClassification classification = RuntimeImports.RhGetEETypeClassification(_value); return classification == RuntimeImports.RhEETypeClassification.UnmanagedPointer; } } internal bool IsValueType { get { return RuntimeImports.RhIsValueType(this); } } internal bool IsString { get { return RuntimeImports.RhIsString(this); } } internal bool IsPrimitive { get { RuntimeImports.RhCorElementType et = CorElementType; return ((et >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN) && (et <= RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_I) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_U); } } internal bool IsEnum { get { RuntimeImports.RhEETypeClassification classification = RuntimeImports.RhGetEETypeClassification(this); // Q: When is an enum type a constructed generic type? // A: When it's nested inside a generic type. if (!(classification == RuntimeImports.RhEETypeClassification.Regular || classification == RuntimeImports.RhEETypeClassification.Generic)) return false; EETypePtr baseType = this.BaseType; return baseType == EETypePtr.EETypePtrOf<Enum>(); } } internal EETypePtr ArrayElementType { get { return RuntimeImports.RhGetRelatedParameterType(this); } } internal EETypePtr BaseType { get { if (IsArray) return EETypePtr.EETypePtrOf<Array>(); if (IsPointer) return new EETypePtr(default(IntPtr)); EETypePtr baseEEType = RuntimeImports.RhGetNonArrayBaseType(this); #if !REAL_MULTIDIM_ARRAYS if (baseEEType == EETypePtr.EETypePtrOf<MDArrayRank2>() || baseEEType == EETypePtr.EETypePtrOf<MDArrayRank3>() || baseEEType == EETypePtr.EETypePtrOf<MDArrayRank4>()) { return EETypePtr.EETypePtrOf<Array>(); } #endif return baseEEType; } } internal ushort ComponentSize { get { return RuntimeImports.RhGetComponentSize(this); } } internal uint BaseSize { get { return RuntimeImports.RhGetBaseSize(this); } } // Has internal gc pointers. internal bool HasPointers { get { return RuntimeImports.RhHasReferenceFields(this); } } internal uint ValueTypeSize { get { Debug.Assert(IsValueType, "ValueTypeSize should only be used on value types"); return RuntimeImports.RhGetValueTypeSize(this); } } internal RuntimeImports.RhCorElementType CorElementType { get { return RuntimeImports.RhGetCorElementType(this); } } internal RuntimeImports.RhCorElementTypeInfo CorElementTypeInfo { get { RuntimeImports.RhCorElementType corElementType = this.CorElementType; return RuntimeImports.GetRhCorElementTypeInfo(corElementType); } } #if CORERT [Intrinsic] #endif internal static EETypePtr EETypePtrOf<T>() { // Compilers are required to provide a low level implementation of this method. // This can be achieved by optimizing away the reflection part of this implementation // by optimizing typeof(!!0).TypeHandle into "ldtoken !!0", or by // completely replacing the body of this method. return typeof(T).TypeHandle.ToEETypePtr(); } } }
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { internal class SampleConsumerObserver<T> : IAsyncObserver<T> { private readonly SampleStreaming_ConsumerGrain hostingGrain; internal SampleConsumerObserver(SampleStreaming_ConsumerGrain hostingGrain) { this.hostingGrain = hostingGrain; } public Task OnNextAsync(T item, StreamSequenceToken token = null) { hostingGrain.logger.Info("OnNextAsync(item={0}, token={1})", item, token != null ? token.ToString() : "null"); hostingGrain.numConsumedItems++; return TaskDone.Done; } public Task OnCompletedAsync() { hostingGrain.logger.Info("OnCompletedAsync()"); return TaskDone.Done; } public Task OnErrorAsync(Exception ex) { hostingGrain.logger.Info("OnErrorAsync({0})", ex); return TaskDone.Done; } } public class SampleStreaming_ProducerGrain : Grain, ISampleStreaming_ProducerGrain { private IAsyncStream<int> producer; private int numProducedItems; private IDisposable producerTimer; internal Logger logger; internal readonly static string RequestContextKey = "RequestContextField"; internal readonly static string RequestContextValue = "JustAString"; public override Task OnActivateAsync() { logger = base.GetLogger("SampleStreaming_ProducerGrain " + base.IdentityString); logger.Info("OnActivateAsync"); numProducedItems = 0; return TaskDone.Done; } public Task BecomeProducer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info("BecomeProducer"); IStreamProvider streamProvider = base.GetStreamProvider(providerToUse); producer = streamProvider.GetStream<int>(streamId, streamNamespace); return TaskDone.Done; } public Task StartPeriodicProducing() { logger.Info("StartPeriodicProducing"); producerTimer = base.RegisterTimer(TimerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); return TaskDone.Done; } public Task StopPeriodicProducing() { logger.Info("StopPeriodicProducing"); producerTimer.Dispose(); producerTimer = null; return TaskDone.Done; } public Task<int> GetNumberProduced() { logger.Info("GetNumberProduced {0}", numProducedItems); return Task.FromResult(numProducedItems); } public Task ClearNumberProduced() { numProducedItems = 0; return TaskDone.Done; } public Task Produce() { return Fire(); } private Task TimerCallback(object state) { return producerTimer != null? Fire(): TaskDone.Done; } private async Task Fire([CallerMemberName] string caller = null) { RequestContext.Set(RequestContextKey, RequestContextValue); await producer.OnNextAsync(numProducedItems); numProducedItems++; logger.Info("{0} (item={1})", caller, numProducedItems); } public override Task OnDeactivateAsync() { logger.Info("OnDeactivateAsync"); return TaskDone.Done; } } public class SampleStreaming_ConsumerGrain : Grain, ISampleStreaming_ConsumerGrain { private IAsyncObservable<int> consumer; internal int numConsumedItems; internal Logger logger; private IAsyncObserver<int> consumerObserver; private StreamSubscriptionHandle<int> consumerHandle; public override Task OnActivateAsync() { logger = base.GetLogger("SampleStreaming_ConsumerGrain " + base.IdentityString); logger.Info("OnActivateAsync"); numConsumedItems = 0; consumerHandle = null; return TaskDone.Done; } public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info("BecomeConsumer"); consumerObserver = new SampleConsumerObserver<int>(this); IStreamProvider streamProvider = base.GetStreamProvider(providerToUse); consumer = streamProvider.GetStream<int>(streamId, streamNamespace); consumerHandle = await consumer.SubscribeAsync(consumerObserver); } public async Task StopConsuming() { logger.Info("StopConsuming"); if (consumerHandle != null) { await consumerHandle.UnsubscribeAsync(); consumerHandle = null; } } public Task<int> GetNumberConsumed() { return Task.FromResult(numConsumedItems); } public override Task OnDeactivateAsync() { logger.Info("OnDeactivateAsync"); return TaskDone.Done; } } public class SampleStreaming_InlineConsumerGrain : Grain, ISampleStreaming_InlineConsumerGrain { private IAsyncObservable<int> consumer; internal int numConsumedItems; internal Logger logger; private StreamSubscriptionHandle<int> consumerHandle; public override Task OnActivateAsync() { logger = base.GetLogger( "SampleStreaming_InlineConsumerGrain " + base.IdentityString ); logger.Info( "OnActivateAsync" ); numConsumedItems = 0; consumerHandle = null; return TaskDone.Done; } public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse) { logger.Info( "BecomeConsumer" ); IStreamProvider streamProvider = base.GetStreamProvider( providerToUse ); consumer = streamProvider.GetStream<int>(streamId, streamNamespace); consumerHandle = await consumer.SubscribeAsync( OnNextAsync, OnErrorAsync, OnCompletedAsync ); } public async Task StopConsuming() { logger.Info( "StopConsuming" ); if ( consumerHandle != null ) { await consumerHandle.UnsubscribeAsync(); //consumerHandle.Dispose(); consumerHandle = null; } } public Task<int> GetNumberConsumed() { return Task.FromResult( numConsumedItems ); } public Task OnNextAsync( int item, StreamSequenceToken token = null ) { logger.Info( "OnNextAsync({0}{1})", item, token != null ? token.ToString() : "null" ); numConsumedItems++; return TaskDone.Done; } public Task OnCompletedAsync() { logger.Info( "OnCompletedAsync()" ); return TaskDone.Done; } public Task OnErrorAsync( Exception ex ) { logger.Info( "OnErrorAsync({0})", ex ); return TaskDone.Done; } public override Task OnDeactivateAsync() { logger.Info("OnDeactivateAsync"); return TaskDone.Done; } } }
// // ViewBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin 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 System.Drawing; using System.IO; using System.Linq; using System.Xml; using Xwt; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using MonoMac.CoreGraphics; using MonoMac.CoreAnimation; #else using Foundation; using AppKit; using ObjCRuntime; using CoreGraphics; using CoreAnimation; #endif namespace Xwt.Mac { public abstract class ViewBackend<T,S>: ViewBackend where T:NSView where S:IWidgetEventSink { public new S EventSink { get { return (S) base.EventSink; } } public new T Widget { get { return (T) base.Widget; } } } public abstract class ViewBackend: IWidgetBackend { Widget frontend; IWidgetEventSink eventSink; IViewObject viewObject; WidgetEvent currentEvents; bool autosize; Size lastFittingSize; bool sizeCalcPending = true; bool sensitive = true; bool canGetFocus = true; Xwt.Drawing.Color backgroundColor; void IBackend.InitializeBackend (object frontend, ApplicationContext context) { ApplicationContext = context; this.frontend = (Widget) frontend; } void IWidgetBackend.Initialize (IWidgetEventSink sink) { eventSink = (IWidgetEventSink) sink; Initialize (); ResetFittingSize (); canGetFocus = Widget.AcceptsFirstResponder (); } /// <summary> /// To be called when the widget is a root and is not inside a Xwt window. For example, when it is in a popover or a tooltip /// In that case, the widget has to listen to the change event of the children and resize itself /// </summary> public void SetAutosizeMode (bool autosize) { this.autosize = autosize; if (autosize) AutoUpdateSize (); } public virtual void Initialize () { } public IWidgetEventSink EventSink { get { return eventSink; } } public Widget Frontend { get { return this.frontend; } } public ApplicationContext ApplicationContext { get; private set; } public object NativeWidget { get { return Widget; } } public NSView Widget { get { return (NSView) ViewObject.View; } } public IViewObject ViewObject { get { return viewObject; } set { viewObject = value; if (viewObject.Backend == null) viewObject.Backend = this; } } public string Name { get; set; } public bool Visible { get { return !Widget.Hidden; } set { Widget.Hidden = !value; } } public double Opacity { get { return Widget.AlphaValue; } set { Widget.AlphaValue = (float)value; } } public virtual bool Sensitive { get { return sensitive; } set { sensitive = value; UpdateSensitiveStatus (Widget, sensitive && ParentIsSensitive ()); } } bool ParentIsSensitive () { IViewObject parent = Widget.Superview as IViewObject; if (parent == null) { var wb = Widget.Window as WindowBackend; return wb == null || wb.Sensitive; } if (!parent.Backend.Sensitive) return false; return parent.Backend.ParentIsSensitive (); } internal void UpdateSensitiveStatus (NSView view, bool parentIsSensitive) { if (view is NSControl) ((NSControl)view).Enabled = parentIsSensitive && sensitive; foreach (var s in view.Subviews) { if ((s is IViewObject) && (((IViewObject)s).Backend != null)) ((IViewObject)s).Backend.UpdateSensitiveStatus (s, parentIsSensitive); else UpdateSensitiveStatus (s, sensitive && parentIsSensitive); } } public virtual bool CanGetFocus { get { return canGetFocus; } set { canGetFocus = value; if (!Widget.AcceptsFirstResponder ()) canGetFocus = false; } } public virtual bool HasFocus { get { return Widget.Window != null && Widget.Window.FirstResponder == Widget; } } public virtual void SetFocus () { if (Widget.Window != null && CanGetFocus) Widget.Window.MakeFirstResponder (Widget); } public string TooltipText { get { return Widget.ToolTip; } set { Widget.ToolTip = value; } } public void NotifyPreferredSizeChanged () { EventSink.OnPreferredSizeChanged (); } internal NSCursor Cursor { get; private set; } public void SetCursor (CursorType cursor) { if (cursor == CursorType.Arrow) Cursor = NSCursor.ArrowCursor; else if (cursor == CursorType.Crosshair) Cursor = NSCursor.CrosshairCursor; else if (cursor == CursorType.Hand) Cursor = NSCursor.OpenHandCursor; else if (cursor == CursorType.IBeam) Cursor = NSCursor.IBeamCursor; else if (cursor == CursorType.ResizeDown) Cursor = NSCursor.ResizeDownCursor; else if (cursor == CursorType.ResizeUp) Cursor = NSCursor.ResizeUpCursor; else if (cursor == CursorType.ResizeLeft) Cursor = NSCursor.ResizeLeftCursor; else if (cursor == CursorType.ResizeRight) Cursor = NSCursor.ResizeRightCursor; else if (cursor == CursorType.ResizeLeftRight) Cursor = NSCursor.ResizeLeftRightCursor; else if (cursor == CursorType.ResizeUpDown) Cursor = NSCursor.ResizeUpDownCursor; else if (cursor == CursorType.Invisible) // TODO: load transparent cursor Cursor = NSCursor.ArrowCursor; else if (cursor == CursorType.Move) Cursor = NSCursor.ClosedHandCursor; else Cursor = NSCursor.ArrowCursor; } ~ViewBackend () { Dispose (false); } public void Dispose () { GC.SuppressFinalize (this); Dispose (true); } protected virtual void Dispose (bool disposing) { } Size IWidgetBackend.Size { get { return new Size (Widget.WidgetWidth (), Widget.WidgetHeight ()); } } public static NSView GetWidget (IWidgetBackend w) { return ((ViewBackend)w).Widget; } public static NSView GetWidget (Widget w) { return GetWidget ((IWidgetBackend)Toolkit.GetBackend (w)); } public static NSView GetWidgetWithPlacement (IWidgetBackend childBackend) { var backend = (ViewBackend)childBackend; var child = backend.Widget; var wrapper = child.Superview as WidgetPlacementWrapper; if (wrapper != null) return wrapper; if (!NeedsAlignmentWrapper (backend.Frontend)) return child; wrapper = new WidgetPlacementWrapper (); wrapper.SetChild (child, backend.Frontend); return wrapper; } public static NSView SetChildPlacement (IWidgetBackend childBackend) { var backend = (ViewBackend)childBackend; var child = backend.Widget; var wrapper = child.Superview as WidgetPlacementWrapper; var fw = backend.Frontend; if (!NeedsAlignmentWrapper (fw)) { if (wrapper != null) { var parent = wrapper.Superview; child.RemoveFromSuperview (); ReplaceSubview (wrapper, child); } return child; } if (wrapper == null) { wrapper = new WidgetPlacementWrapper (); var f = child.Frame; ReplaceSubview (child, wrapper); wrapper.SetChild (child, backend.Frontend); wrapper.Frame = f; } else wrapper.UpdateChildPlacement (); return wrapper; } public static void RemoveChildPlacement (NSView w) { if (w == null) return; if (w is WidgetPlacementWrapper) { var wp = (WidgetPlacementWrapper)w; wp.Subviews [0].RemoveFromSuperview (); } } static bool NeedsAlignmentWrapper (Widget fw) { return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0; } public virtual void UpdateChildPlacement (IWidgetBackend childBackend) { SetChildPlacement (childBackend); } public static void ReplaceSubview (NSView oldChild, NSView newChild) { var vo = oldChild as IViewObject; if (vo != null && vo.Backend.Frontend.GetInternalParent () != null) { var ba = vo.Backend.Frontend.GetInternalParent ().GetBackend () as ViewBackend; if (ba != null) { ba.ReplaceChild (oldChild, newChild); return; } } var f = oldChild.Frame; oldChild.Superview.ReplaceSubviewWith (oldChild, newChild); newChild.Frame = f; } public virtual void ReplaceChild (NSView oldChild, NSView newChild) { var f = oldChild.Frame; oldChild.Superview.ReplaceSubviewWith (oldChild, newChild); newChild.Frame = f; } FontData customFont; public virtual object Font { get { if (customFont != null) return customFont; NSFont font = null; var widget = Widget; if (widget is CustomAlignedContainer) widget = ((CustomAlignedContainer)widget).Child; if (widget is NSControl) font = ((NSControl)(object)widget).Font; else if (widget is NSText) font = ((NSText)(object)widget).Font; else font = NSFont.ControlContentFontOfSize (NSFont.SystemFontSize); return customFont = FontData.FromFont (font); } set { customFont = (FontData) value; var widget = Widget; if (widget is CustomAlignedContainer) widget = ((CustomAlignedContainer)widget).Child; if (widget is NSControl) ((NSControl)(object)widget).Font = customFont.Font; if (widget is NSText) ((NSText)(object)widget).Font = customFont.Font; ResetFittingSize (); } } public virtual Xwt.Drawing.Color BackgroundColor { get { return this.backgroundColor; } set { this.backgroundColor = value; if (Widget.Layer == null) Widget.WantsLayer = true; Widget.Layer.BackgroundColor = value.ToCGColor (); } } #region IWidgetBackend implementation public Point ConvertToScreenCoordinates (Point widgetCoordinates) { var lo = Widget.ConvertPointToView (new CGPoint ((nfloat)widgetCoordinates.X, (nfloat)widgetCoordinates.Y), null); lo = Widget.Window.ConvertRectToScreen (new CGRect (lo, CGSize.Empty)).Location; return MacDesktopBackend.ToDesktopRect (new CGRect (lo.X, lo.Y, 0, Widget.IsFlipped ? 0 : Widget.Frame.Height)).Location; } protected virtual Size GetNaturalSize () { if (sizeCalcPending) { sizeCalcPending = false; var f = Widget.Frame; SizeToFit (); lastFittingSize = new Size (Widget.WidgetWidth (), Widget.WidgetHeight ()); Widget.Frame = f; } return lastFittingSize; } public virtual Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { return GetNaturalSize (); } protected double minWidth = -1, minHeight = -1; public void SetMinSize (double width, double height) { minWidth = width; minHeight = height; } protected void ResetFittingSize () { sizeCalcPending = true; } public void SizeToFit () { OnSizeToFit (); // if (minWidth != -1 && Widget.Frame.Width < minWidth || minHeight != -1 && Widget.Frame.Height < minHeight) // Widget.SetFrameSize (new SizeF (Math.Max (Widget.Frame.Width, (float)minWidth), Math.Max (Widget.Frame.Height, (float)minHeight))); } protected virtual Size CalcFittingSize () { return Size.Zero; } static readonly Selector sizeToFitSel = new Selector ("sizeToFit"); protected virtual void OnSizeToFit () { if (Widget.RespondsToSelector (sizeToFitSel)) { Messaging.void_objc_msgSend (Widget.Handle, sizeToFitSel.Handle); } else { var s = CalcFittingSize (); if (!s.IsZero) Widget.SetFrameSize (new CGSize ((nfloat)s.Width, (nfloat)s.Height)); } } public void SetSizeRequest (double width, double height) { // Nothing to do } public virtual void UpdateLayout () { if (autosize) AutoUpdateSize (); } void AutoUpdateSize () { var s = Frontend.Surface.GetPreferredSize (); Widget.SetFrameSize (new CGSize ((nfloat)s.Width, (nfloat)s.Height)); } NSObject gotFocusObserver; public virtual void EnableEvent (object eventId) { if (eventId is WidgetEvent) { WidgetEvent ev = (WidgetEvent) eventId; currentEvents |= ev; switch (ev) { case WidgetEvent.GotFocus: case WidgetEvent.LostFocus: SetupFocusEvents (Widget.GetType ()); break; } } } public virtual void DisableEvent (object eventId) { if (eventId is WidgetEvent) { WidgetEvent ev = (WidgetEvent) eventId; currentEvents &= ~ev; } } static Selector draggingEnteredSel = new Selector ("draggingEntered:"); static Selector draggingUpdatedSel = new Selector ("draggingUpdated:"); static Selector draggingExitedSel = new Selector ("draggingExited:"); static Selector prepareForDragOperationSel = new Selector ("prepareForDragOperation:"); static Selector performDragOperationSel = new Selector ("performDragOperation:"); static Selector concludeDragOperationSel = new Selector ("concludeDragOperation:"); static Selector becomeFirstResponderSel = new Selector ("becomeFirstResponder"); static Selector resignFirstResponderSel = new Selector ("resignFirstResponder"); static HashSet<Type> typesConfiguredForDragDrop = new HashSet<Type> (); static HashSet<Type> typesConfiguredForFocusEvents = new HashSet<Type> (); static void SetupForDragDrop (Type type) { lock (typesConfiguredForDragDrop) { if (typesConfiguredForDragDrop.Add (type)) { Class c = new Class (type); c.AddMethod (draggingEnteredSel.Handle, new Func<IntPtr,IntPtr,IntPtr,NSDragOperation> (DraggingEntered), "i@:@"); c.AddMethod (draggingUpdatedSel.Handle, new Func<IntPtr,IntPtr,IntPtr,NSDragOperation> (DraggingUpdated), "i@:@"); c.AddMethod (draggingExitedSel.Handle, new Action<IntPtr,IntPtr,IntPtr> (DraggingExited), "v@:@"); c.AddMethod (prepareForDragOperationSel.Handle, new Func<IntPtr,IntPtr,IntPtr,bool> (PrepareForDragOperation), "B@:@"); c.AddMethod (performDragOperationSel.Handle, new Func<IntPtr,IntPtr,IntPtr,bool> (PerformDragOperation), "B@:@"); c.AddMethod (concludeDragOperationSel.Handle, new Action<IntPtr,IntPtr,IntPtr> (ConcludeDragOperation), "v@:@"); } } } static void SetupFocusEvents (Type type) { lock (typesConfiguredForFocusEvents) { if (typesConfiguredForFocusEvents.Add (type)) { Class c = new Class (type); c.AddMethod (becomeFirstResponderSel.Handle, new Func<IntPtr,IntPtr,bool> (OnBecomeFirstResponder), "B@:"); c.AddMethod (resignFirstResponderSel.Handle, new Func<IntPtr,IntPtr,bool> (OnResignFirstResponder), "B@:"); } } } public void DragStart (DragStartData sdata) { var lo = Widget.ConvertPointToBase (new CGPoint (Widget.Bounds.X, Widget.Bounds.Y)); lo = Widget.Window.ConvertBaseToScreen (lo); var ml = NSEvent.CurrentMouseLocation; var pb = NSPasteboard.FromName (NSPasteboard.NSDragPasteboardName); if (pb == null) throw new InvalidOperationException ("Could not get pasteboard"); if (sdata.Data == null) throw new ArgumentNullException ("data"); InitPasteboard (pb, sdata.Data); var img = (NSImage)sdata.ImageBackend; var pos = new CGPoint (ml.X - lo.X - (float)sdata.HotX, lo.Y - ml.Y - (float)sdata.HotY + img.Size.Height); Widget.DragImage (img, pos, new CGSize (0, 0), NSApplication.SharedApplication.CurrentEvent, pb, Widget, true); } public void SetDragSource (TransferDataType[] types, DragDropAction dragAction) { } public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction) { SetupForDragDrop (Widget.GetType ()); var dtypes = types.Select (ToNSDragType).ToArray (); Widget.RegisterForDraggedTypes (dtypes); } static NSDragOperation DraggingEntered (IntPtr sender, IntPtr sel, IntPtr dragInfo) { return DraggingUpdated (sender, sel, dragInfo); } static NSDragOperation DraggingUpdated (IntPtr sender, IntPtr sel, IntPtr dragInfo) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; if (ob == null) return NSDragOperation.None; var backend = ob.Backend; NSDraggingInfo di = (NSDraggingInfo) Runtime.GetNSObject (dragInfo); var types = di.DraggingPasteboard.Types.Select (ToXwtDragType).ToArray (); var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y); if ((backend.currentEvents & WidgetEvent.DragOverCheck) != 0) { var args = new DragOverCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask)); backend.OnDragOverCheck (di, args); if (args.AllowedAction == DragDropAction.None) return NSDragOperation.None; if (args.AllowedAction != DragDropAction.Default) return ConvertAction (args.AllowedAction); } if ((backend.currentEvents & WidgetEvent.DragOver) != 0) { TransferDataStore store = new TransferDataStore (); FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ()); var args = new DragOverEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask)); backend.OnDragOver (di, args); if (args.AllowedAction == DragDropAction.None) return NSDragOperation.None; if (args.AllowedAction != DragDropAction.Default) return ConvertAction (args.AllowedAction); } return di.DraggingSourceOperationMask; } static void DraggingExited (IntPtr sender, IntPtr sel, IntPtr dragInfo) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; if (ob != null) { var backend = ob.Backend; backend.ApplicationContext.InvokeUserCode (delegate { backend.eventSink.OnDragLeave (EventArgs.Empty); }); } } static bool PrepareForDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; if (ob == null) return false; var backend = ob.Backend; NSDraggingInfo di = (NSDraggingInfo) Runtime.GetNSObject (dragInfo); var types = di.DraggingPasteboard.Types.Select (ToXwtDragType).ToArray (); var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y); if ((backend.currentEvents & WidgetEvent.DragDropCheck) != 0) { var args = new DragCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask)); bool res = backend.ApplicationContext.InvokeUserCode (delegate { backend.eventSink.OnDragDropCheck (args); }); if (args.Result == DragDropResult.Canceled || !res) return false; } return true; } static bool PerformDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; if (ob == null) return false; var backend = ob.Backend; NSDraggingInfo di = (NSDraggingInfo) Runtime.GetNSObject (dragInfo); var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y); if ((backend.currentEvents & WidgetEvent.DragDrop) != 0) { TransferDataStore store = new TransferDataStore (); FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ()); var args = new DragEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask)); backend.ApplicationContext.InvokeUserCode (delegate { backend.eventSink.OnDragDrop (args); }); return args.Success; } else return false; } static void ConcludeDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo) { Console.WriteLine ("ConcludeDragOperation"); } protected virtual void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args) { ApplicationContext.InvokeUserCode (delegate { eventSink.OnDragOverCheck (args); }); } protected virtual void OnDragOver (NSDraggingInfo di, DragOverEventArgs args) { ApplicationContext.InvokeUserCode (delegate { eventSink.OnDragOver (args); }); } void InitPasteboard (NSPasteboard pb, TransferDataSource data) { pb.ClearContents (); foreach (var t in data.DataTypes) { if (t == TransferDataType.Text) { pb.AddTypes (new string[] { NSPasteboard.NSStringType }, null); pb.SetStringForType ((string)data.GetValue (t), NSPasteboard.NSStringType); } } } static void FillDataStore (TransferDataStore store, NSPasteboard pb, string[] types) { foreach (var t in types) { if (!pb.Types.Contains (t)) continue; if (t == NSPasteboard.NSStringType) store.AddText (pb.GetStringForType (t)); else if (t == NSPasteboard.NSFilenamesType) { string data = pb.GetStringForType (t); XmlDocument doc = new XmlDocument (); doc.XmlResolver = null; // Avoid DTD validation doc.LoadXml (data); store.AddUris (doc.SelectNodes ("/plist/array/string").Cast<XmlElement> ().Select (e => new Uri (e.InnerText)).ToArray ()); } } } static NSDragOperation ConvertAction (DragDropAction action) { NSDragOperation res = (NSDragOperation)0; if ((action & DragDropAction.Copy) != 0) res |= NSDragOperation.Copy; if ((action & DragDropAction.Move) != 0) res |= NSDragOperation.Move; if ((action & DragDropAction.Link) != 0) res |= NSDragOperation.Link; return res; } static DragDropAction ConvertAction (NSDragOperation action) { if (action == NSDragOperation.AllObsolete) return DragDropAction.All; DragDropAction res = (DragDropAction)0; if ((action & NSDragOperation.Copy) != 0) res |= DragDropAction.Copy; if ((action & NSDragOperation.Move) != 0) res |= DragDropAction.Move; if ((action & NSDragOperation.Link) != 0) res |= DragDropAction.Link; return res; } static string ToNSDragType (TransferDataType type) { if (type == TransferDataType.Text) return NSPasteboard.NSStringType; if (type == TransferDataType.Uri) return NSPasteboard.NSFilenamesType; if (type == TransferDataType.Image) return NSPasteboard.NSPictType; if (type == TransferDataType.Rtf) return NSPasteboard.NSRtfType; if (type == TransferDataType.Html) return NSPasteboard.NSHtmlType; return type.Id; } static TransferDataType ToXwtDragType (string type) { if (type == NSPasteboard.NSStringType) return TransferDataType.Text; if (type == NSPasteboard.NSFilenamesType) return TransferDataType.Uri; if (type == NSPasteboard.NSPictType) return TransferDataType.Image; if (type == NSPasteboard.NSRtfType) return TransferDataType.Rtf; if (type == NSPasteboard.NSHtmlType) return TransferDataType.Html; return TransferDataType.FromId (type); } static bool OnBecomeFirstResponder (IntPtr sender, IntPtr sel) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; var canGetIt = ob.Backend.canGetFocus; if (canGetIt) ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnGotFocus); return canGetIt; } static bool OnResignFirstResponder (IntPtr sender, IntPtr sel) { IViewObject ob = Runtime.GetNSObject (sender) as IViewObject; ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnLostFocus); return true; } #endregion } sealed class WidgetPlacementWrapper: NSControl, IViewObject { NSView child; Widget w; public WidgetPlacementWrapper () { } NSView IViewObject.View { get { return this; } } ViewBackend IViewObject.Backend { get { var vo = child as IViewObject; return vo != null ? vo.Backend : null; } set { var vo = child as IViewObject; if (vo != null) vo.Backend = value; } } public override bool IsFlipped { get { return true; } } public void SetChild (NSView child, Widget w) { this.child = child; this.w = w; AddSubview (child); } public override void SetFrameSize (CGSize newSize) { base.SetFrameSize (newSize); if (w != null) UpdateChildPlacement (); } public void UpdateChildPlacement () { double cheight = Frame.Height - w.Margin.VerticalSpacing; double cwidth = Frame.Width - w.Margin.HorizontalSpacing; double cx = w.MarginLeft; double cy = w.MarginTop; var s = w.Surface.GetPreferredSize (cwidth, cheight); if (w.HorizontalPlacement != WidgetPlacement.Fill) { cx += (cwidth - s.Width) * w.HorizontalPlacement.GetValue (); cwidth = s.Width; } if (w.VerticalPlacement != WidgetPlacement.Fill) { cy += (cheight - s.Height) * w.VerticalPlacement.GetValue (); cheight = s.Height; } child.Frame = new CGRect ((nfloat)cx, (nfloat)cy, (nfloat)cwidth, (nfloat)cheight); } public override void SizeToFit () { base.SizeToFit (); } } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComProduction.DCP.DS { public class PRO_ShiftPatternDS { public PRO_ShiftPatternDS() { } private const string THIS = "PCSComProduction.DCP.DS.PRO_ShiftPatternDS"; private DateTime dtmSpecialDay = new DateTime(1000/01/01); /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { PRO_ShiftPatternVO objObject = (PRO_ShiftPatternVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO PRO_ShiftPattern(" + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.SHIFTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.SHIFTID_FLD].Value = objObject.ShiftID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.COMMENT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_ShiftPatternTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].Value = objObject.EffectDateFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATETO_FLD].Value = objObject.EffectDateTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].Value = objObject.WorkTimeFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMETO_FLD].Value = objObject.WorkTimeTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].Value = objObject.RegularStopFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPTO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].Value = objObject.RegularStopTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].Value = objObject.RefreshingFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGTO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGTO_FLD].Value = objObject.RefreshingTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].Value = objObject.ExtraStopFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPTO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].Value = objObject.ExtraStopTo; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// AddAndReturnID /// </summary> /// <param name="pobjObjectVO"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Tuesday, August 23 2005</date> public int AddAndReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { PRO_ShiftPatternVO objObject = (PRO_ShiftPatternVO) pobjObjectVO; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); string strSql= "INSERT INTO PRO_ShiftPattern(" + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)" + " SELECT @@IDENTITY"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.SHIFTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.SHIFTID_FLD].Value = objObject.ShiftID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.COMMENT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_ShiftPatternTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].Value = objObject.EffectDateFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATETO_FLD].Value = objObject.EffectDateTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].Value = objObject.WorkTimeFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMETO_FLD].Value = objObject.WorkTimeTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPFROM_FLD, OleDbType.Date)); if (objObject.RegularStopFrom.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].Value = objObject.RegularStopFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPTO_FLD, OleDbType.Date)); if (objObject.RegularStopTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].Value = objObject.RegularStopTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGFROM_FLD, OleDbType.Date)); if (objObject.RefreshingFrom.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].Value = objObject.RefreshingFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGTO_FLD, OleDbType.Date)); if (objObject.RefreshingTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGTO_FLD].Value = objObject.RefreshingTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGTO_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPFROM_FLD, OleDbType.Date)); if (objObject.ExtraStopFrom.ToShortDateString()!= dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].Value = objObject.ExtraStopFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPTO_FLD, OleDbType.Date)); if (objObject.ExtraStopTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].Value = objObject.ExtraStopTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].Value = DBNull.Value; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); if (objReturn != null) { return int.Parse(objReturn.ToString()); } else { return 0; } } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + PRO_ShiftPatternTable.TABLE_NAME + " WHERE " + "ShiftPatternID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME +" WHERE " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_ShiftPatternVO objObject = new PRO_ShiftPatternVO(); while (odrPCS.Read()) { objObject.ShiftPatternID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTPATTERNID_FLD].ToString().Trim()); objObject.ShiftID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[PRO_ShiftPatternTable.CCNID_FLD].ToString().Trim()); objObject.Comment = odrPCS[PRO_ShiftPatternTable.COMMENT_FLD].ToString().Trim(); try { objObject.EffectDateFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].ToString().Trim()); } catch{} try { objObject.EffectDateTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATETO_FLD].ToString().Trim()); } catch{} try { objObject.WorkTimeFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].ToString().Trim()); } catch{} try { objObject.WorkTimeTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMETO_FLD].ToString().Trim()); } catch{} try { objObject.RegularStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].ToString().Trim()); } catch{} try { objObject.RegularStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].ToString().Trim()); } catch{} try { objObject.RefreshingFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].ToString().Trim()); } catch{} try { objObject.RefreshingTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGTO_FLD].ToString().Trim()); } catch{} try { objObject.ExtraStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].ToString().Trim()); } catch{} try { objObject.ExtraStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].ToString().Trim()); } catch{} } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public object GetObjectVOByShiftID(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVOByShiftID()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME +" WHERE " + PRO_ShiftPatternTable.SHIFTID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_ShiftPatternVO objObject = new PRO_ShiftPatternVO(); while (odrPCS.Read()) { objObject.ShiftPatternID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTPATTERNID_FLD].ToString().Trim()); objObject.ShiftID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[PRO_ShiftPatternTable.CCNID_FLD].ToString().Trim()); objObject.Comment = odrPCS[PRO_ShiftPatternTable.COMMENT_FLD].ToString().Trim(); try { objObject.EffectDateFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].ToString().Trim()); } catch{} try { objObject.EffectDateTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATETO_FLD].ToString().Trim()); } catch{} try { objObject.WorkTimeFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].ToString().Trim()); } catch{} try { objObject.WorkTimeTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMETO_FLD].ToString().Trim()); } catch{} try { objObject.RegularStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].ToString().Trim()); } catch{} try { objObject.RegularStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].ToString().Trim()); } catch{} try { objObject.RefreshingFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].ToString().Trim()); } catch{} try { objObject.RefreshingTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGTO_FLD].ToString().Trim()); } catch{} try { objObject.ExtraStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].ToString().Trim()); } catch{} try { objObject.ExtraStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].ToString().Trim()); } catch{} } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; PRO_ShiftPatternVO objObject = (PRO_ShiftPatternVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE PRO_ShiftPattern SET " + PRO_ShiftPatternTable.SHIFTID_FLD + "= ?" + "," + PRO_ShiftPatternTable.CCNID_FLD + "= ?" + "," + PRO_ShiftPatternTable.COMMENT_FLD + "= ?" + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "= ?" + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "= ?" + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "= ?" + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "= ?" + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "= ?" + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "= ?" + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "= ?" + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "= ?" + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "= ?" + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + "= ?" +" WHERE " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.SHIFTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.SHIFTID_FLD].Value = objObject.ShiftID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.COMMENT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_ShiftPatternTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].Value = objObject.EffectDateFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EFFECTDATETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.EFFECTDATETO_FLD].Value = objObject.EffectDateTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMEFROM_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].Value = objObject.WorkTimeFrom; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.WORKTIMETO_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_ShiftPatternTable.WORKTIMETO_FLD].Value = objObject.WorkTimeTo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPFROM_FLD, OleDbType.Date)); if (objObject.RegularStopFrom.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].Value = objObject.RegularStopFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REGULARSTOPTO_FLD, OleDbType.Date)); if (objObject.RegularStopTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].Value = objObject.RegularStopTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGFROM_FLD, OleDbType.Date)); if (objObject.RefreshingFrom.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].Value = objObject.RefreshingFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.REFRESHINGTO_FLD, OleDbType.Date)); if (objObject.RefreshingTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGTO_FLD].Value = objObject.RefreshingTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.REFRESHINGTO_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPFROM_FLD, OleDbType.Date)); if (objObject.ExtraStopFrom.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].Value = objObject.ExtraStopFrom; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.EXTRASTOPTO_FLD, OleDbType.Date)); if (objObject.ExtraStopTo.ToShortDateString() != dtmSpecialDay.ToShortDateString()) { ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].Value = objObject.ExtraStopTo; } else ocmdPCS.Parameters[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_ShiftPatternTable.SHIFTPATTERNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_ShiftPatternTable.SHIFTPATTERNID_FLD].Value = objObject.ShiftPatternID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,PRO_ShiftPatternTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// GetWorkingTime /// </summary> /// <returns></returns> /// <author>Trada</author> /// <date>Monday, September 18 2006</date> public DataSet GetWorkingTime() { const string METHOD_NAME = THIS + ".GetWorkingTime()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME + " WHERE " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + " IN (1,2,3)" + " ORDER BY " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,PRO_ShiftPatternTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to PRO_ShiftPattern /// </summary> /// <Inputs> /// PRO_ShiftPatternVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Tuesday, August 02, 2005 /// </History> public void UpdateDataSet(DataSet pdstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pdstData.EnforceConstraints = false; odadPCS.Update(pdstData,PRO_ShiftPatternTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// GetShiftPartternByShiftCode /// </summary> /// <param name="pintCCNID"></param> /// <param name="pintShiftID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Friday, August 12 2005</date> public object GetShiftPartternByShiftCode(int pintShiftID, int pintCCNID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql= "SELECT " + PRO_ShiftPatternTable.SHIFTPATTERNID_FLD + "," + PRO_ShiftPatternTable.SHIFTID_FLD + "," + PRO_ShiftPatternTable.CCNID_FLD + "," + PRO_ShiftPatternTable.COMMENT_FLD + "," + PRO_ShiftPatternTable.EFFECTDATEFROM_FLD + "," + PRO_ShiftPatternTable.EFFECTDATETO_FLD + "," + PRO_ShiftPatternTable.WORKTIMEFROM_FLD + "," + PRO_ShiftPatternTable.WORKTIMETO_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPFROM_FLD + "," + PRO_ShiftPatternTable.REGULARSTOPTO_FLD + "," + PRO_ShiftPatternTable.REFRESHINGFROM_FLD + "," + PRO_ShiftPatternTable.REFRESHINGTO_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPFROM_FLD + "," + PRO_ShiftPatternTable.EXTRASTOPTO_FLD + " FROM " + PRO_ShiftPatternTable.TABLE_NAME + " WHERE " + PRO_ShiftPatternTable.CCNID_FLD + " = " + pintCCNID.ToString() + " AND " + PRO_ShiftPatternTable.SHIFTID_FLD + " = " + pintShiftID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_ShiftPatternVO objObject = new PRO_ShiftPatternVO(); while (odrPCS.Read()) { objObject.ShiftPatternID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTPATTERNID_FLD].ToString().Trim()); objObject.ShiftID = int.Parse(odrPCS[PRO_ShiftPatternTable.SHIFTID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[PRO_ShiftPatternTable.CCNID_FLD].ToString().Trim()); objObject.Comment = odrPCS[PRO_ShiftPatternTable.COMMENT_FLD].ToString().Trim(); objObject.EffectDateFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATEFROM_FLD].ToString().Trim()); objObject.EffectDateTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EFFECTDATETO_FLD].ToString().Trim()); objObject.WorkTimeFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMEFROM_FLD].ToString().Trim()); objObject.WorkTimeTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.WORKTIMETO_FLD].ToString().Trim()); if (odrPCS[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].ToString().Trim() != string.Empty) { objObject.RegularStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPFROM_FLD].ToString().Trim()); } else objObject.RegularStopFrom = dtmSpecialDay; if (odrPCS[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].ToString().Trim() != string.Empty) { objObject.RegularStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REGULARSTOPTO_FLD].ToString().Trim()); } else objObject.RegularStopTo = dtmSpecialDay; if (odrPCS[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].ToString().Trim() != string.Empty) { objObject.RefreshingFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGFROM_FLD].ToString().Trim()); } else objObject.RefreshingFrom = dtmSpecialDay; if (odrPCS[PRO_ShiftPatternTable.REFRESHINGTO_FLD].ToString().Trim() != string.Empty) { objObject.RefreshingTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.REFRESHINGTO_FLD].ToString().Trim()); } else objObject.RefreshingTo = dtmSpecialDay; if (odrPCS[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].ToString().Trim() != string.Empty) { objObject.ExtraStopFrom = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPFROM_FLD].ToString().Trim()); } else objObject.ExtraStopFrom = dtmSpecialDay; if (odrPCS[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].ToString().Trim() != string.Empty) { objObject.ExtraStopTo = DateTime.Parse(odrPCS[PRO_ShiftPatternTable.EXTRASTOPTO_FLD].ToString().Trim()); } else objObject.ExtraStopTo = dtmSpecialDay; } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections; using System.Text; using System.Windows.Forms; using DAQ.Environment; using DAQ.HAL; using DAQ.TransferCavityLock; using NationalInstruments.DAQmx; namespace DecelerationHardwareControl { public class Controller : MarshalByRefObject, TransferCavityLockable { #region Constants private const double synthOffAmplitude = -130.0; #endregion ControlWindow window; HP8673BSynth synth = (HP8673BSynth)Environs.Hardware.Instruments["synth"]; private TransferCavityLockable TCLHelper = new DAQMxTCLHelperSWTimed ("cavity", "analogTrigger3", "laser", "p2", "p1", "analogTrigger2", "cavityTriggerOut"); private bool analogsAvailable; private double lastCavityData; private double lastrefCavityData; private DateTime cavityTimestamp; private DateTime refcavityTimestamp; private double laserFrequencyControlVoltage; private double aomControlVoltage; private Task outputTask = new Task("AomControllerOutput"); private AnalogOutputChannel aomChannel = (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels["highvoltage"]; public AnalogSingleChannelWriter aomWriter; public double normsigGain; public double SynthOnFrequency { get { return Double.Parse(window.synthOnFreqBox.Text); } set { window.SetTextBox(window.synthOnFreqBox, value.ToString()); } } public double SynthOnAmplitude { get { return Double.Parse(window.synthOnAmpBox.Text); } set { window.SetTextBox(window.synthOnAmpBox, value.ToString()); } } // The keys of the hashtable are the names of the analog output channels // The values are all booleans - true means the channel is blocked private Hashtable analogOutputsBlocked; // without this method, any remote connections to this object will time out after // five minutes of inactivity. // It just overrides the lifetime lease system completely. public override Object InitializeLifetimeService() { return null; } public void Start() { analogsAvailable = true; // all the analog outputs are unblocked at the outset analogOutputsBlocked = new Hashtable(); foreach (DictionaryEntry de in Environs.Hardware.AnalogOutputChannels) analogOutputsBlocked.Add(de.Key, false); aomChannel.AddToTask(outputTask, -10, 10); outputTask.Control(TaskAction.Verify); aomWriter = new AnalogSingleChannelWriter(outputTask.Stream); window = new ControlWindow(); window.controller = this; Application.Run(window); } // Applications may set this control voltage themselves, but when they do // they should set this property too public double LaserFrequencyControlVoltage { get { return laserFrequencyControlVoltage; } set { laserFrequencyControlVoltage = value; } } public double AOMControlVoltage { get { return aomControlVoltage; } set { aomControlVoltage = value; } } // returns true if the channel is blocked public bool GetAnalogOutputBlockedStatus(string channel) { return (bool)analogOutputsBlocked[channel]; } // set to true to block the output channel public void SetAnalogOutputBlockedStatus(string channel, bool state) { analogOutputsBlocked[channel] = state; } public bool LaserLocked { get { return window.LaserLockCheckBox.Checked; } set { window.SetCheckBox(window.LaserLockCheckBox, value); } } public bool AnalogInputsAvailable { get { return analogsAvailable; } set { analogsAvailable = value; } } public void UpdateLockCavityData(double cavityValue) { lastCavityData = cavityValue; cavityTimestamp = DateTime.Now; } public void UpdateReferenceCavityData(double refcavityValue) { lastrefCavityData = refcavityValue; refcavityTimestamp = DateTime.Now; } public double LastCavityData { get { return lastCavityData; } } public DateTime LastCavityTimeStamp { get { return cavityTimestamp; } } public double TimeSinceLastCavityRead { get { TimeSpan delta = DateTime.Now - cavityTimestamp; return (delta.Milliseconds + 1000 * delta.Seconds + 60 * 1000 * delta.Minutes); } } public double AOMVoltage { get { return AOMControlVoltage; } set { if (!Environs.Debug) { aomWriter.WriteSingleSample(true, value); outputTask.Control(TaskAction.Unreserve); } else { // Debug mode, do nothing } aomControlVoltage = value; } } public void diodeSaturationError() { window.SetDiodeWarning(window.diodeSaturation, true); } public void diodeSaturation() { window.SetDiodeWarning(window.diodeSaturation, false); } #region TransferCavityLockable Members public void ConfigureCavityScan(int numberOfSteps, bool autostart) { TCLHelper.ConfigureCavityScan(numberOfSteps, autostart); } public void ConfigureReadPhotodiodes(int numberOfMeasurements, bool autostart) { TCLHelper.ConfigureReadPhotodiodes(numberOfMeasurements, autostart); } public void ConfigureSetLaserVoltage(double voltage) { TCLHelper.ConfigureSetLaserVoltage(voltage); } public void ConfigureScanTrigger() { TCLHelper.ConfigureScanTrigger(); } public void ScanCavity(double[] rampVoltages, bool autostart) { TCLHelper.ScanCavity(rampVoltages, autostart); } public void StartScan() { TCLHelper.StartScan(); } public void StopScan() { TCLHelper.StopScan(); } public double[,] ReadPhotodiodes(int numberOfMeasurements) { return TCLHelper.ReadPhotodiodes(numberOfMeasurements); } public void SetLaserVoltage(double voltage) { TCLHelper.SetLaserVoltage(voltage); } public void ReleaseCavityHardware() { TCLHelper.ReleaseCavityHardware(); } public void SendScanTriggerAndWaitUntilDone() { TCLHelper.SendScanTriggerAndWaitUntilDone(); } public void ReleaseLaser() { TCLHelper.ReleaseLaser(); } public void EnableSynth(bool enable) { synth.Connect(); if (enable) { synth.Frequency = SynthOnFrequency; synth.Amplitude = SynthOnAmplitude; synth.Enabled = true; } else { synth.Enabled = false; } synth.Disconnect(); } public void UpdateSynthSettings() { synth.Connect(); synth.Frequency = SynthOnFrequency; synth.Amplitude = SynthOnAmplitude; synth.Disconnect(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.ViewFeatures; namespace Microsoft.AspNetCore.Mvc.Rendering { /// <summary> /// Contains methods and properties that are used to create HTML elements. This class is often used to write HTML /// helpers and tag helpers. /// </summary> [DebuggerDisplay("{DebuggerToString()}")] public class TagBuilder : IHtmlContent { private AttributeDictionary? _attributes; private HtmlContentBuilder? _innerHtml; /// <summary> /// Creates a new HTML tag that has the specified tag name. /// </summary> /// <param name="tagName">An HTML tag name.</param> public TagBuilder(string tagName) { if (string.IsNullOrEmpty(tagName)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(tagName)); } TagName = tagName; } /// <summary> /// Creates a copy of the HTML tag passed as <paramref name="tagBuilder"/>. /// </summary> /// <param name="tagBuilder">Tag to copy.</param> public TagBuilder(TagBuilder tagBuilder) { if (tagBuilder == null) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(tagBuilder)); } if (tagBuilder._attributes != null) { foreach (var tag in tagBuilder._attributes) { Attributes.Add(tag); } } if (tagBuilder._innerHtml != null) { tagBuilder.InnerHtml.CopyTo(InnerHtml); } TagName = tagBuilder.TagName; TagRenderMode = tagBuilder.TagRenderMode; } /// <summary> /// Gets the set of attributes that will be written to the tag. /// </summary> public AttributeDictionary Attributes { get { // Perf: Avoid allocating `_attributes` if possible if (_attributes == null) { _attributes = new AttributeDictionary(); } return _attributes; } } /// <summary> /// Gets the inner HTML content of the element. /// </summary> public IHtmlContentBuilder InnerHtml { get { if (_innerHtml == null) { _innerHtml = new HtmlContentBuilder(); } return _innerHtml; } } /// <summary> /// Gets an indication <see cref="InnerHtml"/> is not empty. /// </summary> public bool HasInnerHtml => _innerHtml?.Count > 0; /// <summary> /// Gets the tag name for this tag. /// </summary> public string TagName { get; } /// <summary> /// The <see cref="Rendering.TagRenderMode"/> with which the tag is written. /// </summary> /// <remarks>Defaults to <see cref="TagRenderMode.Normal"/>.</remarks> public TagRenderMode TagRenderMode { get; set; } = TagRenderMode.Normal; /// <summary> /// Adds a CSS class to the list of CSS classes in the tag. /// If there are already CSS classes on the tag then a space character and the new class will be appended to /// the existing list. /// </summary> /// <param name="value">The CSS class name to add.</param> public void AddCssClass(string value) { if (Attributes.TryGetValue("class", out var currentValue)) { Attributes["class"] = currentValue + " " + value; } else { Attributes["class"] = value; } } /// <summary> /// Returns a valid HTML 4.01 "id" attribute value for an element with the given <paramref name="name"/>. /// </summary> /// <param name="name"> /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name. /// </param> /// <param name="invalidCharReplacement"> /// The <see cref="string"/> (normally a single <see cref="char"/>) to substitute for invalid characters in /// <paramref name="name"/>. /// </param> /// <returns> /// Valid HTML 4.01 "id" attribute value for an element with the given <paramref name="name"/>. /// </returns> /// <remarks> /// Valid "id" attributes are defined in https://www.w3.org/TR/html401/types.html#type-id. /// </remarks> public static string CreateSanitizedId(string? name, string invalidCharReplacement) { if (invalidCharReplacement == null) { throw new ArgumentNullException(nameof(invalidCharReplacement)); } if (string.IsNullOrEmpty(name)) { return string.Empty; } // If there are no invalid characters in the string, then we don't have to create the buffer. var firstIndexOfInvalidCharacter = 1; for (; firstIndexOfInvalidCharacter < name.Length; firstIndexOfInvalidCharacter++) { if (!Html401IdUtil.IsValidIdCharacter(name[firstIndexOfInvalidCharacter])) { break; } } var firstChar = name[0]; var startsWithAsciiLetter = Html401IdUtil.IsAsciiLetter(firstChar); if (!startsWithAsciiLetter) { // The first character must be a letter according to the HTML 4.01 specification. firstChar = 'z'; } if (firstIndexOfInvalidCharacter == name.Length && startsWithAsciiLetter) { return name; } var stringBuffer = new StringBuilder(name.Length); stringBuffer.Append(firstChar); // Characters until 'firstIndexOfInvalidCharacter' have already been checked for validity. // So just copy them. This avoids running them through Html401IdUtil.IsValidIdCharacter again. for (var index = 1; index < firstIndexOfInvalidCharacter; index++) { stringBuffer.Append(name[index]); } for (var index = firstIndexOfInvalidCharacter; index < name.Length; index++) { var thisChar = name[index]; if (Html401IdUtil.IsValidIdCharacter(thisChar)) { stringBuffer.Append(thisChar); } else { stringBuffer.Append(invalidCharReplacement); } } return stringBuffer.ToString(); } /// <summary> /// Adds a valid HTML 4.01 "id" attribute for an element with the given <paramref name="name"/>. Does /// nothing if <see cref="Attributes"/> already contains an "id" attribute or the <paramref name="name"/> /// is <c>null</c> or empty. /// </summary> /// <param name="name"> /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name. /// </param> /// <param name="invalidCharReplacement"> /// The <see cref="string"/> (normally a single <see cref="char"/>) to substitute for invalid characters in /// <paramref name="name"/>. /// </param> /// <seealso cref="CreateSanitizedId(string, string)"/> public void GenerateId(string name, string invalidCharReplacement) { if (invalidCharReplacement == null) { throw new ArgumentNullException(nameof(invalidCharReplacement)); } if (string.IsNullOrEmpty(name)) { return; } if (!Attributes.ContainsKey("id")) { var sanitizedId = CreateSanitizedId(name, invalidCharReplacement); // Duplicate check for null or empty to cover the corner case where name contains only invalid // characters and invalidCharReplacement is empty. if (!string.IsNullOrEmpty(sanitizedId)) { Attributes["id"] = sanitizedId; } } } private void AppendAttributes(TextWriter writer, HtmlEncoder encoder) { // Perf: Avoid allocating enumerator for `_attributes` if possible if (_attributes != null && _attributes.Count > 0) { foreach (var attribute in Attributes) { var key = attribute.Key; if (string.Equals(key, "id", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(attribute.Value)) { continue; } writer.Write(" "); writer.Write(key); writer.Write("=\""); if (attribute.Value != null) { encoder.Encode(writer, attribute.Value); } writer.Write("\""); } } } /// <summary> /// Merge an attribute. /// </summary> /// <param name="key">The attribute key.</param> /// <param name="value">The attribute value.</param> public void MergeAttribute(string key, string? value) { MergeAttribute(key, value, replaceExisting: false); } /// <summary> /// Merge an attribute. /// </summary> /// <param name="key">The attribute key.</param> /// <param name="value">The attribute value.</param> /// <param name="replaceExisting">Whether to replace an existing value.</param> public void MergeAttribute(string key, string? value, bool replaceExisting) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(key)); } if (replaceExisting || !Attributes.ContainsKey(key)) { Attributes[key] = value; } } /// <summary> /// Merge an attribute dictionary. /// </summary> /// <typeparam name="TKey">The key type.</typeparam> /// <typeparam name="TValue">The value type.</typeparam> /// <param name="attributes">The attributes.</param> public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue?> attributes) { MergeAttributes(attributes, replaceExisting: false); } /// <summary> /// Merge an attribute dictionary. /// </summary> /// <typeparam name="TKey">The key type.</typeparam> /// <typeparam name="TValue">The value type.</typeparam> /// <param name="attributes">The attributes.</param> /// <param name="replaceExisting">Whether to replace existing attributes.</param> public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue?> attributes, bool replaceExisting) { // Perf: Avoid allocating enumerator for `attributes` if possible if (attributes != null && attributes.Count > 0) { foreach (var entry in attributes) { var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture)!; var value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture); MergeAttribute(key, value, replaceExisting); } } } /// <inheritdoc /> public void WriteTo(TextWriter writer, HtmlEncoder encoder) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (encoder == null) { throw new ArgumentNullException(nameof(encoder)); } WriteTo(this, writer, encoder, TagRenderMode); } /// <summary> /// Returns an <see cref="IHtmlContent"/> that renders the body. /// </summary> /// <returns>An <see cref="IHtmlContent"/> that renders the body.</returns> public IHtmlContent? RenderBody() => _innerHtml; /// <summary> /// Returns an <see cref="IHtmlContent"/> that renders the start tag. /// </summary> /// <returns>An <see cref="IHtmlContent"/> that renders the start tag.</returns> public IHtmlContent RenderStartTag() => new RenderTagHtmlContent(this, TagRenderMode.StartTag); /// <summary> /// Returns an <see cref="IHtmlContent"/> that renders the end tag. /// </summary> /// <returns>An <see cref="IHtmlContent"/> that renders the end tag.</returns> public IHtmlContent RenderEndTag() => new RenderTagHtmlContent(this, TagRenderMode.EndTag); /// <summary> /// Returns an <see cref="IHtmlContent"/> that renders the self-closing tag. /// </summary> /// <returns>An <see cref="IHtmlContent"/> that renders the self-closing tag.</returns> public IHtmlContent RenderSelfClosingTag() => new RenderTagHtmlContent(this, TagRenderMode.SelfClosing); private static void WriteTo( TagBuilder tagBuilder, TextWriter writer, HtmlEncoder encoder, TagRenderMode tagRenderMode) { switch (tagRenderMode) { case TagRenderMode.StartTag: writer.Write("<"); writer.Write(tagBuilder.TagName); tagBuilder.AppendAttributes(writer, encoder); writer.Write(">"); break; case TagRenderMode.EndTag: writer.Write("</"); writer.Write(tagBuilder.TagName); writer.Write(">"); break; case TagRenderMode.SelfClosing: writer.Write("<"); writer.Write(tagBuilder.TagName); tagBuilder.AppendAttributes(writer, encoder); writer.Write(" />"); break; default: writer.Write("<"); writer.Write(tagBuilder.TagName); tagBuilder.AppendAttributes(writer, encoder); writer.Write(">"); if (tagBuilder._innerHtml != null) { tagBuilder._innerHtml.WriteTo(writer, encoder); } writer.Write("</"); writer.Write(tagBuilder.TagName); writer.Write(">"); break; } } private string DebuggerToString() { using (var writer = new StringWriter()) { WriteTo(writer, HtmlEncoder.Default); return writer.ToString(); } } private class RenderTagHtmlContent : IHtmlContent { private readonly TagBuilder _tagBuilder; private readonly TagRenderMode _tagRenderMode; public RenderTagHtmlContent(TagBuilder tagBuilder, TagRenderMode tagRenderMode) { _tagBuilder = tagBuilder; _tagRenderMode = tagRenderMode; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { TagBuilder.WriteTo(_tagBuilder, writer, encoder, _tagRenderMode); } } private static class Html401IdUtil { public static bool IsAsciiLetter(char testChar) { return (('A' <= testChar && testChar <= 'Z') || ('a' <= testChar && testChar <= 'z')); } public static bool IsValidIdCharacter(char testChar) { return (IsAsciiLetter(testChar) || IsAsciiDigit(testChar) || IsAllowableSpecialCharacter(testChar)); } private static bool IsAsciiDigit(char testChar) { return ('0' <= testChar && testChar <= '9'); } private static bool IsAllowableSpecialCharacter(char testChar) { switch (testChar) { case '-': case '_': case ':': // Note '.' is valid according to the HTML 4.01 specification. Disallowed here to avoid // confusion with CSS class selectors or when using jQuery. return true; default: return false; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TestApp.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// // TrackInfoDisplay.cs // // Author: // Aaron Bockover <abockover@novell.com> // Larry Ewing <lewing@novell.com> (Is my hero) // // Copyright (C) 2007 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 Cairo; using Hyena; using Hyena.Gui; using Hyena.Gui.Theatrics; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.ServiceStack; using Banshee.MediaEngine; namespace Banshee.Gui.Widgets { public abstract class TrackInfoDisplay : Widget { private string current_artwork_id; private ArtworkManager artwork_manager; protected ArtworkManager ArtworkManager { get { return artwork_manager; } } private ImageSurface current_image; protected ImageSurface CurrentImage { get { return current_image; } } private ImageSurface incoming_image; protected ImageSurface IncomingImage { get { return incoming_image; } } protected string MissingAudioIconName { get; set; } protected string MissingVideoIconName { get; set; } private ImageSurface missing_audio_image; protected ImageSurface MissingAudioImage { get { return missing_audio_image ?? (missing_audio_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingAudioIconName), true)); } } private ImageSurface missing_video_image; protected ImageSurface MissingVideoImage { get { return missing_video_image ?? (missing_video_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingVideoIconName), true)); } } protected virtual Cairo.Color BackgroundColor { get; set; } private Cairo.Color text_color; protected virtual Cairo.Color TextColor { get { return text_color; } } private Cairo.Color text_light_color; protected virtual Cairo.Color TextLightColor { get { return text_light_color; } } private TrackInfo current_track; protected TrackInfo CurrentTrack { get { return current_track; } } private TrackInfo incoming_track; protected TrackInfo IncomingTrack { get { return incoming_track; } } private uint idle_timeout_id = 0; private SingleActorStage stage = new SingleActorStage (); protected TrackInfoDisplay (IntPtr native) : base (native) { } public TrackInfoDisplay () { MissingAudioIconName = "audio-x-generic"; MissingVideoIconName = "video-x-generic"; stage.Iteration += OnStageIteration; if (ServiceManager.Contains<ArtworkManager> ()) { artwork_manager = ServiceManager.Get<ArtworkManager> (); } Connected = true; WidgetFlags |= WidgetFlags.NoWindow; } private bool connected; public bool Connected { get { return connected; } set { if (value == connected) return; if (ServiceManager.PlayerEngine != null) { connected = value; if (value) { ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated | PlayerEvent.StateChange); } else { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); } } } } public static Widget GetEditable (TrackInfoDisplay display) { return CoverArtEditor.For (display, (x, y) => display.IsWithinCoverart (x, y), () => display.CurrentTrack, () => {} ); } public override void Dispose () { if (idle_timeout_id > 0) { GLib.Source.Remove (idle_timeout_id); } Connected = false; stage.Iteration -= OnStageIteration; stage = null; InvalidateCache (); base.Dispose (); } protected override void OnRealized () { GdkWindow = Parent.GdkWindow; base.OnRealized (); } protected override void OnUnrealized () { base.OnUnrealized (); InvalidateCache (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); ResetMissingImages (); if (current_track == null) { LoadCurrentTrack (); } else { Invalidate (); } } protected override void OnStyleSet (Style previous) { base.OnStyleSet (previous); text_color = CairoExtensions.GdkColorToCairoColor (Style.Foreground (StateType.Normal)); BackgroundColor = CairoExtensions.GdkColorToCairoColor (Style.Background (StateType.Normal)); text_light_color = Hyena.Gui.Theming.GtkTheme.GetCairoTextMidColor (this); ResetMissingImages (); OnThemeChanged (); } private void ResetMissingImages () { if (missing_audio_image != null) { ((IDisposable)missing_audio_image).Dispose (); var disposed = missing_audio_image; missing_audio_image = null; if (current_image == disposed) { current_image = MissingAudioImage; } if (incoming_image == disposed) { incoming_image = MissingAudioImage; } } if (missing_video_image != null) { ((IDisposable)missing_video_image).Dispose (); var disposed = missing_video_image; missing_video_image = null; if (current_image == disposed) { current_image = MissingVideoImage; } if (incoming_image == disposed) { incoming_image = MissingVideoImage; } } } protected virtual void OnThemeChanged () { } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { bool idle = incoming_track == null && current_track == null; if (!Visible || !IsMapped || (idle && !CanRenderIdle)) { return true; } Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window); foreach (Gdk.Rectangle damage in evnt.Region.GetRectangles ()) { cr.Rectangle (damage.X, damage.Y, damage.Width, damage.Height); cr.Clip (); if (idle) { RenderIdle (cr); } else { RenderAnimation (cr); } cr.ResetClip (); } CairoExtensions.DisposeContext (cr); return true; } protected virtual bool CanRenderIdle { get { return false; } } protected virtual void RenderIdle (Cairo.Context cr) { } private void RenderAnimation (Cairo.Context cr) { if (stage.Actor == null) { // We are not in a transition, just render RenderStage (cr, current_track, current_image); return; } if (current_track == null) { // Fade in the whole stage, nothing to fade out CairoExtensions.PushGroup (cr); RenderStage (cr, incoming_track, incoming_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (stage.Actor.Percent); return; } // Draw the old cover art more and more translucent CairoExtensions.PushGroup (cr); RenderCoverArt (cr, current_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - stage.Actor.Percent); // Draw the new cover art more and more opaque CairoExtensions.PushGroup (cr); RenderCoverArt (cr, incoming_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (stage.Actor.Percent); bool same_artist_album = incoming_track != null ? incoming_track.ArtistAlbumEqual (current_track) : false; bool same_track = incoming_track != null ? incoming_track.Equals (current_track) : false; if (same_artist_album) { RenderTrackInfo (cr, incoming_track, same_track, true); } // Don't xfade the text since it'll look bad (overlapping words); instead, fade // the old out, and then the new in if (stage.Actor.Percent <= 0.5) { // Fade out old text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, current_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - (stage.Actor.Percent * 2.0)); } else { // Fade in new text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, incoming_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha ((stage.Actor.Percent - 0.5) * 2.0); } } private void RenderStage (Cairo.Context cr, TrackInfo track, ImageSurface image) { RenderCoverArt (cr, image); RenderTrackInfo (cr, track, true, true); } protected virtual void RenderCoverArt (Cairo.Context cr, ImageSurface image) { ArtworkRenderer.RenderThumbnail (cr, image, false, Allocation.X, Allocation.Y + ArtworkOffset, ArtworkSizeRequest, ArtworkSizeRequest, !IsMissingImage (image), 0.0, IsMissingImage (image), BackgroundColor); } protected virtual bool IsWithinCoverart (int x, int y) { return x >= 0 && y >= ArtworkOffset && x <= ArtworkSizeRequest && y <= (ArtworkOffset + ArtworkSizeRequest); } protected bool IsMissingImage (ImageSurface pb) { return pb == missing_audio_image || pb == missing_video_image; } protected virtual void InvalidateCache () { } protected abstract void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum); private int ArtworkOffset { get { return (Allocation.Height - ArtworkSizeRequest) / 2; } } protected virtual int ArtworkSizeRequest { get { return Allocation.Height; } } protected virtual int MissingIconSizeRequest { get { return ArtworkSizeRequest; } } private void OnPlayerEvent (PlayerEventArgs args) { if (args.Event == PlayerEvent.StartOfStream) { LoadCurrentTrack (); } else if (args.Event == PlayerEvent.TrackInfoUpdated) { LoadCurrentTrack (true); } else if (args.Event == PlayerEvent.StateChange && (incoming_track != null || incoming_image != null)) { PlayerEventStateChangeArgs state = (PlayerEventStateChangeArgs)args; if (state.Current == PlayerState.Idle) { if (idle_timeout_id == 0) { idle_timeout_id = GLib.Timeout.Add (100, IdleTimeout); } } } } private bool IdleTimeout () { if (ServiceManager.PlayerEngine == null || ServiceManager.PlayerEngine.CurrentTrack == null || ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle) { incoming_track = null; incoming_image = null; current_artwork_id = null; if (stage != null && stage.Actor == null) { stage.Reset (); } } idle_timeout_id = 0; return false; } private void LoadCurrentTrack () { LoadCurrentTrack (false); } private void LoadCurrentTrack (bool force_reload) { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track == current_track && !IsMissingImage (current_image) && !force_reload) { return; } else if (track == null) { incoming_track = null; incoming_image = null; return; } incoming_track = track; LoadImage (track, force_reload); if (stage.Actor == null) { stage.Reset (); } } private void LoadImage (TrackInfo track, bool force) { LoadImage (track.MediaAttributes, track.ArtworkId, force); if (track == current_track) { if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) { ((IDisposable)current_image).Dispose (); } current_image = incoming_image; } } protected void LoadImage (TrackMediaAttributes attr, string artwork_id, bool force) { if (current_artwork_id != artwork_id || force) { current_artwork_id = artwork_id; if (incoming_image != null && current_image != incoming_image && !IsMissingImage (incoming_image)) { ((IDisposable)incoming_image).Dispose (); } incoming_image = artwork_manager.LookupScaleSurface (artwork_id, ArtworkSizeRequest); } if (incoming_image == null) { incoming_image = MissingImage ((attr & TrackMediaAttributes.VideoStream) != 0); } } private ImageSurface MissingImage (bool is_video) { return is_video ? MissingVideoImage : MissingAudioImage; } private double last_fps = 0.0; private void OnStageIteration (object o, EventArgs args) { Invalidate (); if (stage.Actor != null) { last_fps = stage.Actor.FramesPerSecond; return; } InvalidateCache (); if (ApplicationContext.Debugging) { Log.DebugFormat ("TrackInfoDisplay RenderAnimation: {0:0.00} FPS", last_fps); } if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) { ((IDisposable)current_image).Dispose (); } current_image = incoming_image; current_track = incoming_track; incoming_track = null; OnArtworkChanged (); } protected virtual void Invalidate () { QueueDraw (); } protected virtual void OnArtworkChanged () { } protected virtual string GetFirstLineText (TrackInfo track) { return String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (track.DisplayTrackTitle)); } protected virtual string GetSecondLineText (TrackInfo track) { string markup = null; Banshee.Streaming.RadioTrackInfo radio_track = track as Banshee.Streaming.RadioTrackInfo; if ((track.MediaAttributes & TrackMediaAttributes.Podcast) != 0) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Podcast Name and Published Date, respectively; // e.g. 'from BBtv published 7/26/2007' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2} {0}published{1} {3}"), track.DisplayAlbumTitle, track.ReleaseDate.ToShortDateString ()); } else if (radio_track != null && radio_track.ParentTrack != null) { // This is complicated because some radio streams send tags when the song changes, and we // want to display them if they do. But if they don't, we want it to look good too, so we just // display the station name for the second line. string by_from = GetByFrom ( track.ArtistName == radio_track.ParentTrack.ArtistName ? null : track.ArtistName, track.DisplayArtistName, track.AlbumTitle == radio_track.ParentTrack.AlbumTitle ? null : track.AlbumTitle, track.DisplayAlbumTitle, false ); if (String.IsNullOrEmpty (by_from)) { // simply: "Chicago Public Radio" or whatever the artist name is markup = GLib.Markup.EscapeText (radio_track.ParentTrack.ArtistName ?? Catalog.GetString ("Unknown Stream")); } else { // Translators: {0} and {1} are markup so ignore them, {2} is the name of the radio station string on = MarkupFormat (Catalog.GetString ("{0}on{1} {2}"), radio_track.ParentTrack.TrackTitle); // Translators: {0} is the "from {album} by {artist}" type string, and {1} is the "on {radio station name}" string markup = String.Format (Catalog.GetString ("{0} {1}"), by_from, on); } } else { markup = GetByFrom (track.ArtistName, track.DisplayArtistName, track.AlbumTitle, track.DisplayAlbumTitle, true); } return String.Format ("<span color=\"{0}\">{1}</span>", CairoExtensions.ColorGetHex (TextColor, false), markup); } private string MarkupFormat (string fmt, params string [] args) { string [] new_args = new string [args.Length + 2]; new_args[0] = String.Format ("<span color=\"{0}\" size=\"small\">", CairoExtensions.ColorGetHex (TextLightColor, false)); new_args[1] = "</span>"; for (int i = 0; i < args.Length; i++) { new_args[i + 2] = GLib.Markup.EscapeText (args[i]); } return String.Format (fmt, new_args); } private string GetByFrom (string artist, string display_artist, string album, string display_album, bool unknown_ok) { bool has_artist = !String.IsNullOrEmpty (artist); bool has_album = !String.IsNullOrEmpty (album); string markup = null; if (has_artist && has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Artist Name and Album Title, respectively; // e.g. 'by Parkway Drive from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2} {0}from{1} {3}"), display_artist, display_album); } else if (has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Album Title; // e.g. 'from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2}"), display_album); } else if (has_artist || unknown_ok) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Artist Name; // e.g. 'by Parkway Drive' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2}"), display_artist); } return markup; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding; namespace Pathfinding { //Binary Heap #if false /** Binary heap implementation. Binary heaps are really fast for ordering nodes in a way that makes it possible to get the node with the lowest F score. Also known as a priority queue. * \see http://en.wikipedia.org/wiki/Binary_heap */ public class BinaryHeap { public Node[] binaryHeap; public int numberOfItems; public BinaryHeap( int numberOfElements ) { binaryHeap = new Node[numberOfElements]; numberOfItems = 2; } /** Adds a node to the heap */ public void Add(Node node) { if (node == null) { Debug.Log ("Sending null node to BinaryHeap"); return; } if (numberOfItems == binaryHeap.Length) { Debug.Log ("Forced to discard nodes because of binary heap size limit, please consider increasing the size ("+numberOfItems +" "+binaryHeap.Length+")"); numberOfItems--; } binaryHeap[numberOfItems] = node; //node.heapIndex = numberOfItems;//Heap index int bubbleIndex = numberOfItems; uint nodeF = node.f; while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; /*if (binaryHeap[parentIndex] == null) { Debug.Log ("WUT!!"); return; }*/ if (nodeF <= binaryHeap[parentIndex].f) { //binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { /** \todo Wouldn't it be more efficient with '<' instead of '<=' ? * / //Node tmpValue = binaryHeap[parentIndex]; //tmpValue.heapIndex = bubbleIndex;//HeapIndex binaryHeap[bubbleIndex] = binaryHeap[parentIndex]; binaryHeap[parentIndex] = node;//binaryHeap[bubbleIndex]; //binaryHeap[bubbleIndex].heapIndex = bubbleIndex; //Heap index //binaryHeap[parentIndex].heapIndex = parentIndex; //Heap index bubbleIndex = parentIndex; } else { /*if (binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { /** \todo Wouldn't it be more efficient with '<' instead of '<=' ? * Node tmpValue = binaryHeap[parentIndex]; //tmpValue.heapIndex = bubbleIndex;//HeapIndex binaryHeap[parentIndex] = binaryHeap[bubbleIndex]; binaryHeap[bubbleIndex] = tmpValue; bubbleIndex = parentIndex; } else {*/ break; } } numberOfItems++; } /** Returns the node with the lowest F score from the heap */ public Node Remove() { numberOfItems--; Node returnItem = binaryHeap[1]; //returnItem.heapIndex = 0;//Heap index binaryHeap[1] = binaryHeap[numberOfItems]; //binaryHeap[1].heapIndex = 1;//Heap index int swapItem = 1, parent = 1; do { parent = swapItem; int p2 = parent * 2; if ((p2 + 1) <= numberOfItems) { // Both children exist if (binaryHeap[parent].f >= binaryHeap[p2].f) { swapItem = p2;//2 * parent; } if (binaryHeap[swapItem].f >= binaryHeap[p2 + 1].f) { swapItem = p2 + 1; } } else if ((p2) <= numberOfItems) { // Only one child exists if (binaryHeap[parent].f >= binaryHeap[p2].f) { swapItem = p2; } } // One if the parent's children are smaller or equal, swap them if (parent != swapItem) { Node tmpIndex = binaryHeap[parent]; //tmpIndex.heapIndex = swapItem;//Heap index binaryHeap[parent] = binaryHeap[swapItem]; binaryHeap[swapItem] = tmpIndex; //binaryHeap[parent].heapIndex = parent;//Heap index } } while (parent != swapItem); return returnItem; } /** \deprecated Use #Add instead */ public void BubbleDown (Node node) { //int bubbleIndex = node.heapIndex; int bubbleIndex = 0; if (bubbleIndex < 1 || bubbleIndex > numberOfItems) { Debug.LogError ("Node is not in the heap (index "+bubbleIndex+")"); Add (node); return; } while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; /* Can be optimized to use 'node' instead of 'binaryHeap[bubbleIndex]' */ if (binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { Node tmpValue = binaryHeap[parentIndex]; binaryHeap[parentIndex] = binaryHeap[bubbleIndex]; binaryHeap[bubbleIndex] = tmpValue; //binaryHeap[parentIndex].heapIndex = parentIndex; //binaryHeap[bubbleIndex].heapIndex = bubbleIndex; bubbleIndex = parentIndex; } else { return; } } } /** Rebuilds the heap by trickeling down all items. Called after the hTarget on a path has been changed */ public void Rebuild () { if DEBUG int changes = 0; endif for (int i=2;i<numberOfItems;i++) { int bubbleIndex = i; Node node = binaryHeap[i]; uint nodeF = node.f; while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; if (nodeF < binaryHeap[parentIndex].f) { //Node tmpValue = binaryHeap[parentIndex]; binaryHeap[bubbleIndex] = binaryHeap[parentIndex]; binaryHeap[parentIndex] = node; bubbleIndex = parentIndex; if DEBUG changes++; endif } else { break; } } } if DEBUG Debug.Log ("+++ Rebuilt Heap - "+changes+" changes +++"); endif } /** Rearranges a node in the heap which has got it's F score changed (only works for a lower F score). \warning This is slow, often it is more efficient to just add the node to the heap again */ public void Rearrange (Node node) { for (int i=0;i<numberOfItems;i++) { if (binaryHeap[i] == node) { int bubbleIndex = i; while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; if (binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { Node tmpValue = binaryHeap[parentIndex]; binaryHeap[parentIndex] = binaryHeap[bubbleIndex]; binaryHeap[bubbleIndex] = tmpValue; bubbleIndex = parentIndex; } else { return; } } } } } /** Returns a nicely formatted string describing the tree structure. '!!!' marks after a value means that the tree is not correct at that node (i.e it should be swapped with it's parent) */ public override string ToString () { System.Text.StringBuilder text = new System.Text.StringBuilder (); text.Append ("\n=== Writing Binary Heap ===\n"); text.Append ("Number of items: ").Append (numberOfItems-2); text.Append ("Capacity: ").Append (binaryHeap.Length); text.Append ("\n"); if (numberOfItems > 2) { WriteBranch (1,1,text); } text.Append ("\n\n"); return text.ToString (); } /** Writes a branch of the tree to a StringBuilder. Used by #ToString */ private void WriteBranch (int index, int depth, System.Text.StringBuilder text) { text.Append ("\n"); for (int i=0;i<depth;i++) { text.Append (" "); } text.Append (binaryHeap[index].f); if (index > 1) { int parentIndex = index / 2; if (binaryHeap[index].f < binaryHeap[parentIndex].f) { text.Append (" !!!"); } } int p2 = index * 2; if ((p2 + 1) <= numberOfItems) { // Both children exist WriteBranch (p2,depth+1,text); WriteBranch (p2+1,depth+1,text); } else if (p2 <= numberOfItems) { // Only one child exists WriteBranch (p2,depth+1,text); } } } #endif /** Binary heap implementation. Binary heaps are really fast for ordering nodes in a way that makes it possible to get the node with the lowest F score. Also known as a priority queue. * \see http://en.wikipedia.org/wiki/Binary_heap */ public class BinaryHeapM { private NodeRun[] binaryHeap; public int numberOfItems; public float growthFactor = 2; public BinaryHeapM ( int numberOfElements ) { binaryHeap = new NodeRun[numberOfElements]; numberOfItems = 2; } public void Clear () { numberOfItems = 1; } public NodeRun GetNode (int i) { return binaryHeap[i]; } /** Adds a node to the heap */ public void Add(NodeRun node) { if (node == null) throw new System.ArgumentNullException ("Sending null node to BinaryHeap"); if (numberOfItems == binaryHeap.Length) { int newSize = System.Math.Max(binaryHeap.Length+4,(int)System.Math.Round(binaryHeap.Length*growthFactor)); if (newSize > 1<<18) { throw new System.Exception ("Binary Heap Size really large (2^18). A heap size this large is probably the cause of pathfinding running in an infinite loop. " + "\nRemove this check (in BinaryHeap.cs) if you are sure that it is not caused by a bug"); } NodeRun[] tmp = new NodeRun[newSize]; for (int i=0;i<binaryHeap.Length;i++) { tmp[i] = binaryHeap[i]; } #if ASTARDEBUG Debug.Log ("Resizing binary heap to "+newSize); #endif binaryHeap = tmp; //Debug.Log ("Forced to discard nodes because of binary heap size limit, please consider increasing the size ("+numberOfItems +" "+binaryHeap.Length+")"); //numberOfItems--; } binaryHeap[numberOfItems] = node; //node.heapIndex = numberOfItems;//Heap index int bubbleIndex = numberOfItems; uint nodeF = node.f; while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; if (nodeF < binaryHeap[parentIndex].f) { //binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { /* \todo Wouldn't it be more efficient with '<' instead of '<=' ? * / //Node tmpValue = binaryHeap[parentIndex]; //tmpValue.heapIndex = bubbleIndex;//HeapIndex binaryHeap[bubbleIndex] = binaryHeap[parentIndex]; binaryHeap[parentIndex] = node;//binaryHeap[bubbleIndex]; //binaryHeap[bubbleIndex].heapIndex = bubbleIndex; //Heap index //binaryHeap[parentIndex].heapIndex = parentIndex; //Heap index bubbleIndex = parentIndex; } else { /*if (binaryHeap[bubbleIndex].f <= binaryHeap[parentIndex].f) { /* \todo Wouldn't it be more efficient with '<' instead of '<=' ? * Node tmpValue = binaryHeap[parentIndex]; //tmpValue.heapIndex = bubbleIndex;//HeapIndex binaryHeap[parentIndex] = binaryHeap[bubbleIndex]; binaryHeap[bubbleIndex] = tmpValue; bubbleIndex = parentIndex; } else {*/ break; } } numberOfItems++; } /** Returns the node with the lowest F score from the heap */ public NodeRun Remove() { numberOfItems--; NodeRun returnItem = binaryHeap[1]; //returnItem.heapIndex = 0;//Heap index binaryHeap[1] = binaryHeap[numberOfItems]; //binaryHeap[1].heapIndex = 1;//Heap index int swapItem = 1, parent = 1; do { parent = swapItem; int p2 = parent * 2; if (p2 + 1 <= numberOfItems) { // Both children exist if (binaryHeap[parent].f >= binaryHeap[p2].f) { swapItem = p2;//2 * parent; } if (binaryHeap[swapItem].f >= binaryHeap[p2 + 1].f) { swapItem = p2 + 1; } } else if ((p2) <= numberOfItems) { // Only one child exists if (binaryHeap[parent].f >= binaryHeap[p2].f) { swapItem = p2; } } // One if the parent's children are smaller or equal, swap them if (parent != swapItem) { NodeRun tmpIndex = binaryHeap[parent]; //tmpIndex.heapIndex = swapItem;//Heap index binaryHeap[parent] = binaryHeap[swapItem]; binaryHeap[swapItem] = tmpIndex; //binaryHeap[parent].heapIndex = parent;//Heap index } } while (parent != swapItem); return returnItem; } /** Rebuilds the heap by trickeling down all items. * Usually called after the hTarget on a path has been changed */ public void Rebuild () { #if ASTARDEBUG int changes = 0; #endif for (int i=2;i<numberOfItems;i++) { int bubbleIndex = i; NodeRun node = binaryHeap[i]; uint nodeF = node.f; while (bubbleIndex != 1) { int parentIndex = bubbleIndex / 2; if (nodeF < binaryHeap[parentIndex].f) { //Node tmpValue = binaryHeap[parentIndex]; binaryHeap[bubbleIndex] = binaryHeap[parentIndex]; binaryHeap[parentIndex] = node; bubbleIndex = parentIndex; #if ASTARDEBUG changes++; #endif } else { break; } } } #if ASTARDEBUG Debug.Log ("+++ Rebuilt Heap - "+changes+" changes +++"); #endif } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls.Primitives; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using MS.Internal.KnownBoxes; // Disable CS3001: Warning as Error: not CLS-compliant #pragma warning disable 3001 namespace System.Windows.Controls.Primitives { /// <summary> /// ToggleButton /// </summary> [DefaultEvent("Checked")] public class ToggleButton : ButtonBase { #region Constructors static ToggleButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleButton), new FrameworkPropertyMetadata(typeof(ToggleButton))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(ToggleButton)); } /// <summary> /// Default ToggleButton constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public ToggleButton() : base() { } #endregion #region Properties and Events /// <summary> /// Checked event /// </summary> public static readonly RoutedEvent CheckedEvent = EventManager.RegisterRoutedEvent("Checked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToggleButton)); /// <summary> /// Unchecked event /// </summary> public static readonly RoutedEvent UncheckedEvent = EventManager.RegisterRoutedEvent("Unchecked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToggleButton)); /// <summary> /// Indeterminate event /// </summary> public static readonly RoutedEvent IndeterminateEvent = EventManager.RegisterRoutedEvent("Indeterminate", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToggleButton)); /// <summary> /// Add / Remove Checked handler /// </summary> [Category("Behavior")] public event RoutedEventHandler Checked { add { AddHandler(CheckedEvent, value); } remove { RemoveHandler(CheckedEvent, value); } } /// <summary> /// Add / Remove Unchecked handler /// </summary> [Category("Behavior")] public event RoutedEventHandler Unchecked { add { AddHandler(UncheckedEvent, value); } remove { RemoveHandler(UncheckedEvent, value); } } /// <summary> /// Add / Remove Indeterminate handler /// </summary> [Category("Behavior")] public event RoutedEventHandler Indeterminate { add { AddHandler(IndeterminateEvent, value); } remove { RemoveHandler(IndeterminateEvent, value); } } /// <summary> /// The DependencyProperty for the IsChecked property. /// Flags: BindsTwoWayByDefault /// Default Value: false /// </summary> public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool?), typeof(ToggleButton), new FrameworkPropertyMetadata( BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, new PropertyChangedCallback(OnIsCheckedChanged))); /// <summary> /// Indicates whether the ToggleButton is checked /// </summary> [Category("Appearance")] [TypeConverter(typeof(NullableBoolConverter))] [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public bool? IsChecked { get { // Because Nullable<bool> unboxing is very slow (uses reflection) first we cast to bool object value = GetValue(IsCheckedProperty); if (value == null) return new Nullable<bool>(); else return new Nullable<bool>((bool)value); } set { SetValue(IsCheckedProperty, value.HasValue ? BooleanBoxes.Box(value.Value) : null); } } private static object OnGetIsChecked(DependencyObject d) {return ((ToggleButton)d).IsChecked;} /// <summary> /// Called when IsChecked is changed on "d." /// </summary> /// <param name="d">The object on which the property was changed.</param> /// <param name="e">EventArgs that contains the old and new values for this property</param> private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ToggleButton button = (ToggleButton)d; bool? oldValue = (bool?) e.OldValue; bool? newValue = (bool?) e.NewValue; //doing soft casting here because the peer can be that of RadioButton and it is not derived from //ToggleButtonAutomationPeer - specifically to avoid implementing TogglePattern ToggleButtonAutomationPeer peer = UIElementAutomationPeer.FromElement(button) as ToggleButtonAutomationPeer; if (peer != null) { peer.RaiseToggleStatePropertyChangedEvent(oldValue, newValue); } if (newValue == true) { button.OnChecked(new RoutedEventArgs(CheckedEvent)); } else if (newValue == false) { button.OnUnchecked(new RoutedEventArgs(UncheckedEvent)); } else { button.OnIndeterminate(new RoutedEventArgs(IndeterminateEvent)); } button.UpdateVisualState(); } /// <summary> /// Called when IsChecked becomes true. /// </summary> /// <param name="e">Event arguments for the routed event that is raised by the default implementation of this method.</param> protected virtual void OnChecked(RoutedEventArgs e) { RaiseEvent(e); } /// <summary> /// Called when IsChecked becomes false. /// </summary> /// <param name="e">Event arguments for the routed event that is raised by the default implementation of this method.</param> protected virtual void OnUnchecked(RoutedEventArgs e) { RaiseEvent(e); } /// <summary> /// Called when IsChecked becomes null. /// </summary> /// <param name="e">Event arguments for the routed event that is raised by the default implementation of this method.</param> protected virtual void OnIndeterminate(RoutedEventArgs e) { RaiseEvent(e); } /// <summary> /// The DependencyProperty for the IsThreeState property. /// Flags: None /// Default Value: false /// </summary> public static readonly DependencyProperty IsThreeStateProperty = DependencyProperty.Register( "IsThreeState", typeof(bool), typeof(ToggleButton), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// The IsThreeState property determines whether the control supports two or three states. /// IsChecked property can be set to null as a third state when IsThreeState is true /// </summary> [Bindable(true), Category("Behavior")] public bool IsThreeState { get { return (bool) GetValue(IsThreeStateProperty); } set { SetValue(IsThreeStateProperty, BooleanBoxes.Box(value)); } } #endregion #region Override methods /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new ToggleButtonAutomationPeer(this); } /// <summary> /// This override method is called when the control is clicked by mouse or keyboard /// </summary> protected override void OnClick() { OnToggle(); base.OnClick(); } #endregion #region Method Overrides internal override void ChangeVisualState(bool useTransitions) { base.ChangeVisualState(useTransitions); // Update the Check state group var isChecked = IsChecked; if (isChecked == true) { VisualStateManager.GoToState(this, VisualStates.StateChecked, useTransitions); } else if (isChecked == false) { VisualStateManager.GoToState(this, VisualStates.StateUnchecked, useTransitions); } else { // isChecked is null VisualStates.GoToState(this, useTransitions, VisualStates.StateIndeterminate, VisualStates.StateUnchecked); } } /// <summary> /// Gives a string representation of this object. /// </summary> public override string ToString() { string typeText = this.GetType().ToString(); string contentText = String.Empty; bool? isChecked = false; bool valuesDefined = false; // Accessing ToggleButton properties may be thread sensitive if (CheckAccess()) { contentText = GetPlainText(); isChecked = IsChecked; valuesDefined = true; } else { //Not on dispatcher, try posting to the dispatcher with 20ms timeout Dispatcher.Invoke(DispatcherPriority.Send, new TimeSpan(0, 0, 0, 0, 20), new DispatcherOperationCallback(delegate(object o) { contentText = GetPlainText(); isChecked = IsChecked; valuesDefined = true; return null; }), null); } // If Content and isChecked are defined if (valuesDefined) { return SR.Get(SRID.ToStringFormatString_ToggleButton, typeText, contentText, isChecked.HasValue ? isChecked.Value.ToString() : "null"); } // Not able to access the dispatcher return typeText; } #endregion #region Protected virtual methods /// <summary> /// This vitrual method is called from OnClick(). ToggleButton toggles IsChecked property. /// Subclasses can override this method to implement their own toggle behavior /// </summary> protected internal virtual void OnToggle() { // If IsChecked == true && IsThreeState == true ---> IsChecked = null // If IsChecked == true && IsThreeState == false ---> IsChecked = false // If IsChecked == false ---> IsChecked = true // If IsChecked == null ---> IsChecked = false bool? isChecked; if (IsChecked == true) isChecked = IsThreeState ? (bool?)null : (bool?)false; else // false or null isChecked = IsChecked.HasValue; // HasValue returns true if IsChecked==false SetCurrentValueInternal(IsCheckedProperty, isChecked); } #endregion #region Data #endregion #region Accessibility #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace MiaPlaza.ExpressionUtils.Evaluating { using ParameterMap = IReadOnlyDictionary<ParameterExpression, object>; /// <summary> /// An evaluator that visits the expression tree and determines every operations result via /// reflection / dynamic. /// </summary> /// <remarks> /// While the delegates from this technique are quite slow, the overall interpretation-process /// takes less time than any other method. The <see cref="ExpressionInterpreter"/> is as of /// now quite limited in the expressions it can evaluate, but it suffices in general. /// </remarks> public class ExpressionInterpreter : IExpressionEvaluator { public static ExpressionInterpreter Instance = new ExpressionInterpreter(); private ExpressionInterpreter() { } private static readonly ParameterMap emptyMap = new Dictionary<ParameterExpression, object>(); object IExpressionEvaluator.Evaluate(Expression unparametrizedExpression) => Interpret(unparametrizedExpression); public object Interpret(Expression exp) { try { return new ExpressionInterpretationVisitor(emptyMap).GetResultFromExpression(exp); } catch (Exception e) { throw new DynamicEvaluationException(exp, e); } } DELEGATE IExpressionEvaluator.EvaluateTypedLambda<DELEGATE>(Expression<DELEGATE> expression) => InterpretTypedLambda(expression); public DELEGATE InterpretTypedLambda<DELEGATE>(Expression<DELEGATE> expression) where DELEGATE : class => InterpretLambda(expression).WrapDelegate<DELEGATE>(); VariadicArrayParametersDelegate IExpressionEvaluator.EvaluateLambda(LambdaExpression lambdaExpression) => InterpretLambda(lambdaExpression); public VariadicArrayParametersDelegate InterpretLambda(LambdaExpression lambda) => args => { var parameters = new Dictionary<ParameterExpression, object>(); for (int i = 0; i < lambda.Parameters.Count; ++i) { parameters[lambda.Parameters[i]] = args[i]; } try { return new ExpressionInterpretationVisitor(parameters).GetResultFromExpression(lambda.Body); } catch (Exception e) { throw new DynamicEvaluationException(lambda, e); } }; class ExpressionInterpretationVisitor : ExpressionResultVisitor<object> { readonly ParameterMap parameters; public ExpressionInterpretationVisitor(ParameterMap parameters) { this.parameters = parameters; } public override object GetResultFromExpression(Expression exp) { if (exp == null) { return null; } return base.GetResultFromExpression(exp); } protected override object GetResultFromBinary(BinaryExpression exp) { dynamic left = GetResultFromExpression(exp.Left); if (exp.Method != null) { return exp.Method.Invoke(null, new[] { left, GetResultFromExpression(exp.Right) }); } else { switch (exp.NodeType) { case ExpressionType.AndAlso: return (bool)left && (bool)GetResultFromExpression(exp.Right); case ExpressionType.OrElse: return (bool)left || (bool)GetResultFromExpression(exp.Right); case ExpressionType.Coalesce: return left ?? GetResultFromExpression(exp.Right); default: break; } dynamic right = GetResultFromExpression(exp.Right); switch (exp.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: return left + right; case ExpressionType.Subtract: case ExpressionType.SubtractChecked: return left - right; case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: return left * right; case ExpressionType.Divide: return left / right; case ExpressionType.Modulo: return left % right; case ExpressionType.ExclusiveOr: return left ^ right; case ExpressionType.And: return left & right; case ExpressionType.Or: return left | right; case ExpressionType.LessThan: return left < right; case ExpressionType.LessThanOrEqual: return left <= right; case ExpressionType.Equal: return left == right; case ExpressionType.NotEqual: return left != right; case ExpressionType.GreaterThanOrEqual: return left >= right; case ExpressionType.GreaterThan: return left > right; case ExpressionType.LeftShift: return left << right; case ExpressionType.RightShift: return left >> right; case ExpressionType.ArrayIndex: return left.GetValue(right); default: throw new NotImplementedException(exp.NodeType.ToString()); } } } protected override object GetResultFromBlock(BlockExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromCatchBlock(CatchBlock exp) { throw new NotImplementedException(); } protected override object GetResultFromConditional(ConditionalExpression exp) { if ((bool)GetResultFromExpression(exp.Test)) { return GetResultFromExpression(exp.IfTrue); } else { return GetResultFromExpression(exp.IfFalse); } } protected override object GetResultFromConstant(ConstantExpression exp) => exp.Value; protected override object GetResultFromDebugInfo(DebugInfoExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromDefault(DefaultExpression exp) { throw new NotImplementedException("Should never be necessary in expressions."); } protected override object GetResultFromDynamic(DynamicExpression exp) { throw new NotSupportedException("No need for dynamic in expressions."); } protected override object GetResultFromElementInit(ElementInit exp) { throw new NotImplementedException(); } protected override object GetResultFromExtension(Expression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromGoto(GotoExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromIndex(IndexExpression exp) { var obj = GetResultFromExpression(exp.Object); if (exp.Indexer != null) { var indices = exp.Arguments .Select(a => GetResultFromExpression(a)) .ToArray(); return exp.Indexer.GetValue(obj, indices); } else if (obj is Array) { if (exp.Arguments[0].Type == typeof(long)) { // All array access indices must have same type! var indices = exp.Arguments .Select(a => (long)GetResultFromExpression(a)) .ToArray(); return ((Array)obj).GetValue(indices); } else { // .. and it's either long or int. var indices = exp.Arguments .Select(a => (int)GetResultFromExpression(a)) .ToArray(); return ((Array)obj).GetValue(indices); } } else { throw new NotSupportedException("Unknown index-access!"); } } protected override object GetResultFromInvocation(InvocationExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromLabel(LabelExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromLabelTarget(LabelTarget exp) { throw new NotImplementedException(); } protected override object GetResultFromLambda<D>(Expression<D> exp) { return exp; } protected override object GetResultFromListInit(ListInitExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromLoop(LoopExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromMember(MemberExpression exp) { var obj = GetResultFromExpression(exp.Expression); if (exp.Member is PropertyInfo) { return ((PropertyInfo)exp.Member).GetValue(obj); } else if (exp.Member is FieldInfo) { return ((FieldInfo)exp.Member).GetValue(obj); } else { throw new InvalidOperationException("There are only fields and properties"); } } protected override object GetResultFromMemberInit(MemberInitExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromMethodCall(MethodCallExpression exp) { var obj = GetResultFromExpression(exp.Object); var arguments = exp.Arguments .Select(a => GetResultFromExpression(a)) .ToArray(); return exp.Method.Invoke(obj, arguments); } protected override object GetResultFromNew(NewExpression exp) { var args = exp.Arguments .Select(a => GetResultFromExpression(a)) .ToArray(); return exp.Constructor.Invoke(args); } protected override object GetResultFromNewArray(NewArrayExpression exp) { var array = Array.CreateInstance(exp.Type.GetElementType(), exp.Expressions.Count); for (int i = 0; i < array.Length; ++i) { array.SetValue(value: GetResultFromExpression(exp.Expressions[i]), index: i); } return array; } protected override object GetResultFromParameter(ParameterExpression exp) => parameters[exp]; protected override object GetResultFromRuntimeVariables(RuntimeVariablesExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromSwitch(SwitchExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromSwitchCase(SwitchCase exp) { throw new NotImplementedException(); } protected override object GetResultFromTry(TryExpression exp) { throw new NotSupportedException("Not supported by expressions as of now."); } protected override object GetResultFromTypeBinary(TypeBinaryExpression exp) { throw new NotImplementedException("Never encountered any of these."); } protected override object GetResultFromUnary(UnaryExpression exp) { dynamic op = GetResultFromExpression(exp.Operand); if (exp.Method != null) { return exp.Method.Invoke(null, new[] { op }); } else { switch (exp.NodeType) { case ExpressionType.Not: return !op; case ExpressionType.Negate: return -op; case ExpressionType.OnesComplement: return ~op; case ExpressionType.UnaryPlus: return +op; case ExpressionType.Quote: return unquote((LambdaExpression)op); case ExpressionType.ConvertChecked: return convert(op, exp.Type); case ExpressionType.Convert: return uncheckedConvert(op, exp.Type); case ExpressionType.TypeAs: { if (exp.Type.IsAssignableFrom(exp.Operand.Type)) { return exp.Operand; } else { return null; } } default: throw new NotImplementedException(exp.NodeType.ToString()); } } } LambdaExpression unquote(LambdaExpression quotedLambda) { if (parameters.Count == 0) { return quotedLambda; } else { return (LambdaExpression)ParameterSubstituter.SubstituteParameter( quotedLambda, parameters.ToDictionary(kvp => kvp.Key, kvp => (Expression)Expression.Constant(kvp.Value))); } } static readonly Predicate<Type> numericTypes = new HashSet<Type>() { typeof(byte), typeof(sbyte), typeof(ushort), typeof(short), typeof(uint), typeof(int), typeof(ulong), typeof(long), }.Contains; static readonly Predicate<Type> unsignedTypes = new HashSet<Type>() { typeof(byte), typeof(ushort), typeof(uint), typeof(ulong), }.Contains; static readonly IReadOnlyDictionary<Type, dynamic> maxValues = new Dictionary<Type, dynamic>() { { typeof(byte), byte.MaxValue }, { typeof(sbyte), sbyte.MaxValue }, { typeof(ushort), ushort.MaxValue }, { typeof(short), short.MaxValue }, { typeof(uint), uint.MaxValue }, { typeof(int), int.MaxValue }, { typeof(ulong), ulong.MaxValue }, { typeof(long), long.MaxValue }, }; private static object uncheckedConvert(dynamic original, Type target) { if (original == null) { if (target.IsValueType && Nullable.GetUnderlyingType(target) == null) { throw new InvalidCastException($"Cannot assign null to {target.FullName}."); } return null; } if (numericTypes(original.GetType()) && numericTypes(target)) { dynamic maxValue; if (maxValues.TryGetValue(target, out maxValue)) { if (original > maxValue) { original %= maxValue + 1; } else if (unsignedTypes(target)) { if (original < 0) { original %= maxValue + 1; //.net modulo returns negative results for negative input, applying // the mathematical mod operation on the absolute value. original += maxValue + 1; } } } } return convert(original, target); } private static object convert(object original, Type target) { if (original == null) { if (target.IsValueType && Nullable.GetUnderlyingType(target) == null) { throw new InvalidCastException($"Cannot assign null to {target.FullName}."); } return null; } if (Nullable.GetUnderlyingType(target) != null) { original = convert(original, Nullable.GetUnderlyingType(target)); } if (target.IsAssignableFrom(original.GetType())) { return original; } else { try { return Convert.ChangeType(original, target); } catch (OverflowException ex) { throw new OverflowException($"Value: {original}", ex); } } } } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class Tile2D : MonoBehaviour { public Texture tileTexture; public string tileName; //Used to identify sprites when creating tiles in the editor public string tileType; //Tile with the same tileType will trigger automatic sprite changes public float tileSize = 1f; //Used in cases where tiles are not using the standard 1 Unity unit scale public bool passive; //When enabled neighbouring tiles will not autotile based on it. public bool disableColliderOnAwake; //Disable collider when game starts, used mostly on background and foreground objects. //TileTool2D uses physics to check for close by tiles, all tiles must have colliders for this functionality. public ParticleSystem particles; public Tile2DAttachment[] attachments; //In case a sprite needs custom gameobjects containing for example extra colliders, animations or other components. public Tile2DAttachment currentAttachment; [HideInInspector] public string tileSprite; //Contains the side name of this tile ("N" is north tile for example) //Used to identify tiles when adding attachments public Sprite thumbnail; //Sprite used for preview thumbnail in TileTool2D public bool hideInHierarchy; //Tile sprites //These are the most common tiles used in platformers public Sprite[] tileA; public Sprite[] tileC; public Sprite[] tileCE; public Sprite[] tileCN; public Sprite[] tileCS; public Sprite[] tileCW; public Sprite[] tileE; public Sprite[] tileN; public Sprite[] tileNE; public Sprite[] tileNS; public Sprite[] tileNW; public Sprite[] tileS; public Sprite[] tileSE; public Sprite[] tileSW; public Sprite[] tileW; public Sprite[] tileWE; //Corner tile sprites (optinal sprites) public Sprite[] tileCNW; public Sprite[] tileCNE; public Sprite[] tileCSE; public Sprite[] tileCSW; public Sprite[] tileCWE; public Sprite[] tileCNS; public Sprite[] tileCSN; public Sprite[] tileCEW; //Advanced tile sprites (optional sprites) public Sprite[] tileCWNN; public Sprite[] tileCNEE; public Sprite[] tileCSWW; public Sprite[] tileCESS; public Sprite[] tileCNSS; public Sprite[] tileCENN; public Sprite[] tileCWSS; public Sprite[] tileCSEE; public Sprite[] tileSENW; public Sprite[] tileSWNE; public Sprite[] tileNESW; public Sprite[] tileNWSE; public Sprite[] tileCNWE; public Sprite[] tileCENS; public Sprite[] tileCSWE; public Sprite[] tileCWNS; public Sprite[] tileCENSW; public Sprite[] tileCSWEN; public Sprite[] tileCNWES; public Sprite[] tileCWNSE; public Sprite[] tileCNWSE; public Sprite[] tileCNESW; public Sprite[] tileCNSWE; //Close by tiles //These will determine what sprite to use public Tile2D nTile; public Tile2D eTile; public Tile2D sTile; public Tile2D wTile; public Tile2D nwTile; public Tile2D neTile; public Tile2D seTile; public Tile2D swTile; //Cached components public SpriteRenderer cacheRenderer; public Collider2D cacheCollider; public int sortingOrder; [HideInInspector] public Collider2D[] tiles; //public string SpriteNumberToName(int n) { // string r = ""; // if (n == 0) r = "A"; // else if (n == 1) r = "W"; // else if (n == 2) r = "NS"; // else if (n == 3) r = "E"; // else if (n == 4) r = "C"; // else if (n == 5) r = "CN"; // else if (n == 6) r = "CS"; // else if (n == 7) r = "NW"; // else if (n == 8) r = "NE"; // else if (n == 9) r = "N"; // else if (n == 10) r = "CSE"; // else if (n == 11) r = "CSWE"; // else if (n == 12) r = "CSW"; // else if (n == 13) r = "CWE"; // else if (n == 14) r = "CW"; // else if (n == 15) r = "CE"; // else if (n == 16) r = "WE"; // else if (n == 17) r = "CENS"; // else if (n == 18) r = "CNSWE"; // else if (n == 19) r = "CWNS"; // else if (n == 20) r = "CEW"; // else if (n == 21) r = "SW"; // else if (n == 22) r = "SE"; // else if (n == 23) r = "S"; // else if (n == 24) r = "CNE"; // else if (n == 25) r = "CNWE"; // else if (n == 26) r = "CNW"; // else if (n == 27) r = "CNS"; // else if (n == 28) r = "NWSE"; // else if (n == 29) r = "NESW"; // else if (n == 30) r = "CWSS"; // else if (n == 31) r = "CESS"; // else if (n == 32) r = "CNEE"; // else if (n == 33) r = "CNSS"; // else if (n == 34) r = "CSN"; // else if (n == 35) r = "SWNE"; // else if (n == 36) r = "SENW"; // else if (n == 37) r = "CWNN"; // else if (n == 38) r = "CENN"; // else if (n == 39) r = "CSEE"; // else if (n == 40) r = "CSWW"; // else if (n == 41) r = "CNWSE"; // else if (n == 42) r = "CNESW"; // else if (n == 43) r = "CENSW"; // else if (n == 44) r = "CNWES"; // else if (n == 45) r = "CSWEN"; // else if (n == 46) r = "CWNSE"; // return r; //} //#if UNITY_EDITOR // public void NewArray(string s, int length) { // if(s == "tileA") tileA = new Sprite[length]; // else if(s == "tileC") tileC= new Sprite[length]; // else if(s == "tileCE") tileCE= new Sprite[length]; // else if(s == "tileCN") tileCN= new Sprite[length]; // else if(s == "tileCS") tileCS= new Sprite[length]; // else if(s == "tileCW") tileCW= new Sprite[length]; // else if(s == "tileE") tileE= new Sprite[length]; // else if(s == "tileN") tileN = new Sprite[length]; // else if(s == "tileNE") tileNE = new Sprite[length]; // else if(s == "tileNS") tileNS = new Sprite[length]; // else if(s == "tileNW") tileNW= new Sprite[length]; // else if(s == "tileS") tileS= new Sprite[length]; // else if(s == "tileSE") tileSE= new Sprite[length]; // else if(s == "tileSW") tileSW= new Sprite[length]; // else if(s == "tileW") tileW= new Sprite[length]; // else if(s == "tileWE") tileWE= new Sprite[length]; // else if(s == "tileCNW") tileCNW= new Sprite[length]; // else if(s == "tileCNE") tileCNE= new Sprite[length]; // else if(s == "tileCSE") tileCSE= new Sprite[length]; // else if(s == "tileCSW") tileCSW= new Sprite[length]; // else if(s == "tileCWE") tileCWE= new Sprite[length]; // else if(s == "tileCNS") tileCNS= new Sprite[length]; // else if(s == "tileCSN") tileCSN= new Sprite[length]; // else if(s == "tileCEW") tileCEW= new Sprite[length]; // else if(s == "tileCWNN") tileCWNN= new Sprite[length]; // else if(s == "tileCNEE") tileCNEE= new Sprite[length]; // else if(s == "tileCSWW") tileCSWW= new Sprite[length]; // else if(s == "tileCESS") tileCESS= new Sprite[length]; // else if(s == "tileCNSS") tileCNSS= new Sprite[length]; // else if(s == "tileCENN") tileCENN= new Sprite[length]; // else if(s == "tileCWSS") tileCWSS= new Sprite[length]; // else if(s == "tileCSEE") tileCSEE= new Sprite[length]; // else if(s == "tileSENW") tileSENW= new Sprite[length]; // else if(s == "tileSWNE") tileSWNE= new Sprite[length]; // else if(s == "tileNESW") tileNESW= new Sprite[length]; // else if(s == "tileNWSE") tileNWSE= new Sprite[length]; // else if(s == "tileCNWE") tileCNWE= new Sprite[length]; // else if(s == "tileCENS") tileCENS= new Sprite[length]; // else if(s == "tileCSWE") tileCSWE= new Sprite[length]; // else if(s == "tileCWNS") tileCWNS= new Sprite[length]; // else if(s == "tileCENSW") tileCENSW= new Sprite[length]; // else if(s == "tileCSWEN") tileCSWEN= new Sprite[length]; // else if(s == "tileCNWES") tileCNWES= new Sprite[length]; // else if(s == "tileCWNSE") tileCWNSE= new Sprite[length]; // else if(s == "tileCNWSE") tileCNWSE= new Sprite[length]; // else if(s == "tileCNESW") tileCNESW= new Sprite[length]; // else if(s == "tileCNSWE") tileCNSWE= new Sprite[length]; //} //#endif //Function to destroy a tile in run time. public void DestroyTile() { if (nTile != null) nTile.DestroyedTile(this); if (eTile != null) eTile.DestroyedTile(this); if (sTile != null) sTile.DestroyedTile(this); if (wTile != null) wTile.DestroyedTile(this); if (nwTile != null) nwTile.DestroyedTile(this); if (neTile != null) neTile.DestroyedTile(this); if (seTile != null) seTile.DestroyedTile(this); if (swTile != null) swTile.DestroyedTile(this); Destroy(gameObject); if (!disableColliderOnAwake) { BeautifyCloseByTiles(false, false); return; } Debug.LogWarning("Destroying objects with disabled collider has no effect on other tiles"); } public void Awake() { CacheComponents(); //FindTiles(); DisableColliderOnAwake(); if (particles) particles.GetComponent<Renderer>().sortingOrder = cacheRenderer.sortingOrder+1; } public void CacheComponents() { if (cacheCollider == null) cacheCollider = GetComponent<Collider2D>(); if (cacheRenderer == null) cacheRenderer = GetComponent<SpriteRenderer>(); } public void DisableColliderOnAwake() { if (disableColliderOnAwake && cacheCollider) cacheCollider.enabled = false; } void DestroyedTile(Tile2D t) { if (nTile != null && nTile == t) nTile = null; if (eTile != null && eTile == t) eTile = null; if (sTile != null && sTile == t) sTile = null; if (wTile != null && wTile == t) wTile = null; if (nwTile != null && nwTile == t) nwTile = null; if (neTile != null && neTile == t) neTile = null; if (seTile != null && seTile == t) seTile = null; if (swTile != null && swTile == t) swTile = null; } public void BeautifyCloseByTiles(bool enableUndo, bool enablePhysics) { #if UNITY_EDITOR if (!Application.isPlaying) { if (nTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(nTile.gameObject, "TileTool2D: Magic"); nTile.FindTiles(enablePhysics); } if (eTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(eTile.gameObject, "TileTool2D: Magic"); eTile.FindTiles(enablePhysics); } if (sTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(sTile.gameObject, "TileTool2D: Magic"); sTile.FindTiles(enablePhysics); } if (wTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(wTile.gameObject, "TileTool2D: Magic"); wTile.FindTiles(enablePhysics); } if (nwTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(nwTile.gameObject, "TileTool2D: Magic"); nwTile.FindTiles(enablePhysics); } if (neTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(neTile.gameObject, "TileTool2D: Magic"); neTile.FindTiles(enablePhysics); } if (seTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(seTile.gameObject, "TileTool2D: Magic"); seTile.FindTiles(enablePhysics); } if (swTile != null) { if (enableUndo) Undo.RegisterCompleteObjectUndo(swTile.gameObject, "TileTool2D: Magic"); swTile.FindTiles(enablePhysics); } } #endif //Swap tiles in the nearby tile if (nTile != null) nTile.Beautify(); if (eTile != null) eTile.Beautify(); if (sTile != null) sTile.Beautify(); if (wTile != null) wTile.Beautify(); if (nwTile != null) nwTile.Beautify(); if (neTile != null) neTile.Beautify(); if (seTile != null) seTile.Beautify(); if (swTile != null) swTile.Beautify(); //Add attachements to nearby tiles if (nTile != null) nTile.AddAttachment(); if (eTile != null) eTile.AddAttachment(); if (sTile != null) sTile.AddAttachment(); if (wTile != null) wTile.AddAttachment(); if (nwTile != null) nwTile.AddAttachment(); if (neTile != null) neTile.AddAttachment(); if (seTile != null) seTile.AddAttachment(); if (swTile != null) swTile.AddAttachment(); } public void CheckIt(bool enableUndo, bool enablePhysics) { //BeautifyCloseByTiles(); // Find new close by tiles FindTiles(enablePhysics); // Swap sprites based on close by tiles Beautify(); // Find and add attachment AddAttachment(); //Fix new close by tiles BeautifyCloseByTiles(enableUndo, enablePhysics); } public void FindTiles(bool enablePhysics) { nwTile = neTile = seTile = swTile= nTile = eTile = sTile = wTile = null; float overLapSize = 2f * tileSize; int layer = cacheRenderer.sortingLayerID; if (enablePhysics) { if (layer != 0) tiles = Physics2D.OverlapAreaAll(new Vector2(transform.position.x - overLapSize, transform.position.y - overLapSize), new Vector2(transform.position.x + overLapSize, transform.position.y + overLapSize), cacheRenderer.sortingLayerID); else tiles = Physics2D.OverlapAreaAll(new Vector2(transform.position.x - overLapSize, transform.position.y - overLapSize), new Vector2(transform.position.x + overLapSize, transform.position.y + overLapSize)); for (int i = 0; i < tiles.Length; i++) { Tile2D t = tiles[i].transform.GetComponent<Tile2D>(); if (t != null && t != this) FindTile(t); } } else { for (int i = 0; i < transform.parent.childCount; i++) { Tile2D t = transform.parent.GetChild(i).GetComponent<Tile2D>(); if (t != null && t != this) FindTile(t); } } } public void CheckOverlap(bool enableUndo, bool enablePhysics) { //Only useable in Editor #if UNITY_EDITOR float overLapSize = 2f * tileSize; int layer = cacheRenderer.sortingLayerID; if (enablePhysics) { if (layer != 0) tiles = Physics2D.OverlapAreaAll(new Vector2(transform.position.x - overLapSize, transform.position.y - overLapSize), new Vector2(transform.position.x + overLapSize, transform.position.y + overLapSize), cacheRenderer.sortingLayerID); else tiles = Physics2D.OverlapAreaAll(new Vector2(transform.position.x - overLapSize, transform.position.y - overLapSize), new Vector2(transform.position.x + overLapSize, transform.position.y + overLapSize)); for (int i = 0; i < tiles.Length; i++) { Tile2D t = tiles[i].GetComponent<Tile2D>(); if(t != null) { Transform tt = t.transform; if (t != this && gameObject != null && tt.parent == transform.parent && tt.position.x == transform.position.x && tt.position.y == transform.position.y) { tt.position = new Vector3(9999999.999999f, 9999999.999999f, 0); if (enableUndo) Undo.DestroyObjectImmediate(t.gameObject); else DestroyImmediate(t.gameObject); } } } } else { for (int i = 0; i < transform.parent.childCount; i++) { Tile2D t = transform.parent.GetChild(i).GetComponent<Tile2D>(); if (t != null) { Transform tt = t.transform; if (t != this && gameObject != null && tt.position.x == transform.position.x && tt.position.y == transform.position.y) { tt.position = new Vector3(9999999.999999f, 9999999.999999f, 0); if (enableUndo) Undo.DestroyObjectImmediate(t.gameObject); else DestroyImmediate(t.gameObject); } } } } #endif } public void FindTile(Tile2D t) { Transform tt = t.transform; if (tt.parent != transform.parent) return; // Check if tile is directly above if (tt.position.y == Round(transform.position.y + tileSize, tileSize) && tt.position.x == transform.position.x) { if (!t.passive) nTile = t; #if UNITY_EDITOR if (nTile != null) EditorUtility.SetDirty(nTile); #endif return; } // Check if tile is directly below if (tt.position.y == Round(transform.position.y - tileSize, tileSize) && tt.position.x == transform.position.x) { if (!t.passive) sTile = t; #if UNITY_EDITOR if (sTile != null) EditorUtility.SetDirty(sTile); #endif return; } // Check if tile is directly to the right if (tt.position.x == Round(transform.position.x + tileSize, tileSize) && tt.position.y == transform.position.y) { if (!t.passive) eTile = t; #if UNITY_EDITOR if (eTile != null) EditorUtility.SetDirty(eTile); #endif return; } // Check if tile is directly to the left if (tt.position.x == Round(transform.position.x - tileSize, tileSize) && tt.position.y == transform.position.y) { if (!t.passive) wTile = t; #if UNITY_EDITOR if (wTile != null) EditorUtility.SetDirty(wTile); #endif return; } // Check if tile is north west if (tt.position.x == Round(transform.position.x - tileSize, tileSize) && tt.position.y == Round(transform.position.y + tileSize, tileSize)) { if (!t.passive) nwTile = t; #if UNITY_EDITOR if (nwTile != null) EditorUtility.SetDirty(nwTile); #endif return; } // Check if tile is north east if (tt.position.x == Round(transform.position.x + tileSize, tileSize) && tt.position.y == Round(transform.position.y + tileSize, tileSize)) { if (!t.passive) neTile = t; #if UNITY_EDITOR if (neTile != null) EditorUtility.SetDirty(neTile); #endif return; } // Check if tile is south east if (tt.position.x == Round(transform.position.x + tileSize, tileSize) && tt.position.y == Round(transform.position.y - tileSize, tileSize)) { if (!t.passive) seTile = t; #if UNITY_EDITOR if (seTile != null) EditorUtility.SetDirty(seTile); #endif return; } // Check if tile is south west if (tt.position.x == Round(transform.position.x - tileSize, tileSize) && tt.position.y == Round(transform.position.y - tileSize, tileSize)) { if (!t.passive) swTile = t; #if UNITY_EDITOR if (swTile != null) EditorUtility.SetDirty(swTile); #endif return; } // Check if tile is overlapping (EDITOR ONLY) //#if UNITY_EDITOR // if (gameObject != null && tt.position.x == transform.position.x && tt.position.y == transform.position.y) { // tt.position = new Vector3(9999999.999999f, 9999999.999999f, 0); // //Undo.DestroyObjectImmediate(t.gameObject); // //DestroyImmediate(t.gameObject); // return; // } //#endif // // Check if tile is overlapping // if (gameObject != null && tt.position.x == transform.position.x && tt.position.y == transform.position.y) { // tt.position = new Vector3(9999999.999999f, 9999999.999999f, 0); // Destroy(t.gameObject); // return; // } } public void FindCloseByHighestSortOrder() { int s = 0; if (nTile != null) s = nTile.sortingOrder; if ((eTile != null) && eTile.sortingOrder > s) s = eTile.sortingOrder; if ((sTile != null) && sTile.sortingOrder > s) s = sTile.sortingOrder; if ((wTile != null) && wTile.sortingOrder > s) s = wTile.sortingOrder; sortingOrder = s + 1; } public void FixSortingLayer(int layerIndex) { GetComponent<SpriteRenderer>().sortingOrder = layerIndex + Mathf.Clamp(sortingOrder, -1999, 1999); if (currentAttachment != null) SortAttachment(); //#if UNITY_EDITOR // EditorUtility.SetDirty(this); //#endif } public void FindCloseByLowestSortOrder() { int s = 1000000; if (nTile != null) s = nTile.sortingOrder; if ((eTile != null) && eTile.sortingOrder < s) { s = eTile.sortingOrder; } if ((sTile != null) && sTile.sortingOrder < s) { s = sTile.sortingOrder; } if ((wTile != null) && wTile.sortingOrder < s) { s = wTile.sortingOrder; } if (s == 1000000) s = 0; sortingOrder = s - 1; } public void AddAttachment() { GameObject g = FindAttachment(); if (g == null) { if (currentAttachment) { cacheRenderer.enabled = true; DestroyImmediate(currentAttachment.gameObject); } return; } if (currentAttachment) DestroyImmediate(currentAttachment.gameObject); GameObject ng = null; #if UNITY_EDITOR ng = (GameObject)PrefabUtility.InstantiatePrefab(g); #endif if (Application.isPlaying) ng = (GameObject)Instantiate(g, transform.position, transform.rotation); ng.transform.parent = transform; ng.transform.localPosition = Vector3.zero; currentAttachment = ng.GetComponent<Tile2DAttachment>(); if (currentAttachment.replaceSprite) cacheRenderer.enabled = false; SortAttachment(); } public void SortAttachment() { SpriteRenderer[] s = (SpriteRenderer[])currentAttachment.transform.GetComponents<SpriteRenderer>(); for (int i = 0; i < s.Length; i++) { s[i].sortingOrder = cacheRenderer.sortingOrder; s[i].sortingLayerName = cacheRenderer.sortingLayerName; s[i].sortingLayerID = cacheRenderer.sortingLayerID; } } public GameObject FindAttachment() { GameObject g = null; for(int i = 0; i < attachments.Length; i++) { if(attachments[i].replaceTile == tileSprite) { g = attachments[i].gameObject; break; } } return g; } public float Round(float input, float size) { float snappedValue = 0.0f; snappedValue = size * Mathf.Round((input / size)); return (snappedValue); } public void Beautify() { Tile2D nTileX = null; Tile2D eTileX = null; Tile2D sTileX = null; Tile2D wTileX = null; Tile2D neTileX = null; Tile2D nwTileX = null; Tile2D seTileX = null; Tile2D swTileX = null; if ((nTile != null) && nTile.tileType == tileType) nTileX = nTile; if ((eTile != null) && eTile.tileType == tileType) eTileX = eTile; if ((sTile != null) && sTile.tileType == tileType) sTileX = sTile; if ((wTile != null) && wTile.tileType == tileType) wTileX = wTile; if ((nwTile != null) && nwTile.tileType == tileType) nwTileX = nwTile; if ((neTile != null) && neTile.tileType == tileType) neTileX = neTile; if ((seTile != null) && seTile.tileType == tileType) seTileX = seTile; if ((swTile != null) && swTile.tileType == tileType) swTileX = swTile; if (passive || (nTileX == null) && (eTileX == null) && (sTileX == null) && (wTileX == null) && tileA.Length > 0) cacheRenderer.sprite = tileA[Random.Range(0, tileA.Length)]; //Has a tile at all NESW sides if ((nTileX != null) && (eTileX != null) && (sTileX != null) && (wTileX != null)) { if (swTileX == null && seTileX == null && nwTileX == null && neTileX == null && tileCNSWE.Length > 0) { cacheRenderer.sprite = tileCNSWE[Random.Range(0, tileCNSWE.Length)]; tileSprite = "CNSWE"; return; } if (nwTileX == null && neTileX == null && seTileX == null && tileCENSW.Length > 0) { cacheRenderer.sprite = tileCENSW[Random.Range(0, tileCENSW.Length)]; tileSprite = "CENSW"; return; } if (nwTileX == null && neTileX == null && swTileX == null && tileCNWES.Length > 0) { cacheRenderer.sprite = tileCNWES[Random.Range(0, tileCNWES.Length)]; tileSprite = "CNWES"; return; } if(neTileX == null && seTileX == null && swTileX == null && tileCSWEN.Length > 0) { cacheRenderer.sprite = tileCSWEN[Random.Range(0, tileCSWEN.Length)]; tileSprite = "CSWEN"; return; } if (nwTileX == null && seTileX == null && swTileX == null && tileCWNSE.Length > 0) { cacheRenderer.sprite = tileCWNSE[Random.Range(0, tileCWNSE.Length)]; tileSprite = "CWNSE"; return; } if (nwTileX == null && seTileX == null && tileCNWSE.Length > 0) { cacheRenderer.sprite = tileCNWSE[Random.Range(0, tileCNWSE.Length)]; tileSprite = "CNWSE"; return; } if (neTileX == null && swTileX == null && tileCNESW.Length > 0) { cacheRenderer.sprite = tileCNESW[Random.Range(0, tileCNESW.Length)]; tileSprite = "CNESW"; return; } if (nwTileX == null && neTileX == null && tileCNWE.Length > 0) { cacheRenderer.sprite = tileCNWE[Random.Range(0, tileCNWE.Length)]; tileSprite = "CNWE"; return; } if (seTileX == null && neTileX == null && tileCENS.Length > 0) { cacheRenderer.sprite = tileCENS[Random.Range(0, tileCENS.Length)]; tileSprite = "CENS"; return; } if (seTileX == null && swTileX == null && tileCSWE.Length > 0) { cacheRenderer.sprite = tileCSWE[Random.Range(0, tileCSWE.Length)]; tileSprite = "CSWE"; return; } if (nwTileX == null && swTileX == null && tileCWNS.Length > 0) { cacheRenderer.sprite = tileCWNS[Random.Range(0, tileCWNS.Length)]; tileSprite = "CWNS"; return; } if (nwTileX == null && tileCNW.Length > 0) { cacheRenderer.sprite = tileCNW[Random.Range(0, tileCNW.Length)]; tileSprite = "CNW"; return; } if (neTileX == null && tileCNE.Length > 0) { cacheRenderer.sprite = tileCNE[Random.Range(0, tileCNE.Length)]; tileSprite = "CNE"; return; } if (seTileX == null && tileCSE.Length > 0) { cacheRenderer.sprite = tileCSE[Random.Range(0, tileCSE.Length)]; tileSprite = "CSE"; return; } if (swTileX == null && tileCSW.Length > 0) { cacheRenderer.sprite = tileCSW[Random.Range(0, tileCSW.Length)]; tileSprite = "CSW"; return; } if (tileC.Length > 0) { cacheRenderer.sprite = tileC[Random.Range(0, tileC.Length)]; tileSprite = "C"; return; } } if ((nTileX == null) && (eTileX != null) && (sTileX != null) && (wTileX != null)) { if (seTileX == null && swTileX == null && tileCNS.Length > 0) { cacheRenderer.sprite = tileCNS[Random.Range(0, tileCNS.Length)]; tileSprite = "CNS"; return; } if (seTileX == null && tileCNEE.Length > 0) { cacheRenderer.sprite = tileCNEE[Random.Range(0, tileCNEE.Length)]; tileSprite = "CNEE"; return; } if (swTileX == null && tileCNSS.Length > 0) { cacheRenderer.sprite = tileCNSS[Random.Range(0, tileCNSS.Length)]; tileSprite = "CNSS"; return; } if (tileCN.Length > 0) { cacheRenderer.sprite = tileCN[Random.Range(0, tileCN.Length)]; tileSprite = "CN"; return; } } if ((nTileX != null) && (eTileX != null) && (sTileX == null) && (wTileX != null)) { if (neTileX == null && nwTileX == null && tileCSN.Length > 0) { cacheRenderer.sprite = tileCSN[Random.Range(0, tileCSN.Length)]; tileSprite = "CSN"; return; } if (nwTileX == null && tileCSWW.Length > 0) { cacheRenderer.sprite = tileCSWW[Random.Range(0, tileCSWW.Length)]; tileSprite = "CSWW"; return; } if (neTileX == null && tileCSEE.Length > 0) { cacheRenderer.sprite = tileCSEE[Random.Range(0, tileCSEE.Length)]; tileSprite = "CSEE"; return; } if (tileCS.Length > 0) { cacheRenderer.sprite = tileCS[Random.Range(0, tileCS.Length)]; tileSprite = "CS"; return; } } if ((nTileX != null) && (eTileX != null) && (sTileX != null) && (wTileX == null)) { if (neTileX == null && seTileX == null && tileCWE.Length > 0) { cacheRenderer.sprite = tileCWE[Random.Range(0, tileCWE.Length)]; tileSprite = "CWE"; return; } if (neTileX == null && tileCWNN.Length > 0) { cacheRenderer.sprite = tileCWNN[Random.Range(0, tileCWNN.Length)]; tileSprite = "CWNN"; return; } if (seTileX == null && tileCWSS.Length > 0) { cacheRenderer.sprite = tileCWSS[Random.Range(0, tileCWSS.Length)]; tileSprite = "CWSS"; return; } if (tileCW.Length > 0) { cacheRenderer.sprite = tileCW[Random.Range(0, tileCW.Length)]; tileSprite = "CW"; return; } } if ((nTileX != null) && (eTileX == null) && (sTileX != null) && (wTileX != null)) { if (nwTileX == null && swTileX == null && tileCEW.Length > 0) { cacheRenderer.sprite = tileCEW[Random.Range(0, tileCEW.Length)]; tileSprite = "CEW"; return; } if (swTileX == null && tileCESS.Length > 0) { cacheRenderer.sprite = tileCESS[Random.Range(0, tileCESS.Length)]; tileSprite = "CESS"; return; } if (nwTileX == null && tileCENN.Length > 0) { cacheRenderer.sprite = tileCENN[Random.Range(0, tileCENN.Length)]; tileSprite = "CENN"; return; } if (tileCE.Length > 0) { cacheRenderer.sprite = tileCE[Random.Range(0, tileCE.Length)]; tileSprite = "CE"; return; } } // Check if this is NW tile if ((nTileX == null) && (eTileX != null) && (sTileX != null) && (wTileX == null)) { if (seTileX == null && tileNWSE.Length > 0) { cacheRenderer.sprite = tileNWSE[Random.Range(0, tileNWSE.Length)]; tileSprite = "NWSE"; return; } if (tileNW.Length > 0) { cacheRenderer.sprite = tileNW[Random.Range(0, tileNW.Length)]; tileSprite = "NW"; return; } } // Check if this is NE tile if ((nTileX == null) && (eTileX == null) && (sTileX != null) && (wTileX != null)) { if (swTileX == null && tileNESW.Length > 0) { cacheRenderer.sprite = tileNESW[Random.Range(0, tileNESW.Length)]; tileSprite = "NESW"; return; } if (tileNE.Length > 0) { cacheRenderer.sprite = tileNE[Random.Range(0, tileNE.Length)]; tileSprite = "NE"; return; } } // Check if this is SW tile if ((nTileX != null) && (eTileX != null) && (sTileX == null) && (wTileX == null)) { if (neTileX == null && tileSWNE.Length > 0) { cacheRenderer.sprite = tileSWNE[Random.Range(0, tileSWNE.Length)]; tileSprite = "SWNE"; return; } if (tileSW.Length > 0) { cacheRenderer.sprite = tileSW[Random.Range(0, tileSW.Length)]; tileSprite = "SW"; return; } } // Check if this is SE tile if ((nTileX != null) && (eTileX == null) && (sTileX == null) && (wTileX != null)) { if (nwTileX == null && tileSENW.Length > 0) { cacheRenderer.sprite = tileSENW[Random.Range(0, tileSENW.Length)]; tileSprite = "SENW"; return; } if (tileSE.Length > 0) { cacheRenderer.sprite = tileSE[Random.Range(0, tileSE.Length)]; tileSprite = "SE"; return; } } // Check if this is N tile if ((nTileX == null) && (eTileX == null) && (sTileX != null) && (wTileX == null)) { if (tileN.Length > 0) { cacheRenderer.sprite = tileN[Random.Range(0, tileN.Length)]; tileSprite = "N"; return; } } // Check if this is E tile if ((nTileX == null) && (eTileX == null) && (sTileX == null) && (wTileX != null)) { if (tileE.Length > 0) { cacheRenderer.sprite = tileE[Random.Range(0, tileE.Length)]; tileSprite = "E"; return; } } // Check if this is S tile if ((nTileX != null) && (eTileX == null) && (sTileX == null) && (wTileX == null)) { if (tileS.Length > 0) { cacheRenderer.sprite = tileS[Random.Range(0, tileS.Length)]; tileSprite = "S"; return; } } // Check if this is W tile if ((nTileX == null) && (eTileX != null) && (sTileX == null) && (wTileX == null)) { if (tileW.Length > 0) { cacheRenderer.sprite = tileW[Random.Range(0, tileW.Length)]; tileSprite = "W"; return; } } // Check if this is NS tile if ((nTileX == null) && (eTileX != null) && (sTileX == null) && (wTileX != null)) { if (tileNS.Length > 0) { cacheRenderer.sprite = tileNS[Random.Range(0, tileNS.Length)]; tileSprite = "NS"; return; } } // Check if this is WE tile if ((nTileX != null) && (eTileX == null) && (sTileX != null) && (wTileX == null)) { if (tileWE.Length > 0) { cacheRenderer.sprite = tileWE[Random.Range(0, tileWE.Length)]; tileSprite = "WE"; return; } } // Check if this is A tile if (tileA.Length > 0) { cacheRenderer.sprite = tileA[Random.Range(0, tileA.Length)]; tileSprite = "A"; return; } } }
namespace Unity.IO.Compression { using System.Diagnostics; using System.Globalization; internal static class FastEncoderStatics { // static information for encoding, DO NOT MODIFY internal static readonly byte[] FastEncoderTreeStructureData = { 0xec,0xbd,0x07,0x60,0x1c,0x49,0x96,0x25,0x26,0x2f,0x6d,0xca, 0x7b,0x7f,0x4a,0xf5,0x4a,0xd7,0xe0,0x74,0xa1,0x08,0x80,0x60, 0x13,0x24,0xd8,0x90,0x40,0x10,0xec,0xc1,0x88,0xcd,0xe6,0x92, 0xec,0x1d,0x69,0x47,0x23,0x29,0xab,0x2a,0x81,0xca,0x65,0x56, 0x65,0x5d,0x66,0x16,0x40,0xcc,0xed,0x9d,0xbc,0xf7,0xde,0x7b, 0xef,0xbd,0xf7,0xde,0x7b,0xef,0xbd,0xf7,0xba,0x3b,0x9d,0x4e, 0x27,0xf7,0xdf,0xff,0x3f,0x5c,0x66,0x64,0x01,0x6c,0xf6,0xce, 0x4a,0xda,0xc9,0x9e,0x21,0x80,0xaa,0xc8,0x1f,0x3f,0x7e,0x7c, 0x1f,0x3f, }; internal static readonly byte[] BFinalFastEncoderTreeStructureData = { 0xed,0xbd,0x07,0x60,0x1c,0x49,0x96,0x25,0x26,0x2f,0x6d,0xca, 0x7b,0x7f,0x4a,0xf5,0x4a,0xd7,0xe0,0x74,0xa1,0x08,0x80,0x60, 0x13,0x24,0xd8,0x90,0x40,0x10,0xec,0xc1,0x88,0xcd,0xe6,0x92, 0xec,0x1d,0x69,0x47,0x23,0x29,0xab,0x2a,0x81,0xca,0x65,0x56, 0x65,0x5d,0x66,0x16,0x40,0xcc,0xed,0x9d,0xbc,0xf7,0xde,0x7b, 0xef,0xbd,0xf7,0xde,0x7b,0xef,0xbd,0xf7,0xba,0x3b,0x9d,0x4e, 0x27,0xf7,0xdf,0xff,0x3f,0x5c,0x66,0x64,0x01,0x6c,0xf6,0xce, 0x4a,0xda,0xc9,0x9e,0x21,0x80,0xaa,0xc8,0x1f,0x3f,0x7e,0x7c, 0x1f,0x3f, }; // Output a currentMatch with length matchLen (>= MIN_MATCH) and displacement matchPos // // Optimisation: unlike the other encoders, here we have an array of codes for each currentMatch // length (not just each currentMatch length slot), complete with all the extra bits filled in, in // a single array element. // // There are many advantages to doing this: // // 1. A single array lookup on g_FastEncoderLiteralCodeInfo, instead of separate array lookups // on g_LengthLookup (to get the length slot), g_FastEncoderLiteralTreeLength, // g_FastEncoderLiteralTreeCode, g_ExtraLengthBits, and g_BitMask // // 2. The array is an array of ULONGs, so no access penalty, unlike for accessing those USHORT // code arrays in the other encoders (although they could be made into ULONGs with some // modifications to the source). // // Note, if we could guarantee that codeLen <= 16 always, then we could skip an if statement here. // // A completely different optimisation is used for the distance codes since, obviously, a table for // all 8192 distances combining their extra bits is not feasible. The distance codeinfo table is // made up of code[], len[] and # extraBits for this code. // // The advantages are similar to the above; a ULONG array instead of a USHORT and BYTE array, better // cache locality, fewer memory operations. // // Encoding information for literal and Length. // The least 5 significant bits are the length // and the rest is the code bits. internal static readonly uint[] FastEncoderLiteralCodeInfo = { 0x0000d7ee,0x0004d7ee,0x0002d7ee,0x0006d7ee,0x0001d7ee,0x0005d7ee,0x0003d7ee, 0x0007d7ee,0x000037ee,0x0000c7ec,0x00000126,0x000437ee,0x000237ee,0x000637ee, 0x000137ee,0x000537ee,0x000337ee,0x000737ee,0x0000b7ee,0x0004b7ee,0x0002b7ee, 0x0006b7ee,0x0001b7ee,0x0005b7ee,0x0003b7ee,0x0007b7ee,0x000077ee,0x000477ee, 0x000277ee,0x000677ee,0x000017ed,0x000177ee,0x00000526,0x000577ee,0x000023ea, 0x0001c7ec,0x000377ee,0x000777ee,0x000217ed,0x000063ea,0x00000b68,0x00000ee9, 0x00005beb,0x000013ea,0x00000467,0x00001b68,0x00000c67,0x00002ee9,0x00000768, 0x00001768,0x00000f68,0x00001ee9,0x00001f68,0x00003ee9,0x000053ea,0x000001e9, 0x000000e8,0x000021e9,0x000011e9,0x000010e8,0x000031e9,0x000033ea,0x000008e8, 0x0000f7ee,0x0004f7ee,0x000018e8,0x000009e9,0x000004e8,0x000029e9,0x000014e8, 0x000019e9,0x000073ea,0x0000dbeb,0x00000ce8,0x00003beb,0x0002f7ee,0x000039e9, 0x00000bea,0x000005e9,0x00004bea,0x000025e9,0x000027ec,0x000015e9,0x000035e9, 0x00000de9,0x00002bea,0x000127ec,0x0000bbeb,0x0006f7ee,0x0001f7ee,0x0000a7ec, 0x00007beb,0x0005f7ee,0x0000fbeb,0x0003f7ee,0x0007f7ee,0x00000fee,0x00000326, 0x00000267,0x00000a67,0x00000667,0x00000726,0x00001ce8,0x000002e8,0x00000e67, 0x000000a6,0x0001a7ec,0x00002de9,0x000004a6,0x00000167,0x00000967,0x000002a6, 0x00000567,0x000117ed,0x000006a6,0x000001a6,0x000005a6,0x00000d67,0x000012e8, 0x00000ae8,0x00001de9,0x00001ae8,0x000007eb,0x000317ed,0x000067ec,0x000097ed, 0x000297ed,0x00040fee,0x00020fee,0x00060fee,0x00010fee,0x00050fee,0x00030fee, 0x00070fee,0x00008fee,0x00048fee,0x00028fee,0x00068fee,0x00018fee,0x00058fee, 0x00038fee,0x00078fee,0x00004fee,0x00044fee,0x00024fee,0x00064fee,0x00014fee, 0x00054fee,0x00034fee,0x00074fee,0x0000cfee,0x0004cfee,0x0002cfee,0x0006cfee, 0x0001cfee,0x0005cfee,0x0003cfee,0x0007cfee,0x00002fee,0x00042fee,0x00022fee, 0x00062fee,0x00012fee,0x00052fee,0x00032fee,0x00072fee,0x0000afee,0x0004afee, 0x0002afee,0x0006afee,0x0001afee,0x0005afee,0x0003afee,0x0007afee,0x00006fee, 0x00046fee,0x00026fee,0x00066fee,0x00016fee,0x00056fee,0x00036fee,0x00076fee, 0x0000efee,0x0004efee,0x0002efee,0x0006efee,0x0001efee,0x0005efee,0x0003efee, 0x0007efee,0x00001fee,0x00041fee,0x00021fee,0x00061fee,0x00011fee,0x00051fee, 0x00031fee,0x00071fee,0x00009fee,0x00049fee,0x00029fee,0x00069fee,0x00019fee, 0x00059fee,0x00039fee,0x00079fee,0x00005fee,0x00045fee,0x00025fee,0x00065fee, 0x00015fee,0x00055fee,0x00035fee,0x00075fee,0x0000dfee,0x0004dfee,0x0002dfee, 0x0006dfee,0x0001dfee,0x0005dfee,0x0003dfee,0x0007dfee,0x00003fee,0x00043fee, 0x00023fee,0x00063fee,0x00013fee,0x00053fee,0x00033fee,0x00073fee,0x0000bfee, 0x0004bfee,0x0002bfee,0x0006bfee,0x0001bfee,0x0005bfee,0x0003bfee,0x0007bfee, 0x00007fee,0x00047fee,0x00027fee,0x00067fee,0x00017fee,0x000197ed,0x000397ed, 0x000057ed,0x00057fee,0x000257ed,0x00037fee,0x000157ed,0x00077fee,0x000357ed, 0x0000ffee,0x0004ffee,0x0002ffee,0x0006ffee,0x0001ffee,0x00000084,0x00000003, 0x00000184,0x00000044,0x00000144,0x000000c5,0x000002c5,0x000001c5,0x000003c6, 0x000007c6,0x00000026,0x00000426,0x000003a7,0x00000ba7,0x000007a7,0x00000fa7, 0x00000227,0x00000627,0x00000a27,0x00000e27,0x00000068,0x00000868,0x00001068, 0x00001868,0x00000369,0x00001369,0x00002369,0x00003369,0x000006ea,0x000026ea, 0x000046ea,0x000066ea,0x000016eb,0x000036eb,0x000056eb,0x000076eb,0x000096eb, 0x0000b6eb,0x0000d6eb,0x0000f6eb,0x00003dec,0x00007dec,0x0000bdec,0x0000fdec, 0x00013dec,0x00017dec,0x0001bdec,0x0001fdec,0x00006bed,0x0000ebed,0x00016bed, 0x0001ebed,0x00026bed,0x0002ebed,0x00036bed,0x0003ebed,0x000003ec,0x000043ec, 0x000083ec,0x0000c3ec,0x000103ec,0x000143ec,0x000183ec,0x0001c3ec,0x00001bee, 0x00009bee,0x00011bee,0x00019bee,0x00021bee,0x00029bee,0x00031bee,0x00039bee, 0x00041bee,0x00049bee,0x00051bee,0x00059bee,0x00061bee,0x00069bee,0x00071bee, 0x00079bee,0x000167f0,0x000367f0,0x000567f0,0x000767f0,0x000967f0,0x000b67f0, 0x000d67f0,0x000f67f0,0x001167f0,0x001367f0,0x001567f0,0x001767f0,0x001967f0, 0x001b67f0,0x001d67f0,0x001f67f0,0x000087ef,0x000187ef,0x000287ef,0x000387ef, 0x000487ef,0x000587ef,0x000687ef,0x000787ef,0x000887ef,0x000987ef,0x000a87ef, 0x000b87ef,0x000c87ef,0x000d87ef,0x000e87ef,0x000f87ef,0x0000e7f0,0x0002e7f0, 0x0004e7f0,0x0006e7f0,0x0008e7f0,0x000ae7f0,0x000ce7f0,0x000ee7f0,0x0010e7f0, 0x0012e7f0,0x0014e7f0,0x0016e7f0,0x0018e7f0,0x001ae7f0,0x001ce7f0,0x001ee7f0, 0x0005fff3,0x000dfff3,0x0015fff3,0x001dfff3,0x0025fff3,0x002dfff3,0x0035fff3, 0x003dfff3,0x0045fff3,0x004dfff3,0x0055fff3,0x005dfff3,0x0065fff3,0x006dfff3, 0x0075fff3,0x007dfff3,0x0085fff3,0x008dfff3,0x0095fff3,0x009dfff3,0x00a5fff3, 0x00adfff3,0x00b5fff3,0x00bdfff3,0x00c5fff3,0x00cdfff3,0x00d5fff3,0x00ddfff3, 0x00e5fff3,0x00edfff3,0x00f5fff3,0x00fdfff3,0x0003fff3,0x000bfff3,0x0013fff3, 0x001bfff3,0x0023fff3,0x002bfff3,0x0033fff3,0x003bfff3,0x0043fff3,0x004bfff3, 0x0053fff3,0x005bfff3,0x0063fff3,0x006bfff3,0x0073fff3,0x007bfff3,0x0083fff3, 0x008bfff3,0x0093fff3,0x009bfff3,0x00a3fff3,0x00abfff3,0x00b3fff3,0x00bbfff3, 0x00c3fff3,0x00cbfff3,0x00d3fff3,0x00dbfff3,0x00e3fff3,0x00ebfff3,0x00f3fff3, 0x00fbfff3,0x0007fff3,0x000ffff3,0x0017fff3,0x001ffff3,0x0027fff3,0x002ffff3, 0x0037fff3,0x003ffff3,0x0047fff3,0x004ffff3,0x0057fff3,0x005ffff3,0x0067fff3, 0x006ffff3,0x0077fff3,0x007ffff3,0x0087fff3,0x008ffff3,0x0097fff3,0x009ffff3, 0x00a7fff3,0x00affff3,0x00b7fff3,0x00bffff3,0x00c7fff3,0x00cffff3,0x00d7fff3, 0x00dffff3,0x00e7fff3,0x00effff3,0x00f7fff3,0x00fffff3,0x0001e7f1,0x0003e7f1, 0x0005e7f1,0x0007e7f1,0x0009e7f1,0x000be7f1,0x000de7f1,0x000fe7f1,0x0011e7f1, 0x0013e7f1,0x0015e7f1,0x0017e7f1,0x0019e7f1,0x001be7f1,0x001de7f1,0x001fe7f1, 0x0021e7f1,0x0023e7f1,0x0025e7f1,0x0027e7f1,0x0029e7f1,0x002be7f1,0x002de7f1, 0x002fe7f1,0x0031e7f1,0x0033e7f1,0x0035e7f1,0x0037e7f1,0x0039e7f1,0x003be7f1, 0x003de7f1,0x000047eb, }; internal static readonly uint[] FastEncoderDistanceCodeInfo = { 0x00000f06,0x0001ff0a,0x0003ff0b,0x0007ff0b,0x0000ff19,0x00003f18,0x0000bf28, 0x00007f28,0x00001f37,0x00005f37,0x00000d45,0x00002f46,0x00000054,0x00001d55, 0x00000864,0x00000365,0x00000474,0x00001375,0x00000c84,0x00000284,0x00000a94, 0x00000694,0x00000ea4,0x000001a4,0x000009b4,0x00000bb5,0x000005c4,0x00001bc5, 0x000007d5,0x000017d5,0x00000000,0x00000100, }; internal static readonly uint[] BitMask = { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 }; internal static readonly byte[] ExtraLengthBits = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; internal static readonly byte[] ExtraDistanceBits = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0 }; internal const int NumChars = 256; internal const int NumLengthBaseCodes = 29; internal const int NumDistBaseCodes = 30; internal const uint FastEncoderPostTreeBitBuf = 0x0022; internal const int FastEncoderPostTreeBitCount = 9; internal const uint NoCompressionHeader = 0x0; internal const int NoCompressionHeaderBitCount = 3; internal const uint BFinalNoCompressionHeader = 0x1; internal const int BFinalNoCompressionHeaderBitCount = 3; internal const int MaxCodeLen = 16; static private byte[] distLookup; static FastEncoderStatics() { distLookup = new byte[512]; // Generate the global slot tables which allow us to convert a distance // (0..32K) to a distance slot (0..29) // // Distance table // Extra Extra Extra // Code Bits Dist Code Bits Dist Code Bits Distance // ---- ---- ---- ---- ---- ------ ---- ---- -------- // 0 0 1 10 4 33-48 20 9 1025-1536 // 1 0 2 11 4 49-64 21 9 1537-2048 // 2 0 3 12 5 65-96 22 10 2049-3072 // 3 0 4 13 5 97-128 23 10 3073-4096 // 4 1 5,6 14 6 129-192 24 11 4097-6144 // 5 1 7,8 15 6 193-256 25 11 6145-8192 // 6 2 9-12 16 7 257-384 26 12 8193-12288 // 7 2 13-16 17 7 385-512 27 12 12289-16384 // 8 3 17-24 18 8 513-768 28 13 16385-24576 // 9 3 25-32 19 8 769-1024 29 13 24577-32768 // Initialize the mapping length (0..255) -> length code (0..28) //int length = 0; //for (code = 0; code < FastEncoderStatics.NumLengthBaseCodes-1; code++) { // for (int n = 0; n < (1 << FastEncoderStatics.ExtraLengthBits[code]); n++) // lengthLookup[length++] = (byte) code; //} //lengthLookup[length-1] = (byte) code; // Initialize the mapping dist (0..32K) -> dist code (0..29) int dist = 0; int code; for (code = 0; code < 16; code++) { for (int n = 0; n < (1 << FastEncoderStatics.ExtraDistanceBits[code]); n++) distLookup[dist++] = (byte)code; } dist >>= 7; // from now on, all distances are divided by 128 for (; code < FastEncoderStatics.NumDistBaseCodes; code++) { for (int n = 0; n < (1 << (FastEncoderStatics.ExtraDistanceBits[code] - 7)); n++) distLookup[256 + dist++] = (byte)code; } } // Return the position slot (0...29) of a match offset (0...32767) static internal int GetSlot(int pos) { return distLookup[((pos) < 256) ? (pos) : (256 + ((pos) >> 7))]; } // Reverse 'length' of the bits in code public static uint BitReverse(uint code, int length) { uint new_code = 0; Debug.Assert(length > 0 && length <= 16, "Invalid len"); do { new_code |= (code & 1); new_code <<= 1; code >>= 1; } while (--length > 0); return new_code >> 1; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.ResourceSettings.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedResourceSettingsServiceClientTest { [xunit::FactAttribute] public void GetSettingRequestObject() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), View = SettingView.Basic, }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting response = client.GetSetting(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSettingRequestObjectAsync() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), View = SettingView.Basic, }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Setting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting responseCallSettings = await client.GetSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Setting responseCancellationToken = await client.GetSettingAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSetting() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting response = client.GetSetting(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSettingAsync() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Setting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting responseCallSettings = await client.GetSettingAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Setting responseCancellationToken = await client.GetSettingAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSettingResourceNames() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting response = client.GetSetting(request.SettingName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSettingResourceNamesAsync() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); GetSettingRequest request = new GetSettingRequest { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Setting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting responseCallSettings = await client.GetSettingAsync(request.SettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Setting responseCancellationToken = await client.GetSettingAsync(request.SettingName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSettingRequestObject() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); UpdateSettingRequest request = new UpdateSettingRequest { Setting = new Setting(), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.UpdateSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting response = client.UpdateSetting(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSettingRequestObjectAsync() { moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient> mockGrpcClient = new moq::Mock<ResourceSettingsService.ResourceSettingsServiceClient>(moq::MockBehavior.Strict); UpdateSettingRequest request = new UpdateSettingRequest { Setting = new Setting(), }; Setting expectedResponse = new Setting { SettingName = SettingName.FromProjectNumberSettingName("[PROJECT_NUMBER]", "[SETTING_NAME]"), Metadata = new SettingMetadata(), LocalValue = new Value(), EffectiveValue = new Value(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.UpdateSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Setting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ResourceSettingsServiceClient client = new ResourceSettingsServiceClientImpl(mockGrpcClient.Object, null); Setting responseCallSettings = await client.UpdateSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Setting responseCancellationToken = await client.UpdateSettingAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OrchardCore.FileStorage; using OrchardCore.Media.Services; namespace OrchardCore.Media.Controllers { public class AdminController : Controller { private static readonly char[] _invalidFolderNameCharacters = new char[] { '\\', '/' }; private readonly HashSet<string> _allowedFileExtensions; private readonly IMediaFileStore _mediaFileStore; private readonly IMediaNameNormalizerService _mediaNameNormalizerService; private readonly IAuthorizationService _authorizationService; private readonly IContentTypeProvider _contentTypeProvider; private readonly ILogger _logger; private readonly IStringLocalizer S; private readonly MediaOptions _mediaOptions; private readonly IUserAssetFolderNameProvider _userAssetFolderNameProvider; public AdminController( IMediaFileStore mediaFileStore, IMediaNameNormalizerService mediaNameNormalizerService, IAuthorizationService authorizationService, IContentTypeProvider contentTypeProvider, IOptions<MediaOptions> options, ILogger<AdminController> logger, IStringLocalizer<AdminController> stringLocalizer, IUserAssetFolderNameProvider userAssetFolderNameProvider ) { _mediaFileStore = mediaFileStore; _mediaNameNormalizerService = mediaNameNormalizerService; _authorizationService = authorizationService; _contentTypeProvider = contentTypeProvider; _mediaOptions = options.Value; _allowedFileExtensions = _mediaOptions.AllowedFileExtensions; _logger = logger; S = stringLocalizer; _userAssetFolderNameProvider = userAssetFolderNameProvider; } public async Task<IActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } return View(); } public async Task<ActionResult<IEnumerable<IFileStoreEntry>>> GetFolders(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { path = ""; } if (await _mediaFileStore.GetDirectoryInfoAsync(path) == null) { return NotFound(); } // create default folders if not exist if (await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia) && await _mediaFileStore.GetDirectoryInfoAsync(_mediaFileStore.Combine(_mediaOptions.AssetsUsersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(User))) == null) { await _mediaFileStore.TryCreateDirectoryAsync(_mediaFileStore.Combine(_mediaOptions.AssetsUsersFolder, _userAssetFolderNameProvider.GetUserAssetFolderName(User))); } var allowed = _mediaFileStore.GetDirectoryContentAsync(path) .WhereAwait(async e => e.IsDirectory && await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)e.Path)); return Ok(await allowed.ToListAsync()); } public async Task<ActionResult<IEnumerable<object>>> GetMediaItems(string path) { if (string.IsNullOrEmpty(path)) { path = ""; } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) { return Forbid(); } if (await _mediaFileStore.GetDirectoryInfoAsync(path) == null) { return NotFound(); } var allowed = _mediaFileStore.GetDirectoryContentAsync(path) .WhereAwait(async e => !e.IsDirectory && await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)e.Path)) .Select(e => CreateFileResult(e)); return Ok(await allowed.ToListAsync()); } public async Task<ActionResult<object>> GetMediaItem(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return NotFound(); } var f = await _mediaFileStore.GetFileInfoAsync(path); if (f == null) { return NotFound(); } return CreateFileResult(f); } [HttpPost] [MediaSizeLimit] public async Task<ActionResult<object>> Upload( string path, string contentType, ICollection<IFormFile> files) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { path = ""; } var result = new List<object>(); // Loop through each file in the request foreach (var file in files) { // TODO: support clipboard if (!_allowedFileExtensions.Contains(Path.GetExtension(file.FileName), StringComparer.OrdinalIgnoreCase)) { result.Add(new { name = file.FileName, size = file.Length, folder = path, error = S["This file extension is not allowed: {0}", Path.GetExtension(file.FileName)].ToString() }); _logger.LogInformation("File extension not allowed: '{File}'", file.FileName); continue; } var fileName = _mediaNameNormalizerService.NormalizeFileName(file.FileName); Stream stream = null; try { var mediaFilePath = _mediaFileStore.Combine(path, fileName); stream = file.OpenReadStream(); mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, stream); var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath); result.Add(CreateFileResult(mediaFile)); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while uploading a media"); result.Add(new { name = fileName, size = file.Length, folder = path, error = ex.Message }); } finally { stream?.Dispose(); } } return new { files = result.ToArray() }; } [HttpPost] public async Task<IActionResult> DeleteFolder(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot delete root media folder"]); } var mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(path); if (mediaFolder != null && !mediaFolder.IsDirectory) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot delete path because it is not a directory"]); } if (await _mediaFileStore.TryDeleteDirectoryAsync(path) == false) { return NotFound(); } return Ok(); } [HttpPost] public async Task<IActionResult> DeleteMedia(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)path)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return NotFound(); } if (await _mediaFileStore.TryDeleteFileAsync(path) == false) return NotFound(); return Ok(); } [HttpPost] public async Task<IActionResult> MoveMedia(string oldPath, string newPath) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)oldPath)) { return Forbid(); } if (string.IsNullOrEmpty(oldPath) || string.IsNullOrEmpty(newPath)) { return NotFound(); } if (await _mediaFileStore.GetFileInfoAsync(oldPath) == null) { return NotFound(); } if (!_allowedFileExtensions.Contains(Path.GetExtension(newPath), StringComparer.OrdinalIgnoreCase)) { return StatusCode(StatusCodes.Status400BadRequest, S["This file extension is not allowed: {0}", Path.GetExtension(newPath)]); } if (await _mediaFileStore.GetFileInfoAsync(newPath) != null) { return StatusCode(StatusCodes.Status400BadRequest, S["Cannot move media because a file already exists with the same name"]); } await _mediaFileStore.MoveFileAsync(oldPath, newPath); return Ok(); } [HttpPost] public async Task<IActionResult> DeleteMediaList(string[] paths) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } foreach (var path in paths) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)path)) { return Forbid(); } } if (paths == null) { return NotFound(); } foreach (var p in paths) { if (await _mediaFileStore.TryDeleteFileAsync(p) == false) return NotFound(); } return Ok(); } [HttpPost] public async Task<IActionResult> MoveMediaList(string[] mediaNames, string sourceFolder, string targetFolder) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)sourceFolder) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)targetFolder)) { return Forbid(); } if ((mediaNames == null) || (mediaNames.Length < 1) || string.IsNullOrEmpty(sourceFolder) || string.IsNullOrEmpty(targetFolder)) { return NotFound(); } sourceFolder = sourceFolder == "root" ? string.Empty : sourceFolder; targetFolder = targetFolder == "root" ? string.Empty : targetFolder; var filesOnError = new List<string>(); foreach (var name in mediaNames) { var sourcePath = _mediaFileStore.Combine(sourceFolder, name); var targetPath = _mediaFileStore.Combine(targetFolder, name); try { await _mediaFileStore.MoveFileAsync(sourcePath, targetPath); } catch (FileStoreException) { filesOnError.Add(sourcePath); } } if (filesOnError.Count > 0) { return BadRequest(S["Error when moving files. Maybe they already exist on the target folder? Files on error: {0}", string.Join(",", filesOnError)].ToString()); } else { return Ok(); } } [HttpPost] public async Task<ActionResult<IFileStoreEntry>> CreateFolder( string path, string name, [FromServices] IAuthorizationService authorizationService) { if (string.IsNullOrEmpty(path)) { path = ""; } name = _mediaNameNormalizerService.NormalizeFolderName(name); if (_invalidFolderNameCharacters.Any(invalidChar => name.Contains(invalidChar))) { return StatusCode(StatusCodes.Status400BadRequest, S["Cannot create folder because the folder name contains invalid characters"]); } var newPath = _mediaFileStore.Combine(path, name); if (!await authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await authorizationService.AuthorizeAsync(User, Permissions.ManageMediaFolder, (object)newPath)) { return Forbid(); } var mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(newPath); if (mediaFolder != null) { return StatusCode(StatusCodes.Status400BadRequest, S["Cannot create folder because a folder already exists with the same name"]); } var existingFile = await _mediaFileStore.GetFileInfoAsync(newPath); if (existingFile != null) { return StatusCode(StatusCodes.Status400BadRequest, S["Cannot create folder because a file already exists with the same name"]); } await _mediaFileStore.TryCreateDirectoryAsync(newPath); mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(newPath); return new ObjectResult(mediaFolder); } public object CreateFileResult(IFileStoreEntry mediaFile) { _contentTypeProvider.TryGetContentType(mediaFile.Name, out var contentType); return new { name = mediaFile.Name, size = mediaFile.Length, lastModify = mediaFile.LastModifiedUtc.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds, folder = mediaFile.DirectoryPath, url = _mediaFileStore.MapPathToPublicUrl(mediaFile.Path), mediaPath = mediaFile.Path, mime = contentType ?? "application/octet-stream", mediaText = String.Empty, anchor = new { x = 0.5f, y = 0.5f } }; } public IActionResult MediaApplication() { return View(); } public async Task<IActionResult> Options() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewMediaOptions)) { return Forbid(); } return View(_mediaOptions); } } }
namespace Orleans.CodeGenerator { using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Methods common to multiple code generators. /// </summary> internal static class CodeGeneratorCommon { /// <summary> /// The name of these code generators. /// </summary> private const string CodeGeneratorName = "Orleans-CodeGenerator"; /// <summary> /// The prefix for class names. /// </summary> internal const string ClassPrefix = "OrleansCodeGen"; /// <summary> /// The current version. /// </summary> private static readonly string CodeGeneratorVersion = RuntimeVersion.FileVersion; /// <summary> /// Generates and compiles an assembly for the provided grains. /// </summary> /// <param name="generatedSyntax"> /// The generated code. /// </param> /// <param name="assemblyName"> /// The name for the generated assembly. /// </param> /// <returns> /// The raw assembly. /// </returns> /// <exception cref="CodeGenerationException"> /// An error occurred generating code. /// </exception> public static byte[] CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName) { // Add the generated code attribute. var code = AddGeneratedCodeAttribute(generatedSyntax); // Reference everything which can be referenced. var assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location)) .Select(asm => MetadataReference.CreateFromFile(asm.Location)) .Cast<MetadataReference>() .ToArray(); var logger = LogManager.GetLogger("CodeGenerator"); // Generate the code. var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); string source = null; if (logger.IsVerbose3) { source = GenerateSourceCode(code); // Compile the code and load the generated assembly. logger.LogWithoutBulkingAndTruncating( Severity.Verbose3, ErrorCode.CodeGenSourceGenerated, "Generating assembly {0} with source:\n{1}", assemblyName, source); } var compilation = CSharpCompilation.Create(assemblyName) .AddSyntaxTrees(code.SyntaxTree) .AddReferences(assemblies) .WithOptions(options); using (var stream = new MemoryStream()) { var compilationResult = compilation.Emit(stream); if (!compilationResult.Success) { source = source ?? GenerateSourceCode(code); var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString())); logger.Warn( ErrorCode.CodeGenCompilationFailed, "Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}", assemblyName, errors, source); throw new CodeGenerationException(errors); } logger.Verbose(ErrorCode.CodeGenCompilationSucceeded, "Compilation of assembly {0} succeeded.", assemblyName); return stream.ToArray(); } } public static CompilationUnitSyntax AddGeneratedCodeAttribute(GeneratedSyntax generatedSyntax) { var codeGenTargetAttributes = SF.AttributeList() .AddAttributes( generatedSyntax.SourceAssemblies.Select( asm => SF.Attribute(typeof(OrleansCodeGenerationTargetAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(asm.GetName().FullName.GetLiteralExpression()))).ToArray()) .WithTarget(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword))); var generatedCodeAttribute = SF.AttributeList() .AddAttributes( SF.Attribute(typeof(GeneratedCodeAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument("Orleans-CodeGenerator".GetLiteralExpression()), SF.AttributeArgument(RuntimeVersion.FileVersion.GetLiteralExpression()))) .WithTarget(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword))); return generatedSyntax.Syntax.AddAttributeLists(generatedCodeAttribute, codeGenTargetAttributes); } internal static AttributeSyntax GetGeneratedCodeAttributeSyntax() { return SF.Attribute(typeof(GeneratedCodeAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(CodeGeneratorName.GetLiteralExpression()), SF.AttributeArgument(CodeGeneratorVersion.GetLiteralExpression())); } internal static string GenerateSourceCode(CompilationUnitSyntax code) { var syntax = code.NormalizeWhitespace(); var source = syntax.ToFullString(); return source; } /// <summary> /// Generates switch cases for the provided grain type. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="methodIdArgument"> /// The method id argument, which is used to select the correct switch label. /// </param> /// <param name="generateMethodHandler"> /// The function used to generate switch block statements for each method. /// </param> /// <returns> /// The switch cases for the provided grain type. /// </returns> public static SwitchSectionSyntax[] GenerateGrainInterfaceAndMethodSwitch( Type grainType, ExpressionSyntax methodIdArgument, Func<MethodInfo, StatementSyntax[]> generateMethodHandler) { var interfaces = GrainInterfaceUtils.GetRemoteInterfaces(grainType); interfaces[GrainInterfaceUtils.GetGrainInterfaceId(grainType)] = grainType; // Switch on interface id. var interfaceCases = new List<SwitchSectionSyntax>(); foreach (var @interface in interfaces) { var interfaceType = @interface.Value; var interfaceId = @interface.Key; var methods = GrainInterfaceUtils.GetMethods(interfaceType); var methodCases = new List<SwitchSectionSyntax>(); // Switch on method id. foreach (var method in methods) { // Generate switch case. var methodId = GrainInterfaceUtils.ComputeMethodId(method); var methodType = method; // Generate the switch label for this interface id. var methodIdSwitchLabel = SF.CaseSwitchLabel( SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId))); // Generate the switch body. var methodInvokeStatement = generateMethodHandler(methodType); methodCases.Add( SF.SwitchSection().AddLabels(methodIdSwitchLabel).AddStatements(methodInvokeStatement)); } // Generate the switch label for this interface id. var interfaceIdSwitchLabel = SF.CaseSwitchLabel( SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId))); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), SF.BinaryExpression( SyntaxKind.AddExpression, SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)), SF.BinaryExpression( SyntaxKind.AddExpression, ",methodId=".GetLiteralExpression(), methodIdArgument))); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); // Generate switch statements for the methods in this interface. var methodSwitchStatements = SF.SwitchStatement(methodIdArgument).AddSections(methodCases.ToArray()).AddSections(defaultCase); // Generate the switch section for this interface. interfaceCases.Add( SF.SwitchSection().AddLabels(interfaceIdSwitchLabel).AddStatements(methodSwitchStatements)); } return interfaceCases.ToArray(); } public static string GetRandomNamespace() { return "Generated" + DateTime.Now.Ticks.ToString("X"); } public static string GetGeneratedNamespace(Type type, bool randomize = false) { string result; if (randomize || string.IsNullOrWhiteSpace(type.Namespace)) { result = GetRandomNamespace(); } else { result = type.Namespace; } return result; } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; using System.Globalization; namespace SharpMath.Optimization.DualNumbers { /// <summary> /// This class represents a function value and its first derivatives at a given point. Several standard /// mathematical operations are defined. Compare with <see cref="DualNumber" />. The class is immutable. /// </summary> [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{Value}")] public sealed class ReducedDualNumber { private static ReducedDualNumber zero; private double value, multiplier; private Vector gradient; static ReducedDualNumber() { // Used very often (e.g. in matrix initialization). zero = new ReducedDualNumber(0.0); } public ReducedDualNumber(double value) : this(value, null) { } public ReducedDualNumber(double value, Vector gradient) : this(value, gradient, 1.0) { } /// <summary> /// Using this constructor we may reuse the gradient vector instance for all unary operations. /// </summary> private ReducedDualNumber(double value, Vector gradient, double multiplier) { this.value = value; this.gradient = gradient; this.multiplier = multiplier; } /// <summary> /// Constructor for binary operations. /// </summary> private ReducedDualNumber(double value, Vector gradient1, double multiplier1, Vector gradient2, double multiplier2) { this.value = value; if (gradient1 != null && gradient2 != null) { // This is the only situation where we have to create a new gradient vector instance. gradient = multiplier1 * gradient1 + multiplier2 * gradient2; multiplier = 1.0; } else if (gradient1 != null) { gradient = gradient1; multiplier = multiplier1; } else if (gradient2 != null) { gradient = gradient2; multiplier = multiplier2; } } public override string ToString() { return ToString(null); } public string ToString(string format) { return value.ToString(format, CultureInfo.InvariantCulture); } /// <summary> /// Use the DualScalar returned by this method to represent variables as the starting points of the /// calculation. The gradient of a variable with respect to a set of variables is always a unit vector. /// </summary> public static ReducedDualNumber Basis(double value, int n, int i) { return new ReducedDualNumber(value, Vector.Basis(n, i)); } public static ReducedDualNumber Exp(ReducedDualNumber s) { double u = Math.Exp(s.value); return new ReducedDualNumber(u, s.gradient, s.multiplier * u); } public static ReducedDualNumber Log(ReducedDualNumber s) { return new ReducedDualNumber(Math.Log(s.value), s.gradient, s.multiplier / s.value); } public static ReducedDualNumber Sqr(ReducedDualNumber s) { return new ReducedDualNumber(s.value * s.value, s.gradient, 2.0 * s.multiplier * s.value); } public static ReducedDualNumber Sqrt(ReducedDualNumber s) { double u = Math.Sqrt(s.value); return new ReducedDualNumber(u, s.gradient, 0.5 * s.multiplier / u); } public static ReducedDualNumber Pow(ReducedDualNumber s, double t) { return new ReducedDualNumber(Math.Pow(s.value, t), s.gradient, t * Math.Pow(s.value, t - 1.0) * s.multiplier); } public static ReducedDualNumber Pow(ReducedDualNumber s, ReducedDualNumber t) { double u = Math.Pow(s.value, t.value); return new ReducedDualNumber(u, s.gradient, t.value * Math.Pow(s.value, t.value - 1.0) * s.multiplier, t.gradient, u * Math.Log(s.value) * t.multiplier); } public static implicit operator ReducedDualNumber(double s) { if (s == 0.0) { return zero; } return new ReducedDualNumber(s); } public static ReducedDualNumber operator +(ReducedDualNumber s, ReducedDualNumber t) { return new ReducedDualNumber(s.value + t.value, s.gradient, s.multiplier, t.gradient, t.multiplier); } public static ReducedDualNumber operator +(ReducedDualNumber s, double t) { return new ReducedDualNumber(s.value + t, s.gradient, s.multiplier); } public static ReducedDualNumber operator +(double s, ReducedDualNumber t) { return t + s; } public static ReducedDualNumber operator -(ReducedDualNumber s) { return new ReducedDualNumber(-s.value, s.gradient, -s.multiplier); } public static ReducedDualNumber operator -(ReducedDualNumber s, ReducedDualNumber t) { return new ReducedDualNumber(s.value - t.value, s.gradient, s.multiplier, t.gradient, -t.multiplier); } public static ReducedDualNumber operator -(ReducedDualNumber s, double t) { return new ReducedDualNumber(s.value - t, s.gradient, s.multiplier); } public static ReducedDualNumber operator -(double s, ReducedDualNumber t) { return new ReducedDualNumber(s - t.value, t.gradient, -t.multiplier); } public static ReducedDualNumber operator *(ReducedDualNumber s, ReducedDualNumber t) { return new ReducedDualNumber(s.value * t.value, s.gradient, t.value * s.multiplier, t.gradient, s.value * t.multiplier); } public static ReducedDualNumber operator *(ReducedDualNumber s, double t) { return new ReducedDualNumber(s.value * t, s.gradient, t * s.multiplier); } public static ReducedDualNumber operator *(double s, ReducedDualNumber t) { return t * s; } public static ReducedDualNumber operator /(ReducedDualNumber s, ReducedDualNumber t) { return new ReducedDualNumber(s.value / t.value, s.gradient, s.multiplier / t.value, t.gradient, -s.value * t.multiplier / (t.value * t.value)); } public static ReducedDualNumber operator /(ReducedDualNumber s, double t) { return s * (1.0 / t); } public static ReducedDualNumber operator /(double s, ReducedDualNumber t) { return new ReducedDualNumber(s / t.value, t.gradient, -s * t.multiplier / (t.value * t.value)); } public double Value { get { return value; } } public Vector Gradient { get { if (multiplier != 1.0 && gradient != null) { gradient *= multiplier; multiplier = 1.0; } return gradient; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Miruken.AspNet.TestWeb.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// PropertyOperations operations. /// </summary> public partial interface IPropertyOperations { /// <summary> /// Lists a collection of properties defined within a service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PropertyContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<PropertyContract> odataQuery = default(ODataQuery<PropertyContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the details of the property specified by its identifier. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='propId'> /// Identifier of the property. /// </param> /// <param name='customHeaders'> /// The 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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PropertyContract,PropertyGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a property. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='propId'> /// Identifier of the property. /// </param> /// <param name='parameters'> /// Create parameters. /// </param> /// <param name='customHeaders'> /// The 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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PropertyContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, PropertyContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the specific property. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='propId'> /// Identifier of the property. /// </param> /// <param name='parameters'> /// Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the property to update. A value /// of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='customHeaders'> /// The 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="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, PropertyUpdateParameters parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes specific property from the the API Management service /// instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='propId'> /// Identifier of the property. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the property to delete. A value /// of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='customHeaders'> /// The 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="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string propId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists a collection of properties defined within a service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<PropertyContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// // Properties.cs: This class implements IAudioCodec and IVideoCodec // and combines codecs to create generic media properties for a file. // // Author: // Brian Nickel (brian.nickel@gmail.com) // // Original Source: // audioproperties.cpp from TagLib // // Copyright (C) 2006,2007 Brian Nickel // Copyright (C) 2003 Scott Wheeler (Original Implementation) // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; using System.Text; using System.Collections.Generic; namespace TagLib { /// <summary> /// This class implements <see cref="IAudioCodec" />, <see /// cref="IVideoCodec" /> and <see cref="IPhotoCodec" /> /// and combines codecs to create generic media properties /// for a file. /// </summary> public class Properties : IAudioCodec, IVideoCodec, IPhotoCodec { #region Private Fields /// <summary> /// Contains the codecs. /// </summary> private ICodec[] codecs = new ICodec [0]; /// <summary> /// Contains the duration. /// </summary> private TimeSpan duration = TimeSpan.Zero; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="Properties" /> with no codecs or duration. /// </summary> /// <remarks> /// <para>This constructor is used when media properties are /// not read.</para> /// </remarks> public Properties () { } /// <summary> /// Constructs and initializes a new instance of <see /// cref="Properties" /> with a specified duration and array /// of codecs. /// </summary> /// <param name="duration"> /// A <see cref="TimeSpan" /> containing the duration of the /// media, or <see cref="TimeSpan.Zero" /> if the duration is /// to be read from the codecs. /// </param> /// <param name="codecs"> /// A <see cref="ICodec[]" /> containing the codecs to be /// used in the new instance. /// </param> public Properties (TimeSpan duration, params ICodec[] codecs) { this.duration = duration; if (codecs != null) this.codecs = codecs; } /// <summary> /// Constructs and initializes a new instance of <see /// cref="Properties" /> with a specified duration and /// enumaration of codecs. /// </summary> /// <param name="duration"> /// A <see cref="TimeSpan" /> containing the duration of the /// media, or <see cref="TimeSpan.Zero" /> if the duration is /// to be read from the codecs. /// </param> /// <param name="codecs"> /// A <see cref="T:System.Collections.Generic.IEnumerable`1" /> object containing the /// codec to be used in the new instance. /// </param> public Properties (TimeSpan duration, IEnumerable<ICodec> codecs) { this.duration = duration; if (codecs != null) this.codecs = new List<ICodec> (codecs) .ToArray (); } #endregion #region Public Properties /// <summary> /// Gets the codecs contained in the current instance. /// </summary> /// <value> /// A <see cref="T:System.Collections.Generic.IEnumerable`1" /> object containing the /// <see cref="ICodec" /> objects contained in the current /// instance. /// </value> public IEnumerable<ICodec> Codecs { get {return codecs;} } #endregion #region ICodec /// <summary> /// Gets the duration of the media represented by the current /// instance. /// </summary> /// <value> /// A <see cref="TimeSpan" /> containing the duration of the /// media represented by the current instance. /// </value> /// <remarks> /// If the duration was set in the constructor, that value is /// returned. Otherwise, the longest codec duration is used. /// </remarks> public TimeSpan Duration { get { TimeSpan duration = this.duration; if (duration != TimeSpan.Zero) return duration; foreach (ICodec codec in codecs) if (codec != null && codec.Duration > duration) duration = codec.Duration; return duration; } } /// <summary> /// Gets the types of media represented by the current /// instance. /// </summary> /// <value> /// A bitwise combined <see cref="MediaTypes" /> containing /// the types of media represented by the current instance. /// </value> public MediaTypes MediaTypes { get { MediaTypes types = MediaTypes.None; foreach (ICodec codec in codecs) if (codec != null) types |= codec.MediaTypes; return types; } } /// <summary> /// Gets a string description of the media represented by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a description /// of the media represented by the current instance. /// </value> /// <remarks> /// The value contains the descriptions of the codecs joined /// by colons. /// </remarks> public string Description { get { StringBuilder builder = new StringBuilder (); foreach (ICodec codec in codecs) { if (codec == null) continue; if (builder.Length != 0) builder.Append ("; "); builder.Append (codec.Description); } return builder.ToString (); } } #endregion #region IAudioCodec /// <summary> /// Gets the bitrate of the audio represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> containing the bitrate of the audio /// represented by the current instance. /// </value> /// <remarks> /// This value is equal to the first non-zero audio bitrate. /// </remarks> public int AudioBitrate { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Audio) == 0) continue; IAudioCodec audio = codec as IAudioCodec; if (audio != null && audio.AudioBitrate != 0) return audio.AudioBitrate; } return 0; } } /// <summary> /// Gets the sample rate of the audio represented by the /// current instance. /// </summary> /// <value> /// A <see cref="int" /> containing the sample rate of the /// audio represented by the current instance. /// </value> /// <remarks> /// This value is equal to the first non-zero audio sample /// rate. /// </remarks> public int AudioSampleRate { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Audio) == 0) continue; IAudioCodec audio = codec as IAudioCodec; if (audio != null && audio.AudioSampleRate != 0) return audio.AudioSampleRate; } return 0; } } /// <summary> /// Gets the number of bits per sample in the audio /// represented by the current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the number of bits /// per sample in the audio represented by the current /// instance. /// </value> /// <remarks> /// This value is equal to the first non-zero quantization. /// </remarks> public int BitsPerSample { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Audio) == 0) continue; ILosslessAudioCodec lossless = codec as ILosslessAudioCodec; if (lossless != null && lossless.BitsPerSample != 0) return lossless.BitsPerSample; } return 0; } } /// <summary> /// Gets the number of channels in the audio represented by /// the current instance. /// </summary> /// <value> /// A <see cref="int" /> object containing the number of /// channels in the audio represented by the current /// instance. /// </value> /// <remarks> /// This value is equal to the first non-zero audio channel /// count. /// </remarks> public int AudioChannels { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Audio) == 0) continue; IAudioCodec audio = codec as IAudioCodec; if (audio != null && audio.AudioChannels != 0) return audio.AudioChannels; } return 0; } } #endregion #region IVideoCodec /// <summary> /// Gets the width of the video represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> containing the width of the video /// represented by the current instance. /// </value> /// <remarks> /// This value is equal to the first non-zero video width. /// </remarks> public int VideoWidth { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Video) == 0) continue; IVideoCodec video = codec as IVideoCodec; if (video != null && video.VideoWidth != 0) return video.VideoWidth; } return 0; } } /// <summary> /// Gets the height of the video represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> containing the height of the video /// represented by the current instance. /// </value> /// <remarks> /// This value is equal to the first non-zero video height. /// </remarks> public int VideoHeight { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Video) == 0) continue; IVideoCodec video = codec as IVideoCodec; if (video != null && video.VideoHeight != 0) return video.VideoHeight; } return 0; } } #endregion #region IPhotoCodec /// <summary> /// Gets the width of the photo represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the width of the /// photo represented by the current instance. /// </value> public int PhotoWidth { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Photo) == 0) continue; IPhotoCodec photo = codec as IPhotoCodec; if (photo != null && photo.PhotoWidth != 0) return photo.PhotoWidth; } return 0; } } /// <summary> /// Gets the height of the photo represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the height of the /// photo represented by the current instance. /// </value> public int PhotoHeight { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Photo) == 0) continue; IPhotoCodec photo = codec as IPhotoCodec; if (photo != null && photo.PhotoHeight != 0) return photo.PhotoHeight; } return 0; } } /// <summary> /// Gets the (format specific) quality indicator of the photo /// represented by the current instance. /// </summary> /// <value> /// A <see cref="int" /> value indicating the quality. A value /// 0 means that there was no quality indicator for the format /// or the file. /// </value> public int PhotoQuality { get { foreach (ICodec codec in codecs) { if (codec == null || (codec.MediaTypes & MediaTypes.Photo) == 0) continue; IPhotoCodec photo = codec as IPhotoCodec; if (photo != null && photo.PhotoQuality != 0) return photo.PhotoQuality; } return 0; } } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using NLog.Filters; using NLog.Targets; /// <summary> /// Represents a logging rule. An equivalent of &lt;logger /&gt; configuration element. /// </summary> [NLogConfigurationItem] public class LoggingRule { private ILoggingRuleLevelFilter _logLevelFilter = LoggingRuleLevelFilter.Off; private LoggerNameMatcher _loggerNameMatcher = LoggerNameMatcher.Create(null); /// <summary> /// Create an empty <see cref="LoggingRule" />. /// </summary> public LoggingRule() :this(null) { } /// <summary> /// Create an empty <see cref="LoggingRule" />. /// </summary> public LoggingRule(string ruleName) { RuleName = ruleName; Filters = new List<Filter>(); ChildRules = new List<LoggingRule>(); Targets = new List<Target>(); } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> and <paramref name="maxLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target) : this() { LoggerNamePattern = loggerNamePattern; Targets.Add(target); EnableLoggingForLevels(minLevel, maxLevel); } /// <summary> /// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> which writes to <paramref name="target"/>. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target) : this() { LoggerNamePattern = loggerNamePattern; Targets.Add(target); EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); } /// <summary> /// Create a (disabled) <see cref="LoggingRule" />. You should call <see cref="EnableLoggingForLevel"/> or see cref="EnableLoggingForLevels"/> to enable logging. /// </summary> /// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param> /// <param name="target">Target to be written to when the rule matches.</param> public LoggingRule(string loggerNamePattern, Target target) : this() { LoggerNamePattern = loggerNamePattern; Targets.Add(target); } /// <summary> /// Rule identifier to allow rule lookup /// </summary> public string RuleName { get; set; } /// <summary> /// Gets a collection of targets that should be written to when this rule matches. /// </summary> public IList<Target> Targets { get; } /// <summary> /// Gets a collection of child rules to be evaluated when this rule matches. /// </summary> public IList<LoggingRule> ChildRules { get; } internal List<LoggingRule> GetChildRulesThreadSafe() { lock (ChildRules) return ChildRules.ToList(); } internal List<Target> GetTargetsThreadSafe() { lock (Targets) return Targets.ToList(); } internal bool RemoveTargetThreadSafe(Target target) { lock (Targets) return Targets.Remove(target); } /// <summary> /// Gets a collection of filters to be checked before writing to targets. /// </summary> public IList<Filter> Filters { get; } /// <summary> /// Gets or sets a value indicating whether to quit processing any further rule when this one matches. /// </summary> public bool Final { get; set; } /// <summary> /// Gets or sets logger name pattern. /// </summary> /// <remarks> /// Logger name pattern used by <see cref="NameMatches(string)"/> to check if a logger name matches this rule. /// It may include one or more '*' or '?' wildcards at any position. /// <list type="bullet"> /// <item>'*' means zero or more occurrences of any character</item> /// <item>'?' means exactly one occurrence of any character</item> /// </list> /// </remarks> public string LoggerNamePattern { get => _loggerNameMatcher.Pattern; set { _loggerNameMatcher = LoggerNameMatcher.Create(value); } } /// <summary> /// Gets the collection of log levels enabled by this rule. /// </summary> [NLogConfigurationIgnoreProperty] public ReadOnlyCollection<LogLevel> Levels { get { var enabledLogLevels = new List<LogLevel>(); var currentLogLevels = _logLevelFilter.LogLevels; for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (currentLogLevels[i]) { enabledLogLevels.Add(LogLevel.FromOrdinal(i)); } } return enabledLogLevels.AsReadOnly(); } } /// <summary> /// Default action if none of the filters match /// </summary> public FilterResult DefaultFilterResult { get; set; } = FilterResult.Neutral; /// <summary> /// Enables logging for a particular level. /// </summary> /// <param name="level">Level to be enabled.</param> public void EnableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, true); } /// <summary> /// Enables logging for a particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="minLevel">Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, true); } internal void EnableLoggingForLevels(NLog.Layouts.SimpleLayout simpleLayout) { _logLevelFilter = new DynamicLogLevelFilter(this, simpleLayout); } internal void EnableLoggingForRange(Layouts.SimpleLayout minLevel, Layouts.SimpleLayout maxLevel) { _logLevelFilter = new DynamicRangeLevelFilter(this, minLevel, maxLevel); } /// <summary> /// Disables logging for a particular level. /// </summary> /// <param name="level">Level to be disabled.</param> public void DisableLoggingForLevel(LogLevel level) { if (level == LogLevel.Off) { return; } _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, false); } /// <summary> /// Disables logging for particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. /// </summary> /// <param name="minLevel">Minimum log level to be disables.</param> /// <param name="maxLevel">Maximum log level to de disabled.</param> public void DisableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, false); } /// <summary> /// Enables logging the levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. All the other levels will be disabled. /// </summary> /// <param name="minLevel">>Minimum log level needed to trigger this rule.</param> /// <param name="maxLevel">Maximum log level needed to trigger this rule.</param> public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel) { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(LogLevel.MinLevel, LogLevel.MaxLevel, false).SetLoggingLevels(minLevel, maxLevel, true); } /// <summary> /// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { var sb = new StringBuilder(); sb.Append(_loggerNameMatcher.ToString()); sb.Append(" levels: [ "); var currentLogLevels = _logLevelFilter.LogLevels; for (int i = 0; i < currentLogLevels.Length; ++i) { if (currentLogLevels[i]) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString()); } } sb.Append("] appendTo: [ "); foreach (Target app in GetTargetsThreadSafe()) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", app.Name); } sb.Append("]"); return sb.ToString(); } /// <summary> /// Checks whether te particular log level is enabled for this rule. /// </summary> /// <param name="level">Level to be checked.</param> /// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns> public bool IsLoggingEnabledForLevel(LogLevel level) { if (level == LogLevel.Off) { return false; } var currentLogLevels = _logLevelFilter.LogLevels; return currentLogLevels[level.Ordinal]; } /// <summary> /// Checks whether given name matches the <see cref="LoggerNamePattern"/>. /// </summary> /// <param name="loggerName">String to be matched.</param> /// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns> public bool NameMatches(string loggerName) { return _loggerNameMatcher.NameMatches(loggerName); } } }
//------------------------------------------------------------------------------ // <copyright file="FileDialog.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Text; using System.Threading; using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Security.Permissions; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.IO; using ArrayList = System.Collections.ArrayList; using Encoding = System.Text.Encoding; using Microsoft.Win32; using System.Security; using System.Runtime.Versioning; using CharBuffer = System.Windows.Forms.UnsafeNativeMethods.CharBuffer; /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog"]/*' /> /// <devdoc> /// <para> /// Displays a dialog window from which the user can select a file. /// </para> /// </devdoc> [ DefaultEvent("FileOk"), DefaultProperty("FileName") ] public abstract partial class FileDialog : CommonDialog { private const int FILEBUFSIZE = 8192; /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.EventFileOk"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> protected static readonly object EventFileOk = new object(); internal const int OPTION_ADDEXTENSION = unchecked(unchecked((int)0x80000000)); internal int options; private string title; private string initialDir; private string defaultExt; private string[] fileNames; private bool securityCheckFileNames; private string filter; private int filterIndex; private bool supportMultiDottedExtensions; private bool ignoreSecondFileOkNotification; // Used for VS Whidbey 95342 private int okNotificationCount; // Same private CharBuffer charBuffer; private IntPtr dialogHWnd; /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FileDialog"]/*' /> /// <devdoc> /// <para> /// In an inherited class, /// initializes a new instance of the <see cref='System.Windows.Forms.FileDialog'/> /// class. /// </para> /// </devdoc> [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not call Reset // it would be a breaking change. ] internal FileDialog() { Reset(); } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.AddExtension"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the /// dialog box automatically adds an extension to a /// file name if the user omits the extension. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.FDaddExtensionDescr) ] public bool AddExtension { get { return GetOption(OPTION_ADDEXTENSION); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(OPTION_ADDEXTENSION, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.CheckFileExists"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating whether /// the dialog box displays a warning if the user specifies a file name that does not exist.</para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.FDcheckFileExistsDescr) ] public virtual bool CheckFileExists { get { return GetOption(NativeMethods.OFN_FILEMUSTEXIST); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(NativeMethods.OFN_FILEMUSTEXIST, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.CheckPathExists"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the /// dialog box displays a warning if the user specifies a path that does not exist. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.FDcheckPathExistsDescr) ] public bool CheckPathExists { get { return GetOption(NativeMethods.OFN_PATHMUSTEXIST); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(NativeMethods.OFN_PATHMUSTEXIST, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.DefaultExt"]/*' /> /// <devdoc> /// <para> /// Gets or sets the default file extension. /// /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(""), SRDescription(SR.FDdefaultExtDescr) ] public string DefaultExt { get { return defaultExt == null? "": defaultExt; } set { if (value != null) { if (value.StartsWith(".")) value = value.Substring(1); else if (value.Length == 0) value = null; } defaultExt = value; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.DereferenceLinks"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value /// indicating whether the dialog box returns the location of the file referenced by the shortcut or /// whether it returns the location of the shortcut (.lnk). /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.FDdereferenceLinksDescr) ] public bool DereferenceLinks { get { return !GetOption(NativeMethods.OFN_NODEREFERENCELINKS); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(NativeMethods.OFN_NODEREFERENCELINKS, !value); } } internal string DialogCaption { get { int textLen = SafeNativeMethods.GetWindowTextLength(new HandleRef(this, dialogHWnd)); StringBuilder sb = new StringBuilder(textLen+1); UnsafeNativeMethods.GetWindowText(new HandleRef(this, dialogHWnd), sb, sb.Capacity); return sb.ToString(); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FileName"]/*' /> /// <devdoc> /// <para> /// Gets /// or sets a string containing /// the file name selected in the file dialog box. /// </para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(""), SRDescription(SR.FDfileNameDescr) ] public string FileName { get { if (fileNames == null) { return ""; } else { if (fileNames[0].Length > 0) { // See if we need to perform a security check on file names. We need // to do this if the set of file names was provided by the file dialog. // A developer can set file names through the FileDialog API as well, // but we don't need to check those since the developer can provide any // name s/he wants. This is important because it is otherwise possible // to get the FileName property to accept garbage, but throw during get. if (securityCheckFileNames) { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileIO(" + fileNames[0] + ") Demanded"); IntSecurity.DemandFileIO(FileIOPermissionAccess.AllAccess, fileNames[0]); } return fileNames[0]; } else { return ""; } } } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); if (value == null) { fileNames = null; } else { fileNames = new string[] {value}; } // As the developer has called this API and set the file name with an arbitrary value, // we do not need to perform a security check on the name. securityCheckFileNames = false; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FileNames"]/*' /> /// <devdoc> /// <para> /// Gets the file /// names of all selected files in the dialog box. /// </para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.FDFileNamesDescr) ] public string[] FileNames { get{ string[] files = FileNamesInternal; // See if we need to perform a security check on file names. We need // to do this if the set of file names was provided by the file dialog. // A developer can set file names through the FileDialog API as well, // but we don't need to check those since the developer can provide any // name s/he wants. This is important because it is otherwise possible // to get the FileName property to accept garbage, but throw during get. if (securityCheckFileNames) { foreach (string file in files) { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileIO(" + file + ") Demanded"); IntSecurity.DemandFileIO(FileIOPermissionAccess.AllAccess, file); } } return files; } } internal string[] FileNamesInternal { get { if (fileNames == null) { return new string[0]; } else { return(string[])fileNames.Clone(); } } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.Filter"]/*' /> /// <devdoc> /// <para> /// Gets /// or sets the current file name filter string, /// which determines the choices that appear in the "Save as file type" or /// "Files of type" box in the dialog box. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(""), Localizable(true), SRDescription(SR.FDfilterDescr) ] public string Filter { get { return filter == null? "": filter; } set { if (value != filter) { if (value != null && value.Length > 0) { string[] formats = value.Split('|'); if (formats == null || formats.Length % 2 != 0) { throw new ArgumentException(SR.GetString(SR.FileDialogInvalidFilter)); } } else { value = null; } filter = value; } } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FilterExtensions"]/*' /> /// <devdoc> /// Extracts the file extensions specified by the current file filter into /// an array of strings. None of the extensions contain .'s, and the /// default extension is first. /// </devdoc> private string[] FilterExtensions { get { string filter = this.filter; ArrayList extensions = new ArrayList(); // First extension is the default one. It's a little strange if DefaultExt // is not in the filters list, but I guess it's legal. if (defaultExt != null) extensions.Add(defaultExt); if (filter != null) { string[] tokens = filter.Split('|'); if ((filterIndex * 2) - 1 >= tokens.Length) { throw new InvalidOperationException(SR.GetString(SR.FileDialogInvalidFilterIndex)); } if (filterIndex > 0) { string[] exts = tokens[(filterIndex * 2) - 1].Split(';'); foreach (string ext in exts) { int i = this.supportMultiDottedExtensions ? ext.IndexOf('.') : ext.LastIndexOf('.'); if (i >= 0) { extensions.Add(ext.Substring(i + 1, ext.Length - (i + 1))); } } } } string[] temp = new string[extensions.Count]; extensions.CopyTo(temp, 0); return temp; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FilterIndex"]/*' /> /// <devdoc> /// <para> /// Gets or sets the index of the filter currently selected in the file dialog box. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(1), SRDescription(SR.FDfilterIndexDescr) ] public int FilterIndex { get { return filterIndex; } set { filterIndex = value; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.InitialDirectory"]/*' /> /// <devdoc> /// <para> /// Gets or sets the initial directory displayed by the file dialog /// box. /// </para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(""), SRDescription(SR.FDinitialDirDescr) ] public string InitialDirectory { get { return initialDir == null? "": initialDir; } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); initialDir = value; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.Instance"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Gets the Win32 instance handle for the application. /// </para> /// </devdoc> /* SECURITYUNDONE : should require EventQueue permission */ protected virtual IntPtr Instance { [ SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode), SecurityPermission(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode) ] [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] get { return UnsafeNativeMethods.GetModuleHandle(null); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.Options"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Gets the Win32 common Open File Dialog OFN_* option flags. /// </para> /// </devdoc> protected int Options { get { return options & (NativeMethods.OFN_READONLY | NativeMethods.OFN_HIDEREADONLY | NativeMethods.OFN_NOCHANGEDIR | NativeMethods.OFN_SHOWHELP | NativeMethods.OFN_NOVALIDATE | NativeMethods.OFN_ALLOWMULTISELECT | NativeMethods.OFN_PATHMUSTEXIST | NativeMethods.OFN_NODEREFERENCELINKS); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.RestoreDirectory"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the dialog box restores the current directory before /// closing. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.FDrestoreDirectoryDescr) ] public bool RestoreDirectory { get { return GetOption(NativeMethods.OFN_NOCHANGEDIR); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(NativeMethods.OFN_NOCHANGEDIR, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.ShowHelp"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating /// whether whether the Help button is displayed in the file dialog. /// /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.FDshowHelpDescr) ] public bool ShowHelp { get { return GetOption(NativeMethods.OFN_SHOWHELP); } set { SetOption(NativeMethods.OFN_SHOWHELP, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.SupportMultipleExtensions"]/*' /> /// <devdoc> /// <para> /// Gets or sets whether def or abc.def is the extension of the file filename.abc.def /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(false), SRDescription(SR.FDsupportMultiDottedExtensionsDescr) ] public bool SupportMultiDottedExtensions { get { return this.supportMultiDottedExtensions; } set { this.supportMultiDottedExtensions = value; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.Title"]/*' /> /// <devdoc> /// <para> /// Gets or sets the file dialog box title. /// </para> /// </devdoc> [ SRCategory(SR.CatAppearance), DefaultValue(""), Localizable(true), SRDescription(SR.FDtitleDescr) ] public string Title { get { return title == null? "": title; } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); title = value; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.ValidateNames"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the dialog box accepts only valid /// Win32 file names. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.FDvalidateNamesDescr) ] public bool ValidateNames { get { return !GetOption(NativeMethods.OFN_NOVALIDATE); } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded"); IntSecurity.FileDialogCustomization.Demand(); SetOption(NativeMethods.OFN_NOVALIDATE, !value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.FileOk"]/*' /> /// <devdoc> /// <para> /// Occurs when the user clicks on the Open or Save button on a file dialog /// box. /// </para> /// <remarks> /// <para> /// For information about handling events, see <see topic='cpconEventsOverview'/>. /// </para> /// </remarks> /// </devdoc> [SRDescription(SR.FDfileOkDescr)] public event CancelEventHandler FileOk { add { Events.AddHandler(EventFileOk, value); } remove { Events.RemoveHandler(EventFileOk, value); } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.DoFileOk"]/*' /> /// <devdoc> /// Processes the CDN_FILEOK notification. /// </devdoc> private bool DoFileOk(IntPtr lpOFN) { NativeMethods.OPENFILENAME_I ofn = (NativeMethods.OPENFILENAME_I)UnsafeNativeMethods.PtrToStructure(lpOFN, typeof(NativeMethods.OPENFILENAME_I)); int saveOptions = options; int saveFilterIndex = filterIndex; string[] saveFileNames = fileNames; bool saveSecurityCheckFileNames = securityCheckFileNames; bool ok = false; try { options = options & ~NativeMethods.OFN_READONLY | ofn.Flags & NativeMethods.OFN_READONLY; filterIndex = ofn.nFilterIndex; charBuffer.PutCoTaskMem(ofn.lpstrFile); // We are filling in the file names list with secure // data. Any access to this list now will require // a security demand. We set this bit before actually // setting the names; otherwise a thread ---- could // expose them. securityCheckFileNames = true; Thread.MemoryBarrier(); if ((options & NativeMethods.OFN_ALLOWMULTISELECT) == 0) { fileNames = new string[] {charBuffer.GetString()}; } else { fileNames = GetMultiselectFiles(charBuffer); } if (ProcessFileNames()) { CancelEventArgs ceevent = new CancelEventArgs(); if (NativeWindow.WndProcShouldBeDebuggable) { OnFileOk(ceevent); ok = !ceevent.Cancel; } else { try { OnFileOk(ceevent); ok = !ceevent.Cancel; } catch (Exception e) { Application.OnThreadException(e); } } } } finally { if (!ok) { securityCheckFileNames = saveSecurityCheckFileNames; Thread.MemoryBarrier(); fileNames = saveFileNames; options = saveOptions; filterIndex = saveFilterIndex; } } return ok; } /// SECREVIEW: ReviewImperativeSecurity /// vulnerability to watch out for: A method uses imperative security and might be constructing the permission using state information or return values that can change while the demand is active. /// reason for exclude: filename is a local variable and not subject to race conditions. [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal static bool FileExists(string fileName) { bool fileExists = false; try { // SECREVIEW : We must Assert just to check if the file exists. Since // : we are doing this as part of the FileDialog, this is OK. new FileIOPermission(FileIOPermissionAccess.Read, IntSecurity.UnsafeGetFullPath(fileName)).Assert(); try { fileExists = File.Exists(fileName); } finally { CodeAccessPermission.RevertAssert(); } } catch (System.IO.PathTooLongException) { } return fileExists; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.GetMultiselectFiles"]/*' /> /// <devdoc> /// Extracts the filename(s) returned by the file dialog. /// </devdoc> private string[] GetMultiselectFiles(CharBuffer charBuffer) { string directory = charBuffer.GetString(); string fileName = charBuffer.GetString(); if (fileName.Length == 0) return new string[] { directory }; if (directory[directory.Length - 1] != '\\') { directory = directory + "\\"; } ArrayList names = new ArrayList(); do { if (fileName[0] != '\\' && (fileName.Length <= 3 || fileName[1] != ':' || fileName[2] != '\\')) { fileName = directory + fileName; } names.Add(fileName); fileName = charBuffer.GetString(); } while (fileName.Length > 0); string[] temp = new string[names.Count]; names.CopyTo(temp, 0); return temp; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.GetOption"]/*' /> /// <devdoc> /// Returns the state of the given option flag. /// </devdoc> /// <internalonly/> internal bool GetOption(int option) { return(options & option) != 0; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.HookProc"]/*' /> /// <devdoc> /// <para> /// Defines the common dialog box hook procedure that is overridden to add /// specific functionality to the file dialog box. /// </para> /// </devdoc> [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { if (msg == NativeMethods.WM_NOTIFY) { dialogHWnd = UnsafeNativeMethods.GetParent(new HandleRef(null, hWnd)); try { UnsafeNativeMethods.OFNOTIFY notify = (UnsafeNativeMethods.OFNOTIFY)UnsafeNativeMethods.PtrToStructure(lparam, typeof(UnsafeNativeMethods.OFNOTIFY)); switch (notify.hdr_code) { case -601: /* CDN_INITDONE */ MoveToScreenCenter(dialogHWnd); break; case -602: /* CDN_SELCHANGE */ NativeMethods.OPENFILENAME_I ofn = (NativeMethods.OPENFILENAME_I)UnsafeNativeMethods.PtrToStructure(notify.lpOFN, typeof(NativeMethods.OPENFILENAME_I)); // Get the buffer size required to store the selected file names. int sizeNeeded = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, dialogHWnd), 1124 /*CDM_GETSPEC*/, System.IntPtr.Zero, System.IntPtr.Zero); if (sizeNeeded > ofn.nMaxFile) { // A bigger buffer is required. try { int newBufferSize = sizeNeeded + (FILEBUFSIZE / 4); // Allocate new buffer CharBuffer charBufferTmp = CharBuffer.CreateBuffer(newBufferSize); IntPtr newBuffer = charBufferTmp.AllocCoTaskMem(); // Free old buffer Marshal.FreeCoTaskMem(ofn.lpstrFile); // Substitute buffer ofn.lpstrFile = newBuffer; ofn.nMaxFile = newBufferSize; this.charBuffer = charBufferTmp; Marshal.StructureToPtr(ofn, notify.lpOFN, true); Marshal.StructureToPtr(notify, lparam, true); } catch { // intentionaly not throwing here. } } this.ignoreSecondFileOkNotification = false; break; case -604: /* CDN_SHAREVIOLATION */ // See VS Whidbey 95342. When the selected file is locked for writing, // we get this notification followed by *two* CDN_FILEOK notifications. this.ignoreSecondFileOkNotification = true; // We want to ignore the second CDN_FILEOK this.okNotificationCount = 0; // to avoid a second prompt by PromptFileOverwrite. break; case -606: /* CDN_FILEOK */ if (this.ignoreSecondFileOkNotification) { // We got a CDN_SHAREVIOLATION notification and want to ignore the second CDN_FILEOK notification if (this.okNotificationCount == 0) { this.okNotificationCount = 1; // This one is the first and is all right. } else { // This is the second CDN_FILEOK, so we want to ignore it. this.ignoreSecondFileOkNotification = false; UnsafeNativeMethods.SetWindowLong(new HandleRef(null, hWnd), 0, new HandleRef(null, NativeMethods.InvalidIntPtr)); return NativeMethods.InvalidIntPtr; } } if (!DoFileOk(notify.lpOFN)) { UnsafeNativeMethods.SetWindowLong(new HandleRef(null, hWnd), 0, new HandleRef(null, NativeMethods.InvalidIntPtr)); return NativeMethods.InvalidIntPtr; } break; } } catch { if (dialogHWnd != IntPtr.Zero) { UnsafeNativeMethods.EndDialog(new HandleRef(this, dialogHWnd), IntPtr.Zero); } throw; } } return IntPtr.Zero; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.MakeFilterString"]/*' /> /// <devdoc> /// Converts the given filter string to the format required in an OPENFILENAME_I /// structure. /// </devdoc> private static string MakeFilterString(string s, bool dereferenceLinks) { if (s == null || s.Length == 0) { // Workaround for Whidbey bug #5165 // Apply the workaround only when DereferenceLinks is true and OS is at least WinXP. if (dereferenceLinks && System.Environment.OSVersion.Version.Major >= 5) { s = " |*.*"; } else if (s == null) { return null; } } int length = s.Length; char[] filter = new char[length + 2]; s.CopyTo(0, filter, 0, length); for (int i = 0; i < length; i++) { if (filter[i] == '|') filter[i] = (char)0; } filter[length + 1] = (char)0; return new string(filter); } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.OnFileOk"]/*' /> /// <devdoc> /// <para> /// Raises the <see cref='System.Windows.Forms.FileDialog.FileOk'/> event. /// </para> /// </devdoc> protected void OnFileOk(CancelEventArgs e) { CancelEventHandler handler = (CancelEventHandler)Events[EventFileOk]; if (handler != null) handler(this, e); } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.ProcessFileNames"]/*' /> /// <devdoc> /// Processes the filenames entered in the dialog according to the settings /// of the "addExtension", "checkFileExists", "createPrompt", and /// "overwritePrompt" properties. /// </devdoc> private bool ProcessFileNames() { if ((options & NativeMethods.OFN_NOVALIDATE) == 0) { string[] extensions = FilterExtensions; for (int i = 0; i < fileNames.Length; i++) { string fileName = fileNames[i]; if ((options & OPTION_ADDEXTENSION) != 0 && !Path.HasExtension(fileName)) { bool fileMustExist = (options & NativeMethods.OFN_FILEMUSTEXIST) != 0; for (int j = 0; j < extensions.Length; j++) { string currentExtension = Path.GetExtension(fileName); Debug.Assert(!extensions[j].StartsWith("."), "FileDialog.FilterExtensions should not return things starting with '.'"); Debug.Assert(currentExtension.Length == 0 || currentExtension.StartsWith("."), "File.GetExtension should return something that starts with '.'"); string s = fileName.Substring(0, fileName.Length - currentExtension.Length); // we don't want to append the extension if it contains wild cards if (extensions[j].IndexOfAny(new char[] { '*', '?' }) == -1) { s += "." + extensions[j]; } if (!fileMustExist || FileExists(s)) { fileName = s; break; } } fileNames[i] = fileName; } if (!PromptUserIfAppropriate(fileName)) return false; } } return true; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.MessageBoxWithFocusRestore"]/*' /> /// <devdoc> /// <para> /// Prompts the user with a <see cref='System.Windows.Forms.MessageBox'/> /// with the given parameters. It also ensures that /// the focus is set back on the window that had /// the focus to begin with (before we displayed /// the MessageBox). /// </para> /// </devdoc> internal bool MessageBoxWithFocusRestore(string message, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { bool ret; IntPtr focusHandle = UnsafeNativeMethods.GetFocus(); try { ret = RTLAwareMessageBox.Show(null, message, caption, buttons, icon, MessageBoxDefaultButton.Button1, 0) == DialogResult.Yes; } finally { UnsafeNativeMethods.SetFocus(new HandleRef(null, focusHandle)); } return ret; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.PromptFileNotFound"]/*' /> /// <devdoc> /// <para> /// Prompts the user with a <see cref='System.Windows.Forms.MessageBox'/> /// when a file /// does not exist. /// </para> /// </devdoc> private void PromptFileNotFound(string fileName) { MessageBoxWithFocusRestore(SR.GetString(SR.FileDialogFileNotFound, fileName), DialogCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning); } // If it's necessary to throw up a "This file exists, are you sure?" kind of // MessageBox, here's where we do it // Return value is whether or not the user hit "okay". internal virtual bool PromptUserIfAppropriate(string fileName) { if ((options & NativeMethods.OFN_FILEMUSTEXIST) != 0) { if (!FileExists(fileName)) { PromptFileNotFound(fileName); return false; } } return true; } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.Reset"]/*' /> /// <devdoc> /// <para> /// Resets all properties to their default values. /// </para> /// </devdoc> public override void Reset() { options = NativeMethods.OFN_HIDEREADONLY | NativeMethods.OFN_PATHMUSTEXIST | OPTION_ADDEXTENSION; title = null; initialDir = null; defaultExt = null; fileNames = null; filter = null; filterIndex = 1; supportMultiDottedExtensions = false; this._customPlaces.Clear(); } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.RunDialog"]/*' /> /// <devdoc> /// Implements running of a file dialog. /// </devdoc> /// <internalonly/> protected override bool RunDialog(IntPtr hWndOwner) { // See VSWhidbey bug 107000. Shell APIs do not support multisthreaded apartment model. if (Control.CheckForIllegalCrossThreadCalls && Application.OleRequired() != System.Threading.ApartmentState.STA) { throw new System.Threading.ThreadStateException(SR.GetString(SR.DebuggingExceptionOnly, SR.GetString(SR.ThreadMustBeSTA))); } EnsureFileDialogPermission(); if (this.UseVistaDialogInternal) { return RunDialogVista(hWndOwner); } else { return RunDialogOld(hWndOwner); } } internal abstract void EnsureFileDialogPermission(); private bool RunDialogOld(IntPtr hWndOwner) { NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); NativeMethods.OPENFILENAME_I ofn = new NativeMethods.OPENFILENAME_I(); try { charBuffer = CharBuffer.CreateBuffer(FILEBUFSIZE); if (fileNames != null) { charBuffer.PutString(fileNames[0]); } ofn.lStructSize = Marshal.SizeOf(typeof(NativeMethods.OPENFILENAME_I)); // Degrade to the older style dialog if we're not on Win2K. // We do this by setting the struct size to a different value // if (Environment.OSVersion.Platform != System.PlatformID.Win32NT || Environment.OSVersion.Version.Major < 5) { ofn.lStructSize = 0x4C; } ofn.hwndOwner = hWndOwner; ofn.hInstance = Instance; ofn.lpstrFilter = MakeFilterString(filter, this.DereferenceLinks); ofn.nFilterIndex = filterIndex; ofn.lpstrFile = charBuffer.AllocCoTaskMem(); ofn.nMaxFile = FILEBUFSIZE; ofn.lpstrInitialDir = initialDir; ofn.lpstrTitle = title; ofn.Flags = Options | (NativeMethods.OFN_EXPLORER | NativeMethods.OFN_ENABLEHOOK | NativeMethods.OFN_ENABLESIZING); ofn.lpfnHook = hookProcPtr; ofn.FlagsEx = NativeMethods.OFN_USESHELLITEM; if (defaultExt != null && AddExtension) { ofn.lpstrDefExt = defaultExt; } //Security checks happen here return RunFileDialog(ofn); } finally { charBuffer = null; if (ofn.lpstrFile != IntPtr.Zero) { Marshal.FreeCoTaskMem(ofn.lpstrFile); } } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.RunFileDialog"]/*' /> /// <devdoc> /// Implements the actual call to GetOPENFILENAME_I or GetSaveFileName. /// </devdoc> /// <internalonly/> internal abstract bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn); /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.SetOption"]/*' /> /// <devdoc> /// Sets the given option to the given boolean value. /// </devdoc> /// <internalonly/> internal void SetOption(int option, bool value) { if (value) { options |= option; } else { options &= ~option; } } /// <include file='doc\FileDialog.uex' path='docs/doc[@for="FileDialog.ToString"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Provides a string version of this Object. /// </para> /// </devdoc> public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString() + ": Title: " + Title + ", FileName: "); try { sb.Append(FileName); } catch (Exception e) { sb.Append("<"); sb.Append(e.GetType().FullName); sb.Append(">"); } return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { public delegate void TimerCallback(Object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule // all managed timers in the process. // // Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire. // There are roughly two types of timer: // // - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because // the whole point is that the timer only fires if something has gone wrong. // // - scheduled background tasks. These typically do fire, but they usually have quite long durations. // So the impact of spending a few extra cycles to fire these is negligible. // // Because of this, we want to choose a data structure with very fast insert and delete times, but we can live // with linear traversal times when firing timers. // // The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion // and removal, and O(N) traversal when finding expired timers. // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // internal partial class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. private static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { get { return s_queue; } } private TimerQueue() { // empty private constructor to ensure we remain a singleton. } #endregion #region interface to native per-AppDomain timer private int _currentNativeTimerStartTicks; private uint _currentNativeTimerDuration = UInt32.MaxValue; private void EnsureAppDomainTimerFiresBy(uint requestedDuration) { // // The CLR VM's timer implementation does not work well for very long-duration timers. // See kb 950807. // So we'll limit our native timer duration to a "small" value. // This may cause us to attempt to fire timers early, but that's ok - // we'll just see that none of our timers has actually reached its due time, // and schedule the native timer again. // const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); if (_currentNativeTimerDuration != UInt32.MaxValue) { uint elapsed = (uint)(TickCount - _currentNativeTimerStartTicks); if (elapsed >= _currentNativeTimerDuration) return; //the timer's about to fire uint remainingDuration = _currentNativeTimerDuration - elapsed; if (actualDuration >= remainingDuration) return; //the timer will fire earlier than this request } SetTimer(actualDuration); _currentNativeTimerDuration = actualDuration; _currentNativeTimerStartTicks = TickCount; } #endregion #region Firing timers // // The list of timers // private TimerQueueTimer _timers; readonly internal Lock Lock = new Lock(); // // Fire any timers that have expired, and update the native timer to schedule the rest of them. // private void FireNextTimers() { // // we fire the first timer on this thread; any other timers that might have fired are queued // to the ThreadPool. // TimerQueueTimer timerToFireOnThisThread = null; using (LockHolder.Hold(Lock)) { // // since we got here, that means our previous timer has fired. // _currentNativeTimerDuration = UInt32.MaxValue; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; int nowTicks = TickCount; // // Sweep through all timers. The ones that have reached their due time // will fire. We will calculate the next native timer due time from the // other timers. // TimerQueueTimer timer = _timers; while (timer != null) { Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) { // // Remember the next timer in case we delete this one // TimerQueueTimer nextTimer = timer.m_next; if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; timer.m_dueTime = timer.m_period; // // This is a repeating timer; schedule it to run again. // if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } } else { // // Not repeating; remove it from the queue // DeleteTimer(timer); } // // If this is the first timer, we'll fire it on this thread. Otherwise, queue it // to the ThreadPool. // if (timerToFireOnThisThread == null) timerToFireOnThisThread = timer; else QueueTimerCompletion(timer); timer = nextTimer; } else { // // This timer hasn't fired yet. Just update the next time the native timer fires. // uint remaining = timer.m_dueTime - elapsed; if (remaining < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = remaining; } timer = timer.m_next; } } if (haveTimerToSchedule) EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } // // Fire the user timer outside of the lock! // if (timerToFireOnThisThread != null) timerToFireOnThisThread.Fire(); } private static void QueueTimerCompletion(TimerQueueTimer timer) { WaitCallback callback = s_fireQueuedTimerCompletion; if (callback == null) s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion); // Can use "unsafe" variant because we take care of capturing and restoring // the ExecutionContext. ThreadPool.UnsafeQueueUserWorkItem(callback, timer); } private static WaitCallback s_fireQueuedTimerCompletion; private static void FireQueuedTimerCompletion(object state) { ((TimerQueueTimer)state).Fire(); } #endregion #region Queue implementation public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { if (timer.m_dueTime == Timeout.UnsignedInfinite) { // the timer is not in the list; add it (as the head of the list). timer.m_next = _timers; timer.m_prev = null; if (timer.m_next != null) timer.m_next.m_prev = timer; _timers = timer; } timer.m_dueTime = dueTime; timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period; timer.m_startTicks = TickCount; EnsureAppDomainTimerFiresBy(dueTime); return true; } public void DeleteTimer(TimerQueueTimer timer) { if (timer.m_dueTime != Timeout.UnsignedInfinite) { if (timer.m_next != null) timer.m_next.m_prev = timer.m_prev; if (timer.m_prev != null) timer.m_prev.m_next = timer.m_next; if (_timers == timer) _timers = timer.m_next; timer.m_dueTime = Timeout.UnsignedInfinite; timer.m_period = Timeout.UnsignedInfinite; timer.m_startTicks = 0; timer.m_prev = null; timer.m_next = null; } } #endregion } // // A timer in our TimerQueue. // internal sealed partial class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. // // The first four fields are maintained by TimerQueue itself. // internal TimerQueueTimer m_next; internal TimerQueueTimer m_prev; // // The time, according to TimerQueue.TickCount, when this timer's current interval started. // internal int m_startTicks; // // Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire. // internal uint m_dueTime; // // Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval. // internal uint m_period; // // Info about the user's callback // private readonly TimerCallback _timerCallback; private readonly Object _state; private readonly ExecutionContext _executionContext; // // When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only // after all pending callbacks are complete. We set _canceled to prevent any callbacks that // are already queued from running. We track the number of callbacks currently executing in // _callbacksRunning. We set _notifyWhenNoCallbacksRunning only when _callbacksRunning // reaches zero. // private int _callbacksRunning; private volatile bool _canceled; private volatile WaitHandle _notifyWhenNoCallbacksRunning; internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period) { _timerCallback = timerCallback; _state = state; m_dueTime = Timeout.UnsignedInfinite; m_period = Timeout.UnsignedInfinite; _executionContext = ExecutionContext.Capture(); // // After the following statement, the timer may fire. No more manipulation of timer state outside of // the lock is permitted beyond this point! // if (dueTime != Timeout.UnsignedInfinite) Change(dueTime, period); } internal bool Change(uint dueTime, uint period) { bool success; using (LockHolder.Hold(TimerQueue.Instance.Lock)) { if (_canceled) throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); m_period = period; if (dueTime == Timeout.UnsignedInfinite) { TimerQueue.Instance.DeleteTimer(this); success = true; } else { success = TimerQueue.Instance.UpdateTimer(this, dueTime, period); } } return success; } public void Close() { using (LockHolder.Hold(TimerQueue.Instance.Lock)) { if (!_canceled) { _canceled = true; TimerQueue.Instance.DeleteTimer(this); } } } public bool Close(WaitHandle toSignal) { bool success; bool shouldSignal = false; using (LockHolder.Hold(TimerQueue.Instance.Lock)) { if (_canceled) { success = false; } else { _canceled = true; _notifyWhenNoCallbacksRunning = toSignal; TimerQueue.Instance.DeleteTimer(this); if (_callbacksRunning == 0) shouldSignal = true; success = true; } } if (shouldSignal) SignalNoCallbacksRunning(); return success; } internal void Fire() { bool canceled = false; lock (TimerQueue.Instance) { canceled = _canceled; if (!canceled) _callbacksRunning++; } if (canceled) return; CallCallback(); bool shouldSignal = false; using (LockHolder.Hold(TimerQueue.Instance.Lock)) { _callbacksRunning--; if (_canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning != null) shouldSignal = true; } if (shouldSignal) SignalNoCallbacksRunning(); } internal void CallCallback() { ContextCallback callback = s_callCallbackInContext; if (callback == null) s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext); // call directly if EC flow is suppressed if (_executionContext == null) { _timerCallback(_state); } else { ExecutionContext.Run(_executionContext, callback, this); } } private static ContextCallback s_callCallbackInContext; private static void CallCallbackInContext(object state) { TimerQueueTimer t = (TimerQueueTimer)state; t._timerCallback(t._state); } } // // TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer // if the Timer is collected. // This is necessary because Timer itself cannot use its finalizer for this purpose. If it did, // then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize. // You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this // via first-class APIs), but Timer has never offered this, and adding it now would be a breaking // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // internal sealed class TimerHolder { internal TimerQueueTimer m_timer; public TimerHolder(TimerQueueTimer timer) { m_timer = timer; } ~TimerHolder() { m_timer.Close(); } public void Close() { m_timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = m_timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } } public sealed class Timer : MarshalByRefObject, IDisposable { private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder _timer; public Timer(TimerCallback callback, Object state, int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_TimeoutTooLarge); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge); TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm); } [CLSCompliant(false)] public Timer(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { TimerSetup(callback, state, dueTime, period); } public Timer(TimerCallback callback, Object state, long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } public Timer(TimerCallback callback) { int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period); } private void TimerSetup(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { if (callback == null) throw new ArgumentNullException(nameof(TimerCallback)); Contract.EndContractBlock(); _timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period)); } public bool Change(int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Contract.EndContractBlock(); return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(UInt32 dueTime, UInt32 period) { return _timer.m_timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); Contract.EndContractBlock(); return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject == null) throw new ArgumentNullException(nameof(notifyObject)); Contract.EndContractBlock(); return _timer.Close(notifyObject); } public void Dispose() { _timer.Close(); } internal void KeepRootedWhileScheduled() { GC.SuppressFinalize(_timer); } } }
// // $Id: OpenDataSourceDialog.cs 6141 2014-05-05 21:03:47Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // 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.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; using System.Threading; using pwiz.CLI.cv; using pwiz.CLI.data; using pwiz.CLI.msdata; using pwiz.MSGraph; namespace seems { public partial class OpenDataSourceDialog : Form { private ListViewColumnSorter listViewColumnSorter; private BackgroundWorker backgroundSourceLoader; private MSGraphControl ticGraphControl; private class BackgroundSourceLoaderArgs { public BackgroundSourceLoaderArgs() { sourceDirectories = new List<DirectoryInfo>(); sourceFiles = new List<FileInfo>(); sourceTypeFilter = null; getDetails = false; } public SourceInfo[] sourceInfoList; /// <summary> /// Lists paths to Waters, Bruker, Agilent, etc. source directories /// </summary> public List<DirectoryInfo> SourceDirectories { get { return sourceDirectories; } set { sourceDirectories = value; } } private List<DirectoryInfo> sourceDirectories; /// <summary> /// Lists paths to mzML, mzXML, Thermo, etc. source files /// </summary> public List<FileInfo> SourceFiles { get { return sourceFiles; } set { sourceFiles = value; } } private List<FileInfo> sourceFiles; /// <summary> /// The total number of source directories and files. /// </summary> public int TotalSourceCount { get { return sourceDirectories.Count + sourceFiles.Count; } } /// <summary> /// If not null or empty, this string must match getSourceType() for a source to pass the filter /// </summary> public string SourceTypeFilter { get { return sourceTypeFilter; } set { sourceTypeFilter = value; } } private string sourceTypeFilter; /// <summary> /// If true, will open files to get some file-level metadata /// </summary> public bool GetDetails { get { return getDetails; } set { getDetails = value; } } private bool getDetails; } public OpenDataSourceDialog() { InitializeComponent(); listViewColumnSorter = new ListViewColumnSorter(); listView.ListViewItemSorter = listViewColumnSorter; DialogResult = DialogResult.Cancel; string[] sourceTypes = new string[] { "Any spectra format", "mzML", //"mzData", "mzXML", "mz5", "mzMLb", "Thermo RAW", "Waters RAW", "ABSciex WIFF", //"Bruker/Agilent YEP", //"Bruker BAF", //"Bruker FID", "Bruker Analysis", "Agilent MassHunter", "Mascot Generic", "Bruker Data Exchange", //"Sequest DTA" }; sourceTypeComboBox.Items.AddRange( sourceTypes ); sourceTypeComboBox.SelectedIndex = 0; ImageList smallImageList = new ImageList(); smallImageList.ColorDepth = ColorDepth.Depth32Bit; smallImageList.Images.Add( Properties.Resources.folder ); smallImageList.Images.Add( Properties.Resources.file ); smallImageList.Images.Add( Properties.Resources.DataProcessing ); listView.SmallImageList = smallImageList; TreeView tv = new TreeView(); tv.Indent = 8; TreeNode lookInNode = tv.Nodes.Add( "My Recent Documents", "My Recent Documents", 0, 0 ); lookInNode.Tag = lookInNode.Text; lookInComboBox.Items.Add( lookInNode ); TreeNode desktopNode = tv.Nodes.Add( "Desktop", "Desktop", 1, 1 ); desktopNode.Tag = desktopNode.Text; lookInComboBox.Items.Add( desktopNode ); lookInNode = desktopNode.Nodes.Add( "My Documents", "My Documents", 2, 2 ); lookInNode.Tag = lookInNode.Text; lookInComboBox.Items.Add( lookInNode ); TreeNode myComputerNode = desktopNode.Nodes.Add( "My Computer", "My Computer", 3, 3 ); myComputerNode.Tag = myComputerNode.Text; lookInComboBox.Items.Add( myComputerNode ); lookInComboBox.SelectedIndex = 1; lookInComboBox.IntegralHeight = false; lookInComboBox.DropDownHeight = lookInComboBox.Items.Count * lookInComboBox.ItemHeight + 2; ticGraphControl = new MSGraphControl() { Dock = DockStyle.Fill, }; ticGraphControl.GraphPane.Legend.IsVisible = false; ticGraphControl.Visible = false; splitContainer1.Panel2.Controls.Add( ticGraphControl ); splitContainer1.Panel2Collapsed = false; } void initializeBackgroundSourceLoader() { if( backgroundSourceLoader != null ) backgroundSourceLoader.CancelAsync(); backgroundSourceLoader = new BackgroundWorker(); backgroundSourceLoader.WorkerReportsProgress = true; backgroundSourceLoader.WorkerSupportsCancellation = true; backgroundSourceLoader.DoWork += new DoWorkEventHandler( backgroundSourceLoader_DoWork ); backgroundSourceLoader.ProgressChanged += new ProgressChangedEventHandler( backgroundSourceLoader_ProgressChanged ); } void backgroundSourceLoader_ProgressChanged( object sender, ProgressChangedEventArgs arg ) { if( ( sender as BackgroundWorker ).CancellationPending ) return; SourceInfo[] sourceInfoList = arg.UserState as SourceInfo[]; if( sourceInfoList != null ) { foreach( SourceInfo sourceInfo in sourceInfoList ) { // mandatory first pass will be without details for a quick listing; // optional second pass will have details of already listed items if( !sourceInfo.hasDetails ) // first pass { if( sourceInfo.type == "File Folder" || sourceTypeComboBox.SelectedIndex == 0 || sourceTypeComboBox.SelectedItem.ToString() == sourceInfo.type ) { // subitems: Name, Type, Spectra, Size, Date Modified ListViewItem item; if( sourceInfo.type == "File Folder" ) item = new ListViewItem( sourceInfo.ToArray(), 0 ); else item = new ListViewItem( sourceInfo.ToArray(), 2 ); item.SubItems[3].Tag = (object) sourceInfo.size; item.SubItems[4].Tag = (object) sourceInfo.dateModified; item.Name = sourceInfo.name; listView.Items.Add( item ); } } else // second pass { ListViewItem item = listView.Items[sourceInfo.name]; if( item == null ) // a virtual document from a multi-run source { if( sourceInfo.type == "File Folder" ) item = new ListViewItem( sourceInfo.ToArray(), 0 ); else item = new ListViewItem( sourceInfo.ToArray(), 2 ); item.SubItems[3].Tag = (object) sourceInfo.size; item.SubItems[4].Tag = (object) sourceInfo.dateModified; item.Name = sourceInfo.name; listView.Items.Add( item ); } if( sourceInfo.type != "File Folder" ) { item.SubItems[2].Text = sourceInfo.spectra.ToString(); item.SubItems[3].Tag = (object) sourceInfo.size; item.SubItems[4].Tag = (object) sourceInfo.dateModified; item.SubItems[5].Text = sourceInfo.ionSource; item.SubItems[6].Text = sourceInfo.analyzer; item.SubItems[7].Text = sourceInfo.detector; item.SubItems[8].Text = sourceInfo.contentType; } } } } } void backgroundSourceLoader_DoWork( object sender, DoWorkEventArgs arg ) { var worker = sender as BackgroundWorker; var workerArgs = arg.Argument as BackgroundSourceLoaderArgs; var directoriesPassingFilter = new List<DirectoryInfo>(); var filesPassingFilter = new List<FileInfo>(); for( int i = 0; i < workerArgs.SourceDirectories.Count && !backgroundSourceLoader.CancellationPending; ++i ) { try { DirectoryInfo directory = workerArgs.SourceDirectories[i]; FileInfo[] files = directory.GetFiles(); // trigger unauthorized access SourceInfo[] sourceInfo = getSourceInfo( directory, false ); if( sourceInfo == null || sourceInfo.Length == 0 || ( !String.IsNullOrEmpty( workerArgs.SourceTypeFilter ) && sourceInfo[0].type != "File Folder" && sourceInfo[0].type != workerArgs.SourceTypeFilter ) ) continue; directoriesPassingFilter.Add( directory ); worker.ReportProgress( 0, (object) sourceInfo ); } catch { // ignore directories we don't have permission for } } for( int i = 0; i < workerArgs.SourceFiles.Count && !backgroundSourceLoader.CancellationPending; ++i ) { SourceInfo[] sourceInfo = getSourceInfo( workerArgs.SourceFiles[i], false ); if( sourceInfo == null || sourceInfo.Length == 0 || ( !String.IsNullOrEmpty( workerArgs.SourceTypeFilter ) && sourceInfo[0].type != "File Folder" && sourceInfo[0].type != workerArgs.SourceTypeFilter ) ) continue; filesPassingFilter.Add( workerArgs.SourceFiles[i] ); worker.ReportProgress( 0, (object) sourceInfo ); } if( workerArgs.GetDetails ) { for( int i = 0; i < directoriesPassingFilter.Count && !backgroundSourceLoader.CancellationPending; ++i ) worker.ReportProgress( 0, (object) getSourceInfo( directoriesPassingFilter[i], true ) ); for( int i = 0; i < filesPassingFilter.Count && !backgroundSourceLoader.CancellationPending; ++i ) worker.ReportProgress( 0, (object) getSourceInfo( filesPassingFilter[i], true ) ); } arg.Cancel = worker.CancellationPending; } public new DialogResult ShowDialog() { CurrentDirectory = initialDirectory; return base.ShowDialog(); } private Stack<string> previousDirectories = new Stack<string>(); #region Properties private string currentDirectory; private string CurrentDirectory { get { return currentDirectory; } set { if( Directory.Exists( value ) ) { currentDirectory = value; populateListViewFromDirectory( currentDirectory ); populateComboBoxFromDirectory( currentDirectory ); } } } private string initialDirectory; public string InitialDirectory { get { return initialDirectory; } set { initialDirectory = value; } } public string DataSource { get { return dataSources[0]; } } private string[] dataSources; public string[] DataSources { get { return dataSources; } } #endregion private class SourceInfo { public string name; public string type; public UInt64 size; public DateTime dateModified; public bool hasDetails; public int spectra; public string ionSource; public string analyzer; public string detector; public string contentType; public void populateFromMSData( MSData msInfo ) { hasDetails = true; spectra = msInfo.run.spectrumList == null ? 0 : msInfo.run.spectrumList.size(); ionSource = analyzer = detector = ""; foreach( InstrumentConfiguration ic in msInfo.instrumentConfigurationList ) { SortedDictionary<int, string> ionSources = new SortedDictionary<int, string>(); SortedDictionary<int, string> analyzers = new SortedDictionary<int, string>(); SortedDictionary<int, string> detectors = new SortedDictionary<int, string>(); foreach( pwiz.CLI.msdata.Component c in ic.componentList ) { CVParam term; switch( c.type ) { case ComponentType.ComponentType_Source: term = c.cvParamChild( CVID.MS_ionization_type ); if( !term.empty() ) ionSources.Add( c.order, term.name ); break; case ComponentType.ComponentType_Analyzer: term = c.cvParamChild( CVID.MS_mass_analyzer_type ); if( !term.empty() ) analyzers.Add( c.order, term.name ); break; case ComponentType.ComponentType_Detector: term = c.cvParamChild( CVID.MS_detector_type ); if( !term.empty() ) detectors.Add( c.order, term.name ); break; } } if( ionSource.Length > 0 ) ionSource += ", "; ionSource += String.Join( "/", new List<string>( ionSources.Values ).ToArray() ); if( analyzer.Length > 0 ) analyzer += ", "; analyzer += String.Join( "/", new List<string>( analyzers.Values ).ToArray() ); if( detector.Length > 0 ) detector += ", "; detector += String.Join( "/", new List<string>( detectors.Values ).ToArray() ); } System.Collections.Generic.Set<string> contentTypes = new System.Collections.Generic.Set<string>(); CVParamList cvParams = msInfo.fileDescription.fileContent.cvParams; if( cvParams.Count > 0 ) { foreach( CVParam term in msInfo.fileDescription.fileContent.cvParams ) contentTypes.Add( term.name ); contentType = String.Join( ", ", new List<string>( contentTypes.Keys ).ToArray() ); } } public string[] ToArray() { if( type == "File Folder" ) { return new string[] { name, type, "", "", String.Format( "{0} {1}", dateModified.ToShortDateString(), dateModified.ToShortTimeString()), "", "", "", "" }; } else { return new string[] { name, type, spectra.ToString(), String.Format( new FileSizeFormatProvider(), "{0:fs}", size ), String.Format( "{0} {1}", dateModified.ToShortDateString(), dateModified.ToShortTimeString() ), ionSource, analyzer, detector, contentType }; } } } private string getSourceType( string path ) { if( File.Exists( path ) ) return getSourceType( new FileInfo( path ) ); else if( Directory.Exists( path ) ) return getSourceType( new DirectoryInfo( path ) ); else throw new ArgumentException( "path is not a file or a directory" ); } private string getSourceType( DirectoryInfo dirInfo ) { try { string type = ReaderList.FullReaderList.identify( dirInfo.FullName ); if( type == String.Empty ) return "File Folder"; return type; } catch { return ""; } } private string getSourceType( FileInfo fileInfo ) { try { return ReaderList.FullReaderList.identify( fileInfo.FullName ); } catch (Exception) { return ""; } } private SourceInfo[] getSourceInfo( DirectoryInfo dirInfo, bool getDetails ) { var sourceInfoList = new List<SourceInfo>(); sourceInfoList.Add( new SourceInfo() ); sourceInfoList[0].type = getSourceType( dirInfo ); sourceInfoList[0].name = dirInfo.Name; sourceInfoList[0].dateModified = dirInfo.LastWriteTime; sourceInfoList[0].hasDetails = getDetails; if( !getDetails ) return sourceInfoList.ToArray(); if( sourceInfoList[0].type == "File Folder" ) { return sourceInfoList.ToArray(); } else if( sourceInfoList[0].type != String.Empty ) { try { MSDataFile msInfo = new MSDataFile( dirInfo.FullName ); sourceInfoList[0].populateFromMSData( msInfo ); } catch( ThreadAbortException ) { return null; } catch { sourceInfoList[0].spectra = 0; sourceInfoList[0].type = "Invalid " + sourceInfoList[0].type; } sourceInfoList[0].size = 0; sourceInfoList[0].dateModified = DateTime.MinValue; foreach( FileInfo fileInfo in dirInfo.GetFiles( "*", SearchOption.AllDirectories ) ) { sourceInfoList[0].size += (UInt64) fileInfo.Length; if( fileInfo.LastWriteTime > sourceInfoList[0].dateModified ) sourceInfoList[0].dateModified = fileInfo.LastWriteTime; } return sourceInfoList.ToArray(); } return null; } private SourceInfo[] getSourceInfo( FileInfo fileInfo, bool getDetails ) { var sourceInfoList = new List<SourceInfo>(); sourceInfoList.Add( new SourceInfo() ); sourceInfoList[0].type = getSourceType( fileInfo ); sourceInfoList[0].name = fileInfo.Name; sourceInfoList[0].hasDetails = getDetails; sourceInfoList[0].size = (UInt64) fileInfo.Length; sourceInfoList[0].dateModified = fileInfo.LastWriteTime; if( sourceInfoList[0].type != String.Empty ) { if( !getDetails ) return sourceInfoList.ToArray(); try { ReaderList readerList = ReaderList.FullReaderList; var readerConfig = new ReaderConfig { simAsSpectra = Program.SimAsSpectra, srmAsSpectra = Program.SrmAsSpectra }; MSDataList msInfo = new MSDataList(); readerList.read( fileInfo.FullName, msInfo, readerConfig ); foreach( MSData msData in msInfo ) { SourceInfo sourceInfo = new SourceInfo(); sourceInfo.type = sourceInfoList[0].type; sourceInfo.name = sourceInfoList[0].name; if( msInfo.Count > 1 ) sourceInfo.name += " (" + msData.run.id + ")"; sourceInfo.populateFromMSData( msData ); sourceInfoList.Add( sourceInfo ); } } catch { sourceInfoList[0].spectra = 0; sourceInfoList[0].type = "Invalid " + sourceInfoList[0].type; } foreach( SourceInfo sourceInfo in sourceInfoList ) { sourceInfo.size = (UInt64) fileInfo.Length; sourceInfo.dateModified = fileInfo.LastWriteTime; } return sourceInfoList.ToArray(); } return null; } private void populateListViewFromDirectory( string directory ) { initializeBackgroundSourceLoader(); listView.Items.Clear(); DirectoryInfo dirInfo = new DirectoryInfo( directory ); BackgroundSourceLoaderArgs args = new BackgroundSourceLoaderArgs(); args.GetDetails = listView.View == View.Details; if( sourceTypeComboBox.SelectedIndex > 0 ) args.SourceTypeFilter = sourceTypeComboBox.SelectedItem.ToString(); foreach( DirectoryInfo subdirInfo in dirInfo.GetDirectories() ) args.SourceDirectories.Add( subdirInfo ); foreach( FileInfo fileInfo in dirInfo.GetFiles() ) args.SourceFiles.Add( fileInfo ); backgroundSourceLoader.RunWorkerAsync( args ); } private void populateComboBoxFromDirectory( string directory ) { lookInComboBox.SuspendLayout(); // TODO: get network share info // remove old drive entries while( lookInComboBox.Items.Count > 4 ) lookInComboBox.Items.RemoveAt( 4 ); DirectoryInfo dirInfo = new DirectoryInfo(directory); // fill tree view with special locations and drives TreeNode myComputerNode = lookInComboBox.Items[3] as TreeNode; int driveCount = 0; foreach( DriveInfo driveInfo in DriveInfo.GetDrives() ) { // skip this drive if there's a problem accessing its properties try { var foo = driveInfo.VolumeLabel; } catch { continue; } string label; string sublabel = driveInfo.Name; driveReadiness[sublabel] = driveInfo.IsReady; int imageIndex; ++driveCount; switch( driveInfo.DriveType ) { case DriveType.Fixed: if( driveInfo.VolumeLabel.Length > 0 ) label = driveInfo.VolumeLabel; else label = "Local Drive"; imageIndex = 5; break; case DriveType.CDRom: if( driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0 ) label = driveInfo.VolumeLabel; else label = "Optical Drive"; imageIndex = 6; break; case DriveType.Removable: if( driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0 ) label = driveInfo.VolumeLabel; else label = "Removable Drive"; imageIndex = 6; break; case DriveType.Network: label = "Network Share"; imageIndex = 7; break; default: label = ""; imageIndex = 8; break; } TreeNode driveNode; if( label.Length > 0 ) driveNode = myComputerNode.Nodes.Add( sublabel, String.Format( "{0} ({1})", label, sublabel ), imageIndex, imageIndex ); else driveNode = myComputerNode.Nodes.Add( sublabel, sublabel, imageIndex, imageIndex ); driveNode.Tag = sublabel; lookInComboBox.Items.Insert( 3 + driveCount, driveNode ); if( sublabel == dirInfo.Root.Name ) { List<string> branches = new List<string>( directory.Split( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries ) ); TreeNode pathNode = driveNode; for( int i = 1; i < branches.Count; ++i ) { ++driveCount; pathNode = pathNode.Nodes.Add( branches[i], branches[i], 8, 8 ); pathNode.Tag = String.Join( Path.DirectorySeparatorChar.ToString(), branches.GetRange( 0, i ).ToArray() ); lookInComboBox.Items.Insert( 3 + driveCount, pathNode ); } lookInComboBox.SelectedIndex = 3 + driveCount; } } //desktopNode.Nodes.Add( "My Network Places", "My Network Places", 4, 4 ).Tag = "My Network Places"; lookInComboBox.DropDownHeight = lookInComboBox.Items.Count * 18 + 2; lookInComboBox.ResumeLayout(); } // Credit to: http://stackoverflow.com/a/14247337/638445 public static List<string> SplitOnSpacesWithQuoteEscaping(string input) { List<string> split = new List<string>(); StringBuilder sb = new StringBuilder(); bool splitOnQuote = false; char quote = '"'; char space = ' '; foreach (char c in input.ToCharArray()) { if (splitOnQuote) { if (c == quote) { if (sb.Length > 0) { split.Add(sb.ToString()); sb.Clear(); } splitOnQuote = false; } else { sb.Append(c); } } else { if (c == space) { if (sb.Length > 0) { split.Add(sb.ToString()); sb.Clear(); } } else if (c == quote) { if (sb.Length > 0) { split.Add(sb.ToString()); sb.Clear(); } splitOnQuote = true; } else { sb.Append(c); } } } if (sb.Length > 0) split.Add(sb.ToString()); return split; } private void sourcePathTextBox_KeyUp( object sender, KeyEventArgs e ) { // if sourcePathTextBox.Text as a whole is a file or directory, treat it as a single path; // otherwise split it up by spaces with quote escaping List<string> sourcePaths = File.Exists(sourcePathTextBox.Text) || Directory.Exists(sourcePathTextBox.Text) ? new List<string> { sourcePathTextBox.Text } : SplitOnSpacesWithQuoteEscaping(sourcePathTextBox.Text); switch( e.KeyCode ) { case Keys.Enter: if( sourcePaths.Count == 0 ) return; else if( sourcePaths.Count == 1 && Directory.Exists(sourcePaths[0]) ) CurrentDirectory = sourcePaths[0]; else if( sourcePaths.Count == 1 && Directory.Exists( Path.Combine( CurrentDirectory, sourcePaths[0] ) ) ) CurrentDirectory = Path.Combine( CurrentDirectory, sourcePaths[0] ); else { // check that all manually-entered paths are valid List<string> invalidPaths = new List<string>(); foreach( string path in sourcePaths ) if( !File.Exists( path ) && !File.Exists( Path.Combine( CurrentDirectory, path ) ) ) invalidPaths.Add( path ); if( invalidPaths.Count == 0 ) { dataSources = sourcePaths.ToArray(); DialogResult = DialogResult.OK; Close(); } else MessageBox.Show( String.Join( "\r\n", invalidPaths.ToArray() ), "Some source paths are invalid" ); } break; case Keys.F5: populateListViewFromDirectory( currentDirectory ); // refresh break; } } #region ListView handlers private void listView_ItemActivate( object sender, EventArgs e ) { if( listView.SelectedItems.Count == 0 ) return; ListViewItem item = listView.SelectedItems[0]; if( item.SubItems[1].Text == "File Folder" ) { if( currentDirectory != null ) previousDirectories.Push( currentDirectory ); CurrentDirectory = Path.Combine( CurrentDirectory, item.SubItems[0].Text ); } else { dataSources = new string[] { Path.Combine( CurrentDirectory, item.SubItems[0].Text ) }; DialogResult = DialogResult.OK; Close(); } } private void listView_ColumnClick( object sender, ColumnClickEventArgs e ) { // Determine if the clicked column is already the column that is being sorted. if( e.Column == listViewColumnSorter.SortColumn ) { // Reverse the current sort direction for this column. if( listViewColumnSorter.Order == SortOrder.Ascending ) listViewColumnSorter.Order = SortOrder.Descending; else listViewColumnSorter.Order = SortOrder.Ascending; } else { // Set the column number that is to be sorted; default to ascending. listViewColumnSorter.SortColumn = e.Column; listViewColumnSorter.Order = SortOrder.Ascending; } // Perform the sort with these new sort options. listView.Sort(); } private void listView_ItemSelectionChanged( object sender, ListViewItemSelectionChangedEventArgs e ) { if( listView.SelectedItems.Count > 1 ) { List<string> dataSourceList = new List<string>(); foreach( ListViewItem item in listView.SelectedItems ) { if( item.SubItems[1].Text != "File Folder" ) dataSourceList.Add( String.Format( "\"{0}\"", item.SubItems[0].Text ) ); } sourcePathTextBox.Text = String.Join( " ", dataSourceList.ToArray() ); ticGraphControl.GraphPane.GraphObjList.Clear(); ticGraphControl.GraphPane.CurveList.Clear(); ticGraphControl.Visible = false; } else if( listView.SelectedItems.Count > 0 ) { sourcePathTextBox.Text = listView.SelectedItems[0].SubItems[0].Text; ticGraphControl.GraphPane.GraphObjList.Clear(); ticGraphControl.GraphPane.CurveList.Clear(); string sourcePath = Path.Combine( CurrentDirectory, sourcePathTextBox.Text ); string sourceType = getSourceType( sourcePath ); if( !String.IsNullOrEmpty( sourceType ) && sourceType != "File Folder" ) { using (MSDataFile msData = new MSDataFile( sourcePath )) using (ChromatogramList cl = msData.run.chromatogramList) { if( cl != null && !cl.empty() && cl.find( "TIC" ) != cl.size() ) { ticGraphControl.Visible = true; pwiz.CLI.msdata.Chromatogram tic = cl.chromatogram( cl.find( "TIC" ), true ); Map<double, double> sortedFullPointList = new Map<double, double>(); IList<double> timeList = tic.binaryDataArrays[0].data; IList<double> intensityList = tic.binaryDataArrays[1].data; int arrayLength = timeList.Count; for( int i = 0; i < arrayLength; ++i ) sortedFullPointList[timeList[i]] = intensityList[i]; ZedGraph.PointPairList points = new ZedGraph.PointPairList( new List<double>( sortedFullPointList.Keys ).ToArray(), new List<double>( sortedFullPointList.Values ).ToArray() ); ZedGraph.LineItem item = ticGraphControl.GraphPane.AddCurve( "TIC", points, Color.Black, ZedGraph.SymbolType.None ); item.Line.IsAntiAlias = true; ticGraphControl.AxisChange(); ticGraphControl.Refresh(); } else ticGraphControl.Visible = false; } } else ticGraphControl.Visible = false; } else sourcePathTextBox.Text = ""; } private void listView_KeyDown( object sender, KeyEventArgs e ) { switch( e.KeyCode ) { case Keys.F5: populateListViewFromDirectory( currentDirectory ); // refresh break; } } #endregion private void sourceTypeComboBox_SelectionChangeCommitted( object sender, EventArgs e ) { populateListViewFromDirectory( currentDirectory ); } #region Button click handlers private void openButton_Click( object sender, EventArgs e ) { if( listView.SelectedItems.Count > 0 ) { List<string> dataSourceList = new List<string>(); foreach( ListViewItem item in listView.SelectedItems ) { if( item.SubItems[1].Text != "File Folder" ) dataSourceList.Add( Path.Combine( CurrentDirectory, item.SubItems[0].Text ) ); } dataSources = dataSourceList.ToArray(); initializeBackgroundSourceLoader(); DialogResult = DialogResult.OK; Close(); Application.DoEvents(); } else MessageBox.Show( "Please select one or more data sources.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } private void cancelButton_Click( object sender, EventArgs e ) { initializeBackgroundSourceLoader(); DialogResult = DialogResult.Cancel; Close(); Application.DoEvents(); } private void smallIconsToolStripMenuItem_Click( object sender, EventArgs e ) { foreach( ToolStripDropDownItem item in viewsDropDownButton.DropDownItems ) ( item as ToolStripMenuItem ).Checked = false; ( viewsDropDownButton.DropDownItems[0] as ToolStripMenuItem ).Checked = true; listView.View = View.SmallIcon; } private void largeIconsToolStripMenuItem_Click( object sender, EventArgs e ) { foreach( ToolStripDropDownItem item in viewsDropDownButton.DropDownItems ) ( item as ToolStripMenuItem ).Checked = false; ( viewsDropDownButton.DropDownItems[1] as ToolStripMenuItem ).Checked = true; listView.View = View.LargeIcon; } private void tilesToolStripMenuItem_Click( object sender, EventArgs e ) { foreach( ToolStripDropDownItem item in viewsDropDownButton.DropDownItems ) ( item as ToolStripMenuItem ).Checked = false; ( viewsDropDownButton.DropDownItems[2] as ToolStripMenuItem ).Checked = true; listView.View = View.Tile; } private void listToolStripMenuItem_Click( object sender, EventArgs e ) { foreach( ToolStripDropDownItem item in viewsDropDownButton.DropDownItems ) ( item as ToolStripMenuItem ).Checked = false; ( viewsDropDownButton.DropDownItems[3] as ToolStripMenuItem ).Checked = true; listView.View = View.List; } private void detailsToolStripMenuItem_Click( object sender, EventArgs e ) { if( listView.View != View.Details ) { foreach( ToolStripDropDownItem item in viewsDropDownButton.DropDownItems ) ( item as ToolStripMenuItem ).Checked = false; ( viewsDropDownButton.DropDownItems[4] as ToolStripMenuItem ).Checked = true; listView.View = View.Details; populateListViewFromDirectory( currentDirectory ); } } private void upOneLevelButton_Click( object sender, EventArgs e ) { DirectoryInfo parentDirectory = Directory.GetParent(currentDirectory); if( parentDirectory == null ) { parentDirectory = new DirectoryInfo( Environment.GetFolderPath( Environment.SpecialFolder.MyComputer ) ); } if( parentDirectory != null && parentDirectory.FullName != currentDirectory ) { previousDirectories.Push( currentDirectory ); CurrentDirectory = parentDirectory.FullName; } } private void backButton_Click( object sender, EventArgs e ) { if( previousDirectories.Count > 0 ) CurrentDirectory = previousDirectories.Pop(); } private void recentDocumentsButton_Click( object sender, EventArgs e ) { } private void desktopButton_Click( object sender, EventArgs e ) { CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.DesktopDirectory ); } private void myDocumentsButton_Click( object sender, EventArgs e ) { CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ); } private void myComputerButton_Click( object sender, EventArgs e ) { } private void myNetworkPlacesButton_Click( object sender, EventArgs e ) { } #endregion #region Look-In ComboBox handlers System.Collections.Generic.Map<string, bool> driveReadiness = new System.Collections.Generic.Map<string, bool>(); private void lookInComboBox_DropDown( object sender, EventArgs e ) { } private void lookInComboBox_DrawItem( object sender, DrawItemEventArgs e ) { if( e.Index < 0 ) return; TreeNode node = lookInComboBox.Items[e.Index] as TreeNode; int x, y, indent; if( ( e.State & DrawItemState.ComboBoxEdit ) == DrawItemState.ComboBoxEdit ) { x = 2; y = 2; indent = 0; } else { e.DrawBackground(); e.DrawFocusRectangle(); x = node.TreeView.Indent / 2; y = e.Bounds.Y; indent = node.TreeView.Indent * node.Level; } Image image = lookInImageList.Images[node.ImageIndex]; e.Graphics.DrawImage( image, x + indent, y, 16, 16 ); e.Graphics.DrawString( node.Text, lookInComboBox.Font, new SolidBrush(lookInComboBox.ForeColor), x + indent + 16, y ); } private void lookInComboBox_MeasureItem( object sender, MeasureItemEventArgs e ) { if( e.Index < 0 ) return; TreeNode node = lookInComboBox.Items[e.Index] as TreeNode; int x = node.TreeView.Indent / 2; int indent = node.TreeView.Indent * node.Level; e.ItemHeight = 16; e.ItemWidth = x + indent + 16 + (int) e.Graphics.MeasureString( node.Text, lookInComboBox.Font ).Width; } private void lookInComboBox_SelectionChangeCommitted( object sender, EventArgs e ) { if( lookInComboBox.SelectedIndex < 0 ) lookInComboBox.SelectedIndex = 0; string location = ( lookInComboBox.SelectedItem as TreeNode ).Tag as string; switch( location ) { case "My Recent Documents": CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Recent ); break; case "Desktop": CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.DesktopDirectory ); break; case "My Documents": CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Personal ); break; case "My Computer": break; case "My Network Places": break; default: if( driveReadiness[location] ) CurrentDirectory = location; else CurrentDirectory = currentDirectory; break; } } #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 System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Animation; using OpenSim.Services.Interfaces; using AnimationSet = OpenSim.Region.Framework.Scenes.Animation.AnimationSet; namespace OpenSim.Region.OptionalModules.Avatar.Animations { /// <summary> /// A module that just holds commands for inspecting avatar animations. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AnimationsCommandModule")] public class AnimationsCommandModule : ISharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scenes = new List<Scene>(); public string Name { get { return "Animations Command Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Remove(scene); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Add(scene); scene.AddCommand( "Users", this, "show animations", "show animations [<first-name> <last-name>]", "Show animation information for avatars in this simulator.", "If no name is supplied then information for all avatars is shown.\n" + "Please note that for inventory animations, the animation name is the name under which the animation was originally uploaded\n" + ", which is not necessarily the current inventory name.", HandleShowAnimationsCommand); } protected void HandleShowAnimationsCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: show animations [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } StringBuilder sb = new StringBuilder(); lock (m_scenes) { foreach (Scene scene in m_scenes) { if (targetNameSupplied) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) GetAttachmentsReport(sp, sb); } else { scene.ForEachRootScenePresence(sp => GetAttachmentsReport(sp, sb)); } } } MainConsole.Instance.Output(sb.ToString()); } private void GetAttachmentsReport(ScenePresence sp, StringBuilder sb) { sb.AppendFormat("Animations for {0}\n", sp.Name); ConsoleDisplayList cdl = new ConsoleDisplayList() { Indent = 2 }; ScenePresenceAnimator spa = sp.Animator; AnimationSet anims = sp.Animator.Animations; string cma = spa.CurrentMovementAnimation; cdl.AddRow( "Current movement anim", string.Format("{0}, {1}", DefaultAvatarAnimations.GetDefaultAnimation(cma), cma)); UUID defaultAnimId = anims.DefaultAnimation.AnimID; cdl.AddRow( "Default anim", string.Format("{0}, {1}", defaultAnimId, sp.Animator.GetAnimName(defaultAnimId))); UUID implicitDefaultAnimId = anims.ImplicitDefaultAnimation.AnimID; cdl.AddRow( "Implicit default anim", string.Format("{0}, {1}", implicitDefaultAnimId, sp.Animator.GetAnimName(implicitDefaultAnimId))); cdl.AddToStringBuilder(sb); ConsoleDisplayTable cdt = new ConsoleDisplayTable() { Indent = 2 }; cdt.AddColumn("Animation ID", 36); cdt.AddColumn("Name", 20); cdt.AddColumn("Seq", 3); cdt.AddColumn("Object ID", 36); UUID[] animIds; int[] sequenceNumbers; UUID[] objectIds; sp.Animator.Animations.GetArrays(out animIds, out sequenceNumbers, out objectIds); for (int i = 0; i < animIds.Length; i++) { UUID animId = animIds[i]; string animName = sp.Animator.GetAnimName(animId); int seq = sequenceNumbers[i]; UUID objectId = objectIds[i]; cdt.AddRow(animId, animName, seq, objectId); } cdt.AddToStringBuilder(sb); sb.Append("\n"); } } }
namespace Microsoft.Protocols.TestSuites.MS_OXCRPC { using System; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// AUX_PERF_SESSIONINFO structure /// </summary> public struct AUX_PERF_SESSIONINFO { /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// Reserved (2 bytes), padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// SessionGuid (16 bytes), GUID representing the client session to associate with the session identification number /// in field SessionID. /// </summary> public byte[] SessionGuid; /// <summary> /// Serializes AUX_PERF_SESSIONINFO to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_SESSIONINFO</returns> public byte[] Serialize() { if (this.SessionGuid == null) { // According to Open Specification, this field should be a 16 byte array this.SessionGuid = new byte[ConstValues.GuidByteSize]; } // Refer to 2.2.2.4 AUX_PERF_SESSIONINFO int size = (sizeof(short) * 2) + this.SessionGuid.Length; byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(this.SessionGuid, 0, resultBytes, index, this.SessionGuid.Length); return resultBytes; } } /// <summary> /// AUX_PERF_SESSIONINFO_V2 structure /// </summary> public struct AUX_PERF_SESSIONINFO_v2 { /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// Reserved (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// SessionGuid (16 bytes): GUID representing the client session to associate with the session identification number /// in field SessionID. /// </summary> public byte[] SessionGuid; /// <summary> /// ConnectionID (4 bytes): Connection identification number. /// </summary> public int ConnectionID; /// <summary> /// Serializes AUX_PERF_SESSIONINFO_V2 to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_SESSIONINFO_V2</returns> public byte[] Serialize() { if (this.SessionGuid == null) { // According to Open Specification, this field should be a 16 byte array this.SessionGuid = new byte[ConstValues.GuidByteSize]; } // Refer to 2.2.2.5 AUX_PERF_SESSIONINFO_V2 int size = (sizeof(short) * 2) + sizeof(int) + this.SessionGuid.Length; byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(this.SessionGuid, 0, resultBytes, index, this.SessionGuid.Length); index += this.SessionGuid.Length; Array.Copy(BitConverter.GetBytes(this.ConnectionID), 0, resultBytes, index, sizeof(int)); return resultBytes; } } /// <summary> /// AUX_PERF_CLIENTINFO structure /// </summary> public struct AUX_PERF_CLIENTINFO { /// <summary> /// AdapterSpeed (4 bytes): Speed of client computer's network adapter (kbits/s). /// </summary> public int AdapterSpeed; /// <summary> /// ClientID (2 bytes): Client-assigned identification number. /// </summary> public short ClientID; /// <summary> /// MachineNameOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the MachineName field. /// A value of zero indicates that the MachineName field is null or empty. /// </summary> public short MachineNameOffset; /// <summary> /// UserNameOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the UserName field. /// A value of zero indicates that the UserName field is null or empty. /// </summary> public short UserNameOffset; /// <summary> /// ClientIPSize (2 bytes): Size of the client IP address referenced by the ClientIPOffset field. /// The client IP address is located in the ClientIP field. /// </summary> public short ClientIPSize; /// <summary> /// ClientIPOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the ClientIP field. /// A value of zero indicates that the ClientIP field is null or empty. /// </summary> public short ClientIPOffset; /// <summary> /// ClientIPMaskSize (2 bytes): Size of the client IP subnet mask referenced by the ClientIPMaskOffset field. /// The client IP mask is located in the ClientIPMask field. /// </summary> public short ClientIPMaskSize; /// <summary> /// ClientIPMaskOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the ClientIPMask field. /// The size of the IP subnet mask is found in the ClientIPMaskSize field. /// A value of zero indicates that the ClientIPMask field is null or empty. /// </summary> public short ClientIPMaskOffset; /// <summary> /// AdapterNameOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the AdapterName field. /// A value of zero indicates that the AdapterName field is null or empty. /// </summary> public short AdapterNameOffset; /// <summary> /// MacAddressSize (2 bytes): Size of the network adapter MAC address referenced by the MacAddressOffset field. /// The network adapter MAC address is located in the MacAddress field. /// </summary> public short MacAddressSize; /// <summary> /// MacAddressOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the MacAddress field. /// A value of zero indicates that the MacAddress field is null or empty. /// </summary> public short MacAddressOffset; /// <summary> /// ClientMode (2 bytes): Determines the mode in which the client is running. /// </summary> public short ClientMode; /// <summary> /// Reserved (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// MachineName (variable): A null-terminated Unicode string that contains the client computer name. /// This variable field is offset from the beginning of the AUX_HEADER structure by the MachineNameOffset value. /// </summary> public byte[] MachineName; /// <summary> /// UserName (variable): A null-terminated Unicode string that contains the user's account name. /// This variable field is offset from the beginning of the AUX_HEADER structure by the UserNameOffset value. /// </summary> public byte[] UserName; /// <summary> /// ClientIP (variable): The client's IP address. /// This variable field is offset from the beginning of the AUX_HEADER structure by the ClientIPOffset value. /// The size of the client IP address data is found in the ClientIPSize field. /// </summary> public byte[] ClientIP; /// <summary> /// ClientIPMask (variable): The client's IP subnet mask. /// This variable field is offset from the beginning of the AUX_HEADER structure by the ClientIPMaskOffset value. /// The size of the client IP mask data is found in the ClientIPMaskSize field. /// </summary> public byte[] ClientIPMask; /// <summary> /// AdapterName (variable): A null-terminated Unicode string that contains the client network adapter name. /// This variable field is offset from the beginning of the AUX_HEADER structure by the AdapterNameOffset value. /// </summary> public byte[] AdapterName; /// <summary> /// MacAddress (variable):The client's network adapter MAC address. /// This variable field is offset from the beginning of the AUX_HEADER structure by the MacAddressOffset value. /// The size of the network adapter MAC address data is found in the MacAddressSize field. /// </summary> public byte[] MacAddress; /// <summary> /// Serializes AUX_PERF_CLIENTINFO to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_CLIENTINFO</returns> public byte[] Serialize() { // Refer to 2.2.2.6 AUX_PERF_CLIENTINFO int size = sizeof(int) + (sizeof(short) * 12); if (this.MachineName != null) { size += this.MachineName.Length; } if (this.UserName != null) { size += this.UserName.Length; } if (this.ClientIP != null) { size += this.ClientIP.Length; } if (this.ClientIPMask != null) { size += this.ClientIPMask.Length; } if (this.AdapterName != null) { size += this.AdapterName.Length; } if (this.MacAddress != null) { size += this.MacAddress.Length; } byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.AdapterSpeed), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.MachineNameOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.UserNameOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientIPSize), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientIPOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientIPMaskSize), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.AdapterNameOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.MacAddressSize), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientMode), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientIPMaskOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); if (this.MachineName != null) { Array.Copy(this.MachineName, 0, resultBytes, index, this.MachineName.Length); index += this.MachineName.Length; } if (this.UserName != null) { Array.Copy(this.UserName, 0, resultBytes, index, this.UserName.Length); index += this.UserName.Length; } if (this.ClientIP != null) { Array.Copy(this.ClientIP, 0, resultBytes, index, this.ClientIP.Length); index += this.ClientIP.Length; } if (this.ClientIPMask != null) { Array.Copy(this.ClientIPMask, 0, resultBytes, index, this.ClientIPMask.Length); index += this.ClientIPMask.Length; } if (this.AdapterName != null) { Array.Copy(this.AdapterName, 0, resultBytes, index, this.AdapterName.Length); index += this.AdapterName.Length; } if (this.MacAddress != null) { Array.Copy(this.MacAddress, 0, resultBytes, index, this.MacAddress.Length); index += this.MacAddress.Length; } return resultBytes; } } /// <summary> /// 2.2.2.8 AUX_PERF_PROCESSINFO /// </summary> public struct AUX_PERF_PROCESSINFO { /// <summary> /// ProcessID (2 bytes): Client-assigned process identification number. /// </summary> public short ProcessID; /// <summary> /// Reserved_1 (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved1; /// <summary> /// ProcessGuid (16 bytes): GUID representing the client process to associate with the process identification number /// in field ProcessID. /// </summary> public byte[] ProcessGuid; /// <summary> /// ProcessNameOffset (2 bytes): The offset from the beginning of the AUX_HEADER structure to the ProcessName field. /// A value of zero indicates that the ProcessName field is null or empty. /// </summary> public short ProcessNameOffset; /// <summary> /// Reserved_2 (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved2; /// <summary> /// ProcessName (variable): A null-terminated Unicode string that contains the client process name. /// This variable field is offset from the beginning of the AUX_HEADER structure by the ProcessNameOffset value. /// </summary> public byte[] ProcessName; /// <summary> /// Serializes AUX_PERF_PROCESSINFO to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_PROCESSINFO</returns> public byte[] Serialize() { if (this.ProcessGuid == null) { // According to Open Specification, this field should be a 16 byte array this.ProcessGuid = new byte[ConstValues.GuidByteSize]; } // Refer to 2.2.2.8 AUX_PERF_PROCESSINFO int size = (sizeof(short) * 4) + this.ProcessGuid.Length; if (this.ProcessName != null) { size += this.ProcessName.Length; } byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ProcessID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved1), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(this.ProcessGuid, 0, resultBytes, index, this.ProcessGuid.Length); index += this.ProcessGuid.Length; Array.Copy(BitConverter.GetBytes(this.ProcessNameOffset), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved2), 0, resultBytes, index, sizeof(short)); index += sizeof(short); if (this.ProcessName != null) { Array.Copy(this.ProcessName, 0, resultBytes, index, this.ProcessName.Length); index += this.ProcessName.Length; } return resultBytes; } } /// <summary> /// 2.2.2.9 AUX_PERF_DEFMDB_SUCCESS /// </summary> public struct AUX_PERF_DEFMDB_SUCCESS { /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since successful request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToCompleteRequest (4 bytes): Number of milliseconds the successful request took to complete. /// </summary> public int TimeToCompleteRequest; /// <summary> /// RequestID (2 bytes): Request identification number. /// </summary> public short RequestID; /// <summary> /// Reserved (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// Serializes AUX_PERF_DEFMDB_SUCCESS to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_DEFMDB_SUCCESS</returns> public byte[] Serialize() { // 2.2.2.9 AUX_PERF_DEFMDB_SUCCESS int size = (sizeof(short) * 2) + (sizeof(int) * 2); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToCompleteRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.RequestID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); return resultBytes; } } /// <summary> /// 2.2.2.10 AUX_PERF_DEFGC_SUCCESS /// </summary> public struct AUX_PERF_DEFGC_SUCCESS { /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since successful request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToCompleteRequest (4 bytes): Number of milliseconds the successful request took to complete. /// </summary> public int TimeToCompleteRequest; /// <summary> /// RequestOperation (1 byte): Client-defined operation that was successful. /// </summary> public byte RequestOperation; /// <summary> /// Reserved (3 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public int Reserved; /// <summary> /// Serializes AUX_PERF_DEFGC_SUCCESS to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_DEFGC_SUCCESS</returns> public byte[] Serialize() { // 2.2.2.10 AUX_PERF_DEFGC_SUCCESS int size = 18; byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToCompleteRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); resultBytes[index] = this.RequestOperation; index += sizeof(byte); // The length of processName is three bytes, so the first byte will be abandoned. Array.Copy(BitConverter.GetBytes(this.Reserved), 1, resultBytes, index, 3); return resultBytes; } } /// <summary> /// 2.2.2.12 AUX_PERF_MDB_SUCCESS_V2 /// </summary> public struct AUX_PERF_MDB_SUCCESS_V2 { /// <summary> /// ProcessID (2 bytes): Process identification number. /// </summary> public short ProcessID; /// <summary> /// ClientID (2 bytes): Client identification number. /// </summary> public short ClientID; /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// RequestID (2 bytes): Request identification number. /// </summary> public short RequestID; /// <summary> /// Reserved (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since successful request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToCompleteRequest (4 bytes): Number of milliseconds the successful request took to complete. /// </summary> public int TimeToCompleteRequest; /// <summary> /// Serializes AUX_PERF_MDB_SUCCESS_V2 to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_MDB_SUCCESS_V2</returns> public byte[] Serialize() { // 2.2.2.12 AUX_PERF_MDB_SUCCESS_V2 int size = (sizeof(short) * 6) + (sizeof(int) * 2); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ProcessID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.RequestID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToCompleteRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); return resultBytes; } } /// <summary> /// 2.2.2.13 AUX_PERF_GC_SUCCESS /// </summary> public struct AUX_PERF_GC_SUCCESS { /// <summary> /// ClientID (2 bytes): Client identification number. /// </summary> public short ClientID; /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// Reserved_1 (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved1; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since successful request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToCompleteRequest (4 bytes): Number of milliseconds the successful request took to complete. /// </summary> public int TimeToCompleteRequest; /// <summary> /// RequestOperation (1 byte): Client-defined operation that was successful. /// </summary> public byte RequestOperation; /// <summary> /// Reserved_2 (3 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public int Reserved2; /// <summary> /// Serializes AUX_PERF_GC_SUCCESS to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_GC_SUCCESS</returns> public byte[] Serialize() { // 2.2.2.13 AUX_PERF_GC_SUCCESS int size = (sizeof(short) * 4) + (sizeof(int) * 3) + sizeof(byte); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved1), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToCompleteRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); resultBytes[index] = this.RequestOperation; index += sizeof(byte); // The length of processName is three bytes, so the first byte will be abandoned. Array.Copy(BitConverter.GetBytes(this.Reserved2), 1, resultBytes, index, 3); return resultBytes; } } /// <summary> /// 2.2.2.14 AUX_PERF_GC_SUCCESS_V2 /// </summary> public struct AUX_PERF_GC_SUCCESS_V2 { /// <summary> /// ProcessID (2 bytes): Process identification number. /// </summary> public short ProcessID; /// <summary> /// ClientID (2 bytes): Client identification number. /// </summary> public short ClientID; /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since successful request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToCompleteRequest (4 bytes): Number of milliseconds the successful request took to complete. /// </summary> public int TimeToCompleteRequest; /// <summary> /// RequestOperation (1 byte): Client-defined operation that was successful. /// </summary> public byte RequestOperation; /// <summary> /// Reserved (3 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public int Reserved; /// <summary> /// Serializes AUX_PERF_GC_SUCCESS_V2 to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_GC_SUCCESS_V2</returns> public byte[] Serialize() { // 2.2.2.14 AUX_PERF_GC_SUCCESS_V2 int size = (sizeof(short) * 4) + (sizeof(int) * 3) + sizeof(byte); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ProcessID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToCompleteRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); resultBytes[index] = this.RequestOperation; index += sizeof(byte); // The length of processName is three bytes, so the first byte will be abandoned. Array.Copy(BitConverter.GetBytes(this.Reserved), 1, resultBytes, index, 3); return resultBytes; } } /// <summary> /// 2.2.2.15 AUX_PERF_FAILURE /// </summary> public struct AUX_PERF_FAILURE { /// <summary> /// ClientID (2 bytes): Client identification number. /// </summary> public short ClientID; /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// RequestID (2 bytes): Request identification number. /// </summary> public short RequestID; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since failure request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToFailRequest (4 bytes): Number of milliseconds the failure request took to complete. /// </summary> public int TimeToFailRequest; /// <summary> /// ResultCode (4 bytes): Error code return of failed request. Returned error codes are implementation specific. /// </summary> public int ResultCode; /// <summary> /// RequestOperation (1 byte): Client-defined operation that failed. /// </summary> public byte RequestOperation; /// <summary> /// Reserved (3 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public int Reserved; /// <summary> /// Serializes AUX_PERF_FAILURE to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_FAILURE</returns> public byte[] Serialize() { // 2.2.2.15 AUX_PERF_FAILURE int size = (sizeof(short) * 4) + (sizeof(int) * 4) + sizeof(byte); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.RequestID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToFailRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.ResultCode), 0, resultBytes, index, sizeof(int)); index += sizeof(int); resultBytes[index] = this.RequestOperation; index += sizeof(byte); // The length of processName is three bytes, so the first byte will be abandoned. Array.Copy(BitConverter.GetBytes(this.Reserved), 1, resultBytes, index, 3); return resultBytes; } } /// <summary> /// 2.2.2.16 AUX_PERF_FAILURE_V2 /// </summary> public struct AUX_PERF_FAILURE_V2 { /// <summary> /// ProcessID (2 bytes): Process identification number. /// </summary> public short ProcessID; /// <summary> /// ClientID (2 bytes): Client identification number. /// </summary> public short ClientID; /// <summary> /// ServerID (2 bytes): Server identification number. /// </summary> public short ServerID; /// <summary> /// SessionID (2 bytes): Session identification number. /// </summary> public short SessionID; /// <summary> /// RequestID (2 bytes): Request identification number. /// </summary> public short RequestID; /// <summary> /// Reserved_1 (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved1; /// <summary> /// TimeSinceRequest (4 bytes): Number of milliseconds since failure request occurred. /// </summary> public int TimeSinceRequest; /// <summary> /// TimeToFailRequest (4 bytes): Number of milliseconds the failure request took to complete. /// </summary> public int TimeToFailRequest; /// <summary> /// ResultCode (4 bytes): Error code return of failed request. Returned error codes are implementation specific. /// </summary> public int ResultCode; /// <summary> /// RequestOperation (1 byte): Client-defined operation that failed. /// </summary> public byte RequestOperation; /// <summary> /// Reserved_2 (3 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public int Reserved2; /// <summary> /// Serializes AUX_PERF_FAILURE_V2 to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_FAILURE_V2</returns> public byte[] Serialize() { // 2.2.2.16 AUX_PERF_FAILURE_V2 int size = (sizeof(short) * 6) + (sizeof(int) * 4) + sizeof(byte); byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ProcessID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.ServerID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.SessionID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.RequestID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved1), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.TimeSinceRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.TimeToFailRequest), 0, resultBytes, index, sizeof(int)); index += sizeof(int); Array.Copy(BitConverter.GetBytes(this.ResultCode), 0, resultBytes, index, sizeof(int)); index += sizeof(int); resultBytes[index] = this.RequestOperation; index += sizeof(byte); // The length of processName is three bytes, so the first byte will be abandoned. Array.Copy(BitConverter.GetBytes(this.Reserved2), 1, resultBytes, index, 3); return resultBytes; } } /// <summary> /// 2.2.2.20 AUX_PERF_ACCOUNTINFO /// </summary> public struct AUX_PERF_ACCOUNTINFO { /// <summary> /// ClientID (2 bytes): Client assigned identification number. /// </summary> public short ClientID; /// <summary> /// Reserved (2 bytes): Padding to enforce alignment of the data on a 4-byte field. /// The client can fill this field with any value when writing the stream. /// The server MUST ignore the value of this field when reading the stream. /// </summary> public short Reserved; /// <summary> /// Account (16 bytes): A GUID representing the client account information that relates to the client /// identification number in the ClientID field. /// </summary> public byte[] Account; /// <summary> /// Serializes AUX_PERF_ACCOUNTINFO to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_PERF_ACCOUNTINFO</returns> public byte[] Serialize() { if (this.Account == null) { // According to Open Specification, this field should be a 16 byte array this.Account = new byte[ConstValues.GuidByteSize]; } // 2.2.2.20 AUX_PERF_ACCOUNTINFO int size = (sizeof(short) * 2) + this.Account.Length; byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(BitConverter.GetBytes(this.ClientID), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index += sizeof(short); Array.Copy(this.Account, 0, resultBytes, index, this.Account.Length); return resultBytes; } } /// <summary> /// The data structure of AUX_CLIENT_CONNECTION_INFO /// </summary> public struct AUX_CLIENT_CONNECTION_INFO { /// <summary> /// The GUID of the connection to the server. /// </summary> public Guid ConnectionGUID; /// <summary> /// The offset from the beginning of the AUX_HEADER structure to the ConnectionContextInfo field. /// </summary> public short OffsetConnectionContextInfo; /// <summary> /// Padding to enforce alignment of the data on a 4-byte field. /// </summary> public short Reserved; /// <summary> /// The number of connection attempts. /// </summary> public short ConnectionAttempts; /// <summary> /// A value of 0x0001 for this field means that the client is running in cached mode. /// A value of 0x0000 means that the client is not designating a mode of operation. /// </summary> public int ConnectionFlags; /// <summary> /// A null-terminated Unicode string that contains opaque connection context information to be logged by the server. /// </summary> public string ConnectionContextInfo; /// <summary> /// Serializes AUX_CLIENT_CONNECTION_INFO to a byte array /// </summary> /// <returns>Returns the byte array of serialized AUX_CLIENT_CONNECTION_INFO.</returns> public byte[] Serialize() { byte[] connectionContextInfo = new byte[0]; if (!string.IsNullOrEmpty(this.ConnectionContextInfo)) { connectionContextInfo = System.Text.Encoding.Unicode.GetBytes(this.ConnectionContextInfo); } int size = 28 + connectionContextInfo.Length; byte[] resultBytes = new byte[size]; int index = 0; Array.Copy(this.ConnectionGUID.ToByteArray(), 0, resultBytes, index, 16); index = index + 16; Array.Copy(BitConverter.GetBytes(this.OffsetConnectionContextInfo), 0, resultBytes, index, sizeof(short)); index = index + sizeof(short); Array.Copy(BitConverter.GetBytes(this.Reserved), 0, resultBytes, index, sizeof(short)); index = index + sizeof(short); Array.Copy(BitConverter.GetBytes(this.ConnectionAttempts), 0, resultBytes, index, sizeof(short)); index = index + sizeof(short); Array.Copy(BitConverter.GetBytes(this.ConnectionFlags), 0, resultBytes, index, sizeof(int)); index = index + sizeof(int); Array.Copy(connectionContextInfo, 0, resultBytes, index, connectionContextInfo.Length); return resultBytes; } } /// <summary> /// The structure of rgbAuxOut that contains the AUX_CLIENT_CONTROL, AUX_OSVERSIONINFO or AUX_EXORGINFO. /// </summary> public struct AUX_SERVER_TOPOLOGY_STRUCTURE { /// <summary> /// The header before the payload in rgbAuxOut. /// </summary> public AUX_HEADER Header; /// <summary> /// Payload that contains the AUX_CLIENT_CONTROL, AUX_OSVERSIONINFO or AUX_EXORGINFO /// </summary> public byte[] Payload; } /// <summary> /// The structure of AUX_SERVER_CAPABILITIES. /// </summary> public struct AUX_SERVER_CAPABILITIES { /// <summary> /// A flag that indicates that the server supports specific capabilities. /// </summary> public uint ServerCapabilityFlags; } }
// 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.ApplicationInsights.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApplicationInsights; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ComponentsOperations. /// </summary> public static partial class ComponentsOperationsExtensions { /// <summary> /// Gets a list of all Application Insights components within a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ApplicationInsightsComponent> List(this IComponentsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all Application Insights components within a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationInsightsComponent>> ListAsync(this IComponentsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of Application Insights components within a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<ApplicationInsightsComponent> ListByResourceGroup(this IComponentsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of Application Insights components within a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationInsightsComponent>> ListByResourceGroupAsync(this IComponentsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Application Insights component. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> public static void Delete(this IComponentsOperations operations, string resourceGroupName, string resourceName) { operations.DeleteAsync(resourceGroupName, resourceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Application Insights component. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IComponentsOperations operations, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, resourceName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns an Application Insights component. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> public static ApplicationInsightsComponent Get(this IComponentsOperations operations, string resourceGroupName, string resourceName) { return operations.GetAsync(resourceGroupName, resourceName).GetAwaiter().GetResult(); } /// <summary> /// Returns an Application Insights component. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationInsightsComponent> GetAsync(this IComponentsOperations operations, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, resourceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates (or updates) an Application Insights component. Note: You cannot /// specify a different value for InstrumentationKey nor AppId in the Put /// operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='insightProperties'> /// Properties that need to be specified to create an Application Insights /// component. /// </param> public static ApplicationInsightsComponent CreateOrUpdate(this IComponentsOperations operations, string resourceGroupName, string resourceName, ApplicationInsightsComponent insightProperties) { return operations.CreateOrUpdateAsync(resourceGroupName, resourceName, insightProperties).GetAwaiter().GetResult(); } /// <summary> /// Creates (or updates) an Application Insights component. Note: You cannot /// specify a different value for InstrumentationKey nor AppId in the Put /// operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='insightProperties'> /// Properties that need to be specified to create an Application Insights /// component. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationInsightsComponent> CreateOrUpdateAsync(this IComponentsOperations operations, string resourceGroupName, string resourceName, ApplicationInsightsComponent insightProperties, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, resourceName, insightProperties, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an existing component's tags. To update other fields use the /// CreateOrUpdate method. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='tags'> /// Resource tags /// </param> public static ApplicationInsightsComponent UpdateTags(this IComponentsOperations operations, string resourceGroupName, string resourceName, IDictionary<string, string> tags = default(IDictionary<string, string>)) { return operations.UpdateTagsAsync(resourceGroupName, resourceName, tags).GetAwaiter().GetResult(); } /// <summary> /// Updates an existing component's tags. To update other fields use the /// CreateOrUpdate method. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='tags'> /// Resource tags /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationInsightsComponent> UpdateTagsAsync(this IComponentsOperations operations, string resourceGroupName, string resourceName, IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateTagsWithHttpMessagesAsync(resourceGroupName, resourceName, tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of all Application Insights components within a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationInsightsComponent> ListNext(this IComponentsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all Application Insights components within a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationInsightsComponent>> ListNextAsync(this IComponentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of Application Insights components within a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationInsightsComponent> ListByResourceGroupNext(this IComponentsOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of Application Insights components within a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationInsightsComponent>> ListByResourceGroupNextAsync(this IComponentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XSSF.UserModel { using System; using System.Collections.Generic; using System.IO; using System.Xml; using NPOI.OpenXml4Net.OPC; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS; public class XSSFPivotTable : POIXMLDocumentPart { protected internal static short CREATED_VERSION = 3; protected internal static short MIN_REFRESHABLE_VERSION = 3; protected internal static short UPDATED_VERSION = 3; private CT_PivotTableDefinition pivotTableDefinition; private XSSFPivotCacheDefinition pivotCacheDefinition; private XSSFPivotCache pivotCache; private XSSFPivotCacheRecords pivotCacheRecords; private ISheet parentSheet; private ISheet dataSheet; public XSSFPivotTable() : base() { pivotTableDefinition = new CT_PivotTableDefinition(); pivotCache = new XSSFPivotCache(); pivotCacheDefinition = new XSSFPivotCacheDefinition(); pivotCacheRecords = new XSSFPivotCacheRecords(); } /** * Creates an XSSFPivotTable representing the given package part and relationship. * Should only be called when Reading in an existing file. * * @param part - The package part that holds xml data representing this pivot table. * @param rel - the relationship of the given package part in the underlying OPC package */ protected XSSFPivotTable(PackagePart part) : base(part) { ReadFrom(part.GetInputStream()); } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] protected XSSFPivotTable(PackagePart part, PackageRelationship rel) : this(part) { } public void ReadFrom(Stream is1) { try { //XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); //Removing root element //options.LoadReplaceDocumentElement=(/*setter*/null); XmlDocument xmlDoc = ConvertStreamToXml(is1); pivotTableDefinition = CT_PivotTableDefinition.Parse(xmlDoc.DocumentElement, NamespaceManager); } catch (XmlException e) { throw new IOException(e.Message); } } public void SetPivotCache(XSSFPivotCache pivotCache) { this.pivotCache = pivotCache; } public XSSFPivotCache GetPivotCache() { return pivotCache; } public ISheet GetParentSheet() { return parentSheet; } public void SetParentSheet(XSSFSheet parentSheet) { this.parentSheet = parentSheet; } public CT_PivotTableDefinition GetCTPivotTableDefinition() { return pivotTableDefinition; } public void SetCTPivotTableDefinition(CT_PivotTableDefinition pivotTableDefinition) { this.pivotTableDefinition = pivotTableDefinition; } public XSSFPivotCacheDefinition GetPivotCacheDefinition() { return pivotCacheDefinition; } public void SetPivotCacheDefinition(XSSFPivotCacheDefinition pivotCacheDefinition) { this.pivotCacheDefinition = pivotCacheDefinition; } public XSSFPivotCacheRecords GetPivotCacheRecords() { return pivotCacheRecords; } public void SetPivotCacheRecords(XSSFPivotCacheRecords pivotCacheRecords) { this.pivotCacheRecords = pivotCacheRecords; } public ISheet GetDataSheet() { return dataSheet; } private void SetDataSheet(ISheet dataSheet) { this.dataSheet = dataSheet; } protected internal override void Commit() { //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); //Sets the pivotTableDefInition tag //xmlOptions.SetSaveSyntheticDocumentElement(new QName(CTPivotTableDefinition.type.Name. // GetNamespaceURI(), "pivotTableDefinition")); PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); pivotTableDefinition.Save(out1); out1.Close(); } /** * Set default values for the table defInition. */ protected internal void SetDefaultPivotTableDefinition() { //Not more than one until more Created pivotTableDefinition.multipleFieldFilters = (/*setter*/false); //Indentation increment for compact rows pivotTableDefinition.indent = (/*setter*/0); //The pivot version which Created the pivot cache Set to default value pivotTableDefinition.createdVersion = (byte)CREATED_VERSION; //Minimun version required to update the pivot cache pivotTableDefinition.minRefreshableVersion = (byte)MIN_REFRESHABLE_VERSION; //Version of the application which "updated the spreadsheet last" pivotTableDefinition.updatedVersion = (byte)UPDATED_VERSION; //Titles Shown at the top of each page when printed pivotTableDefinition.itemPrintTitles = (/*setter*/true); //Set autoformat properties pivotTableDefinition.useAutoFormatting = (/*setter*/true); pivotTableDefinition.applyNumberFormats = (/*setter*/false); pivotTableDefinition.applyWidthHeightFormats = (/*setter*/true); pivotTableDefinition.applyAlignmentFormats = (/*setter*/false); pivotTableDefinition.applyPatternFormats = (/*setter*/false); pivotTableDefinition.applyFontFormats = (/*setter*/false); pivotTableDefinition.applyBorderFormats = (/*setter*/false); pivotTableDefinition.cacheId = (/*setter*/pivotCache.GetCTPivotCache().cacheId); pivotTableDefinition.name = (/*setter*/"PivotTable" + pivotTableDefinition.cacheId); pivotTableDefinition.dataCaption = (/*setter*/"Values"); //Set the default style for the pivot table CT_PivotTableStyle style = pivotTableDefinition.AddNewPivotTableStyleInfo(); style.name = (/*setter*/"PivotStyleLight16"); style.showLastColumn = (/*setter*/true); style.showColStripes = (/*setter*/false); style.showRowStripes = (/*setter*/false); style.showColHeaders = (/*setter*/true); style.showRowHeaders = (/*setter*/true); } protected AreaReference GetPivotArea() { IWorkbook wb = GetDataSheet().Workbook; AreaReference pivotArea = GetPivotCacheDefinition().GetPivotArea(wb); return pivotArea; } /** * Verify column index (relative to first column in1 pivot area) is within the * pivot area * * @param columnIndex * @ */ private void CheckColumnIndex(int columnIndex) { AreaReference pivotArea = GetPivotArea(); int size = pivotArea.LastCell.Col - pivotArea.FirstCell.Col + 1; if (columnIndex < 0 || columnIndex >= size) { throw new IndexOutOfRangeException("Column Index: " + columnIndex + ", Size: " + size); } } /** * Add a row label using data from the given column. * @param columnIndex the index of the column to be used as row label. */ public void AddRowLabel(int columnIndex) { CheckColumnIndex(columnIndex); AreaReference pivotArea = GetPivotArea(); int lastRowIndex = pivotArea.LastCell.Row - pivotArea.FirstCell.Row; CT_PivotFields pivotFields = pivotTableDefinition.pivotFields; CT_PivotField pivotField = new CT_PivotField(); CT_Items items = pivotField.AddNewItems(); pivotField.axis = (/*setter*/ST_Axis.axisRow); pivotField.showAll = (/*setter*/false); for (int i = 0; i <= lastRowIndex; i++) { items.AddNewItem().t = (/*setter*/ST_ItemType.@default); } items.count = (/*setter*/items.SizeOfItemArray()); pivotFields.SetPivotFieldArray(columnIndex, pivotField); CT_RowFields rowFields; if (pivotTableDefinition.rowFields != null) { rowFields = pivotTableDefinition.rowFields; } else { rowFields = pivotTableDefinition.AddNewRowFields(); } rowFields.AddNewField().x = (/*setter*/columnIndex); rowFields.count = (/*setter*/rowFields.SizeOfFieldArray()); } public IList<int> GetRowLabelColumns() { if (pivotTableDefinition.rowFields != null) { List<int> columnIndexes = new List<int>(); foreach (CT_Field f in pivotTableDefinition.rowFields.GetFieldArray()) { columnIndexes.Add(f.x); } return columnIndexes; } else { return new List<int>(); } } /** * Add a column label using data from the given column and specified function * @param columnIndex the index of the column to be used as column label. * @param function the function to be used on the data * The following functions exists: * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp * @param valueFieldName the name of pivot table value field */ public void AddColumnLabel(DataConsolidateFunction function, int columnIndex, String valueFieldName) { CheckColumnIndex(columnIndex); AddDataColumn(columnIndex, true); AddDataField(function, columnIndex, valueFieldName); // colfield should be Added for the second one. if (pivotTableDefinition.dataFields.count == 2) { CT_ColFields colFields; if (pivotTableDefinition.colFields != null) { colFields = pivotTableDefinition.colFields; } else { colFields = pivotTableDefinition.AddNewColFields(); } colFields.AddNewField().x = (/*setter*/-2); colFields.count = (/*setter*/colFields.SizeOfFieldArray()); } } /** * Add a column label using data from the given column and specified function * @param columnIndex the index of the column to be used as column label. * @param function the function to be used on the data * The following functions exists: * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp */ public void AddColumnLabel(DataConsolidateFunction function, int columnIndex) { AddColumnLabel(function, columnIndex, function.Name); } /** * Add data field with data from the given column and specified function. * @param function the function to be used on the data * The following functions exists: * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp * @param columnIndex the index of the column to be used as column label. * @param valueFieldName the name of pivot table value field */ private void AddDataField(DataConsolidateFunction function, int columnIndex, String valueFieldName) { CheckColumnIndex(columnIndex); AreaReference pivotArea = GetPivotArea(); CT_DataFields dataFields; if (pivotTableDefinition.dataFields != null) { dataFields = pivotTableDefinition.dataFields; } else { dataFields = pivotTableDefinition.AddNewDataFields(); } CT_DataField dataField = dataFields.AddNewDataField(); dataField.subtotal = (ST_DataConsolidateFunction)(function.Value); ICell cell = GetDataSheet().GetRow(pivotArea.FirstCell.Row) .GetCell(pivotArea.FirstCell.Col + columnIndex); cell.SetCellType(CellType.String); dataField.name = (/*setter*/valueFieldName); dataField.fld = (uint)columnIndex; dataFields.count = (/*setter*/dataFields.SizeOfDataFieldArray()); } /** * Add column Containing data from the referenced area. * @param columnIndex the index of the column Containing the data * @param isDataField true if the data should be displayed in the pivot table. */ public void AddDataColumn(int columnIndex, bool isDataField) { CheckColumnIndex(columnIndex); CT_PivotFields pivotFields = pivotTableDefinition.pivotFields; CT_PivotField pivotField = new CT_PivotField(); pivotField.dataField = (/*setter*/isDataField); pivotField.showAll = (/*setter*/false); pivotFields.SetPivotFieldArray(columnIndex, pivotField); } /** * Add filter for the column with the corresponding index and cell value * @param columnIndex index of column to filter on */ public void AddReportFilter(int columnIndex) { CheckColumnIndex(columnIndex); AreaReference pivotArea = GetPivotArea(); int lastRowIndex = pivotArea.LastCell.Row - pivotArea.FirstCell.Row; CT_PivotFields pivotFields = pivotTableDefinition.pivotFields; CT_PivotField pivotField = new CT_PivotField(); CT_Items items = pivotField.AddNewItems(); pivotField.axis = (/*setter*/ST_Axis.axisPage); pivotField.showAll = (/*setter*/false); for (int i = 0; i <= lastRowIndex; i++) { items.AddNewItem().t = (/*setter*/ST_ItemType.@default); } items.count = (/*setter*/items.SizeOfItemArray()); pivotFields.SetPivotFieldArray(columnIndex, pivotField); CT_PageFields pageFields; if (pivotTableDefinition.pageFields != null) { pageFields = pivotTableDefinition.pageFields; //Another filter has already been Created pivotTableDefinition.multipleFieldFilters = (/*setter*/true); } else { pageFields = pivotTableDefinition.AddNewPageFields(); } CT_PageField pageField = pageFields.AddNewPageField(); pageField.hier = (/*setter*/-1); pageField.fld = (/*setter*/columnIndex); pageFields.count = (/*setter*/pageFields.SizeOfPageFieldArray()); pivotTableDefinition.location.colPageCount = (/*setter*/pageFields.count); } /** * Creates cacheSource and workSheetSource for pivot table and sets the source reference as well assets the location of the pivot table * @param sourceRef Source for data for pivot table - mutually exclusive with sourceName * @param sourceName Source for data for pivot table - mutually exclusive with sourceRef * @param position Position for pivot table in sheet * @param sourceSheet Sheet where the source will be collected from */ protected internal void CreateSourceReferences(CellReference position, ISheet sourceSheet, IPivotTableReferenceConfigurator refConfig) { //Get cell one to the right and one down from position, add both to AreaReference and Set pivot table location. AreaReference destination = new AreaReference(position, new CellReference(position.Row + 1, position.Col + 1)); CT_Location location; if (pivotTableDefinition.location == null) { location = pivotTableDefinition.AddNewLocation(); location.firstDataCol = (/*setter*/1); location.firstDataRow = (/*setter*/1); location.firstHeaderRow = (/*setter*/1); } else { location = pivotTableDefinition.location; } location.@ref = (/*setter*/destination.FormatAsString()); pivotTableDefinition.location = (/*setter*/location); //Set source for the pivot table CT_PivotCacheDefinition cacheDef = GetPivotCacheDefinition().GetCTPivotCacheDefinition(); CT_CacheSource cacheSource = cacheDef.AddNewCacheSource(); cacheSource.type = (/*setter*/ST_SourceType.worksheet); CT_WorksheetSource worksheetSource = cacheSource.AddNewWorksheetSource(); worksheetSource.sheet = (/*setter*/sourceSheet.SheetName); SetDataSheet(sourceSheet); refConfig.ConfigureReference(worksheetSource); if (worksheetSource.name == null && worksheetSource.@ref == null) throw new ArgumentException("Pivot table source area reference or name must be specified."); } protected internal void CreateDefaultDataColumns() { CT_PivotFields pivotFields; if (pivotTableDefinition.pivotFields != null) { pivotFields = pivotTableDefinition.pivotFields; } else { pivotFields = pivotTableDefinition.AddNewPivotFields(); } AreaReference sourceArea = GetPivotArea(); int firstColumn = sourceArea.FirstCell.Col; int lastColumn = sourceArea.LastCell.Col; CT_PivotField pivotField; for (int i = firstColumn; i <= lastColumn; i++) { pivotField = pivotFields.AddNewPivotField(); pivotField.dataField = (/*setter*/false); pivotField.showAll = (/*setter*/false); } pivotFields.count = (/*setter*/pivotFields.SizeOfPivotFieldArray()); } public interface IPivotTableReferenceConfigurator { /** * Configure the name or area reference for the pivot table * @param wsSource CTWorksheetSource that needs the pivot source reference assignment */ void ConfigureReference(CT_WorksheetSource wsSource); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections.Generic; namespace OLEDB.Test.ModuleCore { //////////////////////////////////////////////////////////////// // CKeywordParser // //////////////////////////////////////////////////////////////// public class CKeywordParser { //Enum protected enum PARSE { Initial, Keyword, Equal, Value, SingleBegin, SingleEnd, DoubleBegin, DoubleEnd, End }; //Accessors //Note: You can override these if you want to leverage our parser (inherit), and change //some of the behavior (without reimplementing it). private static Tokens s_DefaultTokens = new Tokens(); public class Tokens { public string Equal = "="; public string Seperator = ";"; public string SingleQuote = "'"; public string DoubleQuote = "\""; }; //Methods public static MyDict<string, string> ParseKeywords(string str) { return ParseKeywords(str, s_DefaultTokens); } public static MyDict<string, string> ParseKeywords(string str, Tokens tokens) { PARSE state = PARSE.Initial; int index = 0; int keyStart = 0; MyDict<string, string> keywords = new MyDict<string, string>(); string key = null; if (str != null) { StringBuilder builder = new StringBuilder(str.Length); for (; index < str.Length; index++) { char ch = str[index]; switch (state) { case PARSE.Initial: if (Char.IsLetterOrDigit(ch)) { keyStart = index; state = PARSE.Keyword; } break; case PARSE.Keyword: if (tokens.Equal.IndexOf(ch) >= 0) { //Note: We have a case-insensitive hashtable so we don't have to lowercase key = str.Substring(keyStart, index - keyStart).Trim(); state = PARSE.Equal; } break; case PARSE.Equal: if (Char.IsWhiteSpace(ch)) break; builder.Length = 0; //Note: Since we allow you to alter the tokens, these are not //constant values, so we cannot use a switch statement... if (tokens.SingleQuote.IndexOf(ch) >= 0) { state = PARSE.SingleBegin; } else if (tokens.DoubleQuote.IndexOf(ch) >= 0) { state = PARSE.DoubleBegin; } else if (tokens.Seperator.IndexOf(ch) >= 0) { keywords[key] = String.Empty; state = PARSE.Initial; } else { state = PARSE.Value; builder.Append(ch); } break; case PARSE.Value: if (tokens.Seperator.IndexOf(ch) >= 0) { keywords[key] = (builder.ToString()).Trim(); state = PARSE.Initial; } else { builder.Append(ch); } break; case PARSE.SingleBegin: if (tokens.SingleQuote.IndexOf(ch) >= 0) state = PARSE.SingleEnd; else builder.Append(ch); break; case PARSE.DoubleBegin: if (tokens.DoubleQuote.IndexOf(ch) >= 0) state = PARSE.DoubleEnd; else builder.Append(ch); break; case PARSE.SingleEnd: if (tokens.SingleQuote.IndexOf(ch) >= 0) { state = PARSE.SingleBegin; builder.Append(ch); } else { keywords[key] = builder.ToString(); state = PARSE.End; goto case PARSE.End; } break; case PARSE.DoubleEnd: if (tokens.DoubleQuote.IndexOf(ch) >= 0) { state = PARSE.DoubleBegin; builder.Append(ch); } else { keywords[key] = builder.ToString(); state = PARSE.End; goto case PARSE.End; } break; case PARSE.End: if (tokens.Seperator.IndexOf(ch) >= 0) { state = PARSE.Initial; } break; default: Common.Assert(false, "Unhandled State " + Common.ToString(state)); break; } } switch (state) { case PARSE.Initial: case PARSE.Keyword: case PARSE.End: break; case PARSE.Equal: keywords[key] = String.Empty; break; case PARSE.Value: keywords[key] = (builder.ToString()).Trim(); break; case PARSE.SingleBegin: case PARSE.DoubleBegin: case PARSE.SingleEnd: case PARSE.DoubleEnd: keywords[key] = builder.ToString(); break; default: Common.Assert(false, "Unhandled State " + Common.ToString(state)); break; }; } return keywords; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Web; using ASC.Data.Storage; using ASC.Forum; using ASC.Web.Core.Users; using ASC.Web.Core.Utility.Skins; using ASC.Web.Studio.Utility; namespace ASC.Web.UserControls.Forum.Common { public class ForumManager { private class SecurityActionValidator : ISecurityActionView { #region ISecurityActionView Members public bool IsAccessible { get; set; } public event EventHandler<SecurityAccessEventArgs> ValidateAccess; #endregion public void OnValidate(SecurityAccessEventArgs e) { if (ValidateAccess != null) ValidateAccess(this, e); } } internal static string ForumScriptKey { get { return "__forum_core_script"; } } internal static string SearchHelperScriptKey { get { return "__searchhelper_core_script"; } } private static readonly object _syncObj = new object(); private static readonly Hashtable _settingsCollection; private readonly SecurityActionValidator _securityValidator; public IPresenterFactory PresenterFactory { get; private set; } public Settings Settings { get; private set; } internal ForumManager(Settings settings) { SessionKeys = new ForumSessionKeys(settings.ID); Settings = settings; PresenterFactory = new ForumPresenterFactory(); _securityValidator = new SecurityActionValidator(); IPresenter securityPresenter = PresenterFactory.GetPresenter<ISecurityActionView>(); securityPresenter.SetView(_securityValidator); } static ForumManager() { _settingsCollection = Hashtable.Synchronized(new Hashtable()); } public static ForumManager GetForumManager(Guid settingsID) { lock (_syncObj) { if (_settingsCollection.ContainsKey(settingsID)) return (_settingsCollection[settingsID] as Settings).ForumManager; } return null; } public bool ValidateAccessSecurityAction(ForumAction forumAction, object targetObject) { _securityValidator.OnValidate(new SecurityAccessEventArgs(forumAction, targetObject)); return _securityValidator.IsAccessible; } public string GetTopicImage(Topic topic) { var isNew = topic.IsNew(); if (!topic.Sticky) { if (topic.Type == TopicType.Informational && isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_new_closed.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_new.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && !isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_closed.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && !isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_new_closed.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_new.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && !isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_closed.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && !isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll.png", Settings.ImageItemID); } else { if (topic.Type == TopicType.Informational && isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_new_closed_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_new_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && !isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_closed_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Informational && !isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("top_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_new_closed_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_new_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && !isNew && topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_closed_sticky.png", Settings.ImageItemID); else if (topic.Type == TopicType.Poll && !isNew && !topic.Closed) return WebImageSupplier.GetAbsoluteWebPath("poll_sticky.png", Settings.ImageItemID); } return ""; } internal IDataStore GetStore() { return StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), this.Settings.FileStoreModuleID); } #region Remove and Find Attachments public string GetAttachmentVirtualDirPath(Thread thread, Guid settingsID, Guid userID, out string offsetPhysicalPath) { offsetPhysicalPath = thread.CategoryID + "\\" + thread.ID + "\\" + userID.ToString(); return thread.CategoryID + "/" + thread.ID + "/" + userID.ToString(); } public string GetAttachmentWebPath(Attachment attachment) { return GetStore().GetUri(attachment.OffsetPhysicalPath).ToString(); } public void RemoveAttachments(string offsetPhysicalPath) { try { var store = GetStore(); store.Delete(offsetPhysicalPath); } catch { }; } public void RemoveAttachments(Post post) { if (post.Attachments == null) return; foreach (var attachment in post.Attachments) { RemoveAttachments(attachment.OffsetPhysicalPath); } } public void RemoveAttachments(string[] attachmentPaths) { foreach (var offsetPath in attachmentPaths) { RemoveAttachments(offsetPath); } } public void RemoveAttachments(Thread thread) { string attachmentTopicDir = thread.CategoryID + "\\" + thread.ID; ClearDirectory(attachmentTopicDir); } public void RemoveAttachments(ThreadCategory threadCategory) { ClearDirectory(threadCategory.ID.ToString()); } private void ClearDirectory(string directoryPath) { var store = GetStore(); try { store.DeleteFiles(directoryPath, "*", true); } catch { }; } #endregion public string GetHTMLImgUserAvatar(Guid userID) { return "<img alt=\"\" class='userPhoto' src=\"" + UserPhotoManager.GetBigPhotoURL(userID) + "\"/>"; } public PageLocation CurrentPage { get { if (HttpContext.Current != null && HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation] != null) return (PageLocation)HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation]; return new PageLocation(ForumPage.Default, Settings.StartPageAbsolutePath); } } public PageLocation PreviousPage { get { if (HttpContext.Current != null && HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation] != null) return (PageLocation)HttpContext.Current.Session[this.SessionKeys.PreviousPageLocation]; return new PageLocation(ForumPage.Default, Settings.StartPageAbsolutePath); } } public void SetCurrentPage(ForumPage page) { if (HttpContext.Current != null) { PageLocation current = new PageLocation(ForumPage.Default, Settings.StartPageAbsolutePath); if (HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation] != null) current = (PageLocation)HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation]; PageLocation previous = (PageLocation)current.Clone(); if (previous.Page != page) HttpContext.Current.Session[this.SessionKeys.PreviousPageLocation] = previous; current = new PageLocation(page, HttpContext.Current.Request.GetUrlRewriter().AbsoluteUri); HttpContext.Current.Session[this.SessionKeys.CurrentPageLocation] = current; } } public ForumSessionKeys SessionKeys { get; private set; } public class ForumSessionKeys { private Guid _settingsID; public ForumSessionKeys(Guid settingsID) { _settingsID = settingsID; } public string CurrentPageLocation { get { return "forum_current_page_location" + _settingsID.ToString(); } } public string PreviousPageLocation { get { return "forum_previous_page_location" + _settingsID.ToString(); } } } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; namespace DaydreamElements.Teleport { /// Allow moving the player in the scene by teleporting. /// You can fully customize and extend the teleport behavior /// by changing the detector, visualizer, and transition classes. /// /// Teleportation is activated by using triggers, which allow /// you to pick which controller buttons will activate teleportation /// and rotation. To setup a trigger simply add it as a component /// and then assign that component for one of the TeleportController triggers. /// You can build your own triggers by subclass BaseActionTrigger if /// you have a custom gesture or controller scheme to integrate with. /// /// Here's an example of a common teleport trigger configuration: /// startTrigger = TouchpadTouchDownTrigger /// cancelTrigger = TouchpadTouchUpTrigger /// commitTrigger = TouchpadClickTrigger /// rotateLeftTrigger = TouchpadSideTrigger (left configured) /// rotateRightTrigger = TouchpadSideTrigger (right configured) public class TeleportController : MonoBehaviour { /// Player tracking. [Tooltip("Player transform to move when teleporting")] public Transform player; /// Controller transform. [Tooltip("Controller transform used for tracking tilt angle")] public Transform controller; /// Trigger use to start teleport arc selection [Tooltip("Trigger used to start teleport selection")] public BaseActionTrigger teleportStartTrigger; /// Trigger used to commit selection and perform teleport. [Tooltip("Trigger used to commit selection and perform teleport")] public BaseActionTrigger teleportCommitTrigger; /// Trigger use to cancel teleport arc selection [Tooltip("Optional trigger used to cancel teleport selection")] public BaseActionTrigger teleportCancelTrigger; /// Trigger used to activate left rotation. [Tooltip("Trigger used to signal left rotation")] public BaseActionTrigger rotateLeftTrigger; /// Trigger used to activate right rotation. [Tooltip("Trigger used to signal right rotation")] public BaseActionTrigger rotateRightTrigger; /// Detect if there's a valid teleport selection. [Tooltip("Detects if there's a valid teleport selection")] public BaseTeleportDetector detector; /// Visualize active teleport selection. [Tooltip("Visualize a teleport selection")] public BaseTeleportVisualizer visualizer; /// Transition used for teleporting if selection is valid. [Tooltip("Transition to use when teleporting player")] public BaseTeleportTransition transition; /// Rotate player when they click the side of the d-pad. [Tooltip("Rotate the player when they click the side of the touchpad")] public bool allowRotation = true; /// Speed to rotate at while trigger is active. [Tooltip("Rotation speed while trigger is active")] public float rotationSpeed = 45.0f; /// Rotation amount in degrees. public float rotationDegreesIncrement = 20.0f; /// Flag for if we're currently showing teleport selection. private bool selectionIsActive; /// State tracking for completing animated rotations. private bool isRotating; private Quaternion finalRotation; // The transform of the current controller. private Transform currentController; // The selection result returned by the detector. private BaseTeleportDetector.Result selectionResult; /// Returns true if the user is currently selecting a location to teleport to. public bool IsSelectingTeleportLocation { get { return selectionIsActive; } } /// Returns true if the user is currently teleporting. public bool IsTeleporting { get { if (transition == null) { return false; } return transition.IsTransitioning; } } #if UNITY_EDITOR void OnValidate() { if (Application.isPlaying && isActiveAndEnabled) { Start(); } } #endif void Start() { if (detector == null) { detector = GetComponent<BaseTeleportDetector>(); } if (visualizer == null) { visualizer = GetComponent<BaseTeleportVisualizer>(); } if (transition == null) { transition = GetComponent<BaseTeleportTransition>(); } } void OnDisable() { if (!selectionIsActive) { return; } selectionIsActive = false; isRotating = false; // Clear selection state. if (visualizer != null) { visualizer.EndSelection(); } // Clear transition state. if (transition != null && transition.IsTransitioning) { transition.CancelTransition(); } } void Update() { if (IsConfigured() == false) { return; } currentController = GetControllerTransform(); // Complete active teleport transitions. if (IsTeleporting) { visualizer.OnTeleport(); // Update the visualization. visualizer.UpdateSelection(currentController, selectionResult); return; } // If rotation is allowed, handle player rotations. if (allowRotation) { HandlePlayerRotations(); } // If a teleport selection session has not started, check the appropriate // trigger to see if one should start. if (selectionIsActive == false) { if (teleportStartTrigger.TriggerActive()) { StartTeleportSelection(); } } // Get the current selection result from the detector. float playerHeight = DetectPlayerHeight(); selectionResult = detector.DetectSelection(currentController, playerHeight); // Update the visualization. visualizer.UpdateSelection(currentController, selectionResult); // If not actively teleporting, just return. if (selectionIsActive == false) { return; } // Check for the optional cancel trigger. if (teleportCancelTrigger != null && teleportCancelTrigger.TriggerActive() && !teleportCommitTrigger.TriggerActive()) { EndTeleportSelection(); return; } // When trigger deactivates we finish the teleport. if (selectionIsActive && teleportCommitTrigger.TriggerActive()) { if (selectionResult.selectionIsValid) { Vector3 nextPlayerPosition = new Vector3( selectionResult.selection.x, selectionResult.selection.y + playerHeight, selectionResult.selection.z); // Start a transition to move the player. transition.StartTransition( player, currentController, nextPlayerPosition); } EndTeleportSelection(); } } private void StartTeleportSelection() { detector.StartSelection(currentController); visualizer.StartSelection(currentController); selectionIsActive = true; } private void EndTeleportSelection() { detector.EndSelection(); visualizer.EndSelection(); selectionIsActive = false; } private float DetectPlayerHeight() { RaycastHit hit; if (Physics.Raycast(player.position, Vector3.down, out hit)) { return hit.distance; } else{ // Log error, and default to something sensible. Debug.LogError("Failed to detect player height by raycasting downwards"); return 1.0f; } } // Returns the transform of the assigned controller. // The pointer provided by GVR is used if no controller is assigned. private Transform GetControllerTransform() { if (controller != null) { return controller; } if (GvrPointerInputModule.Pointer == null) { return null; } return GvrPointerInputModule.Pointer.PointerTransform; } /// Returns true if player rotation was applied. private bool HandlePlayerRotations() { // Rotate left. if (rotateLeftTrigger != null && rotateLeftTrigger.TriggerActive()) { Quaternion left = Quaternion.Euler(0, -rotationDegreesIncrement, 0); finalRotation = player.rotation * left; isRotating = true; } // Rotate right. if (rotateRightTrigger != null && rotateRightTrigger.TriggerActive()) { Quaternion right = Quaternion.Euler(0, rotationDegreesIncrement, 0); finalRotation = player.rotation * right; isRotating = true; } // Continue a rotation animation each frame. if (isRotating) { player.rotation = Quaternion.Lerp(player.rotation, finalRotation, rotationSpeed * Time.deltaTime); if (player.rotation == finalRotation) { isRotating = false; } return true; } return false; } // Make sure we have required modules for teleporting. private bool IsConfigured() { if (teleportStartTrigger == null) { Debug.LogError("Can't teleport without start trigger"); return false; } if (teleportCommitTrigger == null) { Debug.LogError("Can't teleoprt without commit trigger"); return false; } if (detector == null) { Debug.LogError("Can't teleport without detector"); return false; } if (visualizer == null) { Debug.LogError("Can't teleport without visualizer"); return false; } if (transition == null) { Debug.LogError("Can't teleport without transition"); return false; } if (player == null) { Debug.LogError("Can't teleport without player"); return false; } if (GetControllerTransform() == null) { Debug.LogError("Can't teleport without controller"); return false; } if (allowRotation) { if (rotateLeftTrigger == null) { Debug.LogError("Can't rotate left without trigger"); return false; } if (rotateRightTrigger == null) { Debug.LogError("Can't rotate right without trigger"); return false; } } return true; } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // // Copyright (C) 2008 Novell (https://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. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // // The NUnit version of this file introduces conditional compilation for // building under .NET Standard // // 11/5/2015 - // Change namespace to avoid conflict with user code use of mono.options using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using NUnit.Compatibility; // Missing XML Docs #pragma warning disable 1591 #if !NETSTANDARD1_4 using System.Security.Permissions; using System.Runtime.Serialization; #endif namespace NUnit.Options { public class OptionValueCollection : IList, IList<string> { readonly List<string> values = new List<string>(); readonly OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException (nameof(index)); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private readonly OptionSet set; private readonly OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { readonly string prototype; readonly string description; readonly string[] names; readonly OptionValueType type; readonly int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException (nameof(prototype)); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", nameof(prototype)); if (maxValueCount < 0) throw new ArgumentOutOfRangeException (nameof(maxValueCount)); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", nameof(maxValueCount)); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), nameof(maxValueCount)); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", nameof(prototype)); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { Type tt = typeof (T); bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType && !tt.GetTypeInfo().IsGenericTypeDefinition && tt.GetGenericTypeDefinition () == typeof (Nullable<>); Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T); #if !NETSTANDARD1_4 TypeConverter conv = TypeDescriptor.GetConverter (targetType); #endif T t = default (T); try { if (value != null) #if NETSTANDARD1_4 t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture); #else t = (T) conv.ConvertFromString (value); #endif } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, targetType.Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private readonly string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } #if SERIALIZATION protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } #endif public string OptionName { get {return this.option;} } #if SERIALIZATION [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } #endif } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { string Localizer(string msg) { return msg; } public string MessageLocalizer(string msg) { return msg; } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException (nameof(item)); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException (nameof(option)); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException (nameof(option)); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { readonly Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException (nameof(action)); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException (nameof(action)); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException (nameof(action)); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { readonly Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException (nameof(action)); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { readonly OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException (nameof(action)); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly static Regex ValueOption = new Regex( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException (nameof(argument)); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (Localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (Localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } bool indent = false; string prefix = new string (' ', OptionWidth+2); foreach (string line in GetLines (Localizer (GetDescription (p.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); indent = true; } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, Localizer ("[")); } Write (o, ref written, Localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, Localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, Localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static IEnumerable<string> GetLines (string description) { if (string.IsNullOrEmpty (description)) { yield return string.Empty; yield break; } int length = 80 - OptionWidth - 1; int start = 0, end; do { end = GetLineEnd (start, length, description); char c = description [end-1]; if (char.IsWhiteSpace (c)) --end; bool writeContinuation = end != description.Length && !IsEolChar (c); string line = description.Substring (start, end - start) + (writeContinuation ? "-" : ""); yield return line; start = end; if (char.IsWhiteSpace (c)) ++start; length = 80 - OptionWidth - 2 - 1; } while (end < description.Length); } private static bool IsEolChar (char c) { return !char.IsLetterOrDigit (c); } private static int GetLineEnd (int start, int length, string description) { int end = System.Math.Min (start + length, description.Length); int sep = -1; for (int i = start+1; i < end; ++i) { if (description [i] == '\n') return i+1; if (IsEolChar (description [i])) sep = i+1; } if (sep == -1 || end == description.Length) return end; return sep; } } }
using System; using System.ComponentModel; using System.Xml.Serialization; using Wyam.Feeds.Syndication.Extensions; namespace Wyam.Feeds.Syndication.Rdf { /// <summary> /// RDF 1.0 Item /// http://web.resource.org/rss/1.0/spec#s5.5 /// </summary> public class RdfItem : RdfBase, IFeedItem { private string _description = string.Empty; // extensions private DublinCore _dublinCore = null; private string _contentEncoded = null; private Uri _wfwComment = null; private Uri _wfwCommentRss = null; private int? _slashComments = null; public RdfItem() { } public RdfItem(IFeedItem source) { // ** IFeedMetadata // ID Link = source.ID.ToString(); // Title string title = source.Title; if (!string.IsNullOrWhiteSpace(title)) { Title = title; } // Description string description = source.Description; if (!string.IsNullOrEmpty(description)) { Description = description; } // Author string author = source.Author; if (!string.IsNullOrEmpty(author)) { DublinCore[DublinCore.TermName.Creator] = author; } // Published DateTime? published = source.Published; if (published.HasValue) { DublinCore[DublinCore.TermName.Date] = ConvertToString(published.Value); } // Updated DateTime? updated = source.Updated; if (updated.HasValue) { DublinCore[DublinCore.TermName.Date] = ConvertToString(updated.Value); } // Link Uri link = source.Link; if (link != null) { Link = link.ToString(); } // ImageLink // Not in RDF // ** IFeedItem // Content string content = source.Content; if (!string.IsNullOrEmpty(content)) { ContentEncoded = content; } // ThreadLink Uri threadLink = source.ThreadLink; if (threadLink != null) { _wfwCommentRss = threadLink; } // ThreadCount int? threadCount = source.ThreadCount; if (threadCount.HasValue) { SlashComments = threadCount.Value; } // ThreadUpdated // Not in RDF } /// <summary> /// Gets and sets a brief description of the channel's content, function, source, etc. /// </summary> /// <remarks> /// Suggested maximum length is 500 characters. /// Required even if empty. /// </remarks> [XmlElement("description")] public string Description { get { return _description; } set { _description = string.IsNullOrEmpty(value) ? string.Empty : value; } } protected internal string Copyright { get { return DublinCore[DublinCore.TermName.Rights]; } set { DublinCore[DublinCore.TermName.Rights] = value; } } /// <summary> /// Gets and sets the encoded content for this item /// </summary> [DefaultValue(null)] [XmlElement(ContentEncodedElement, Namespace=ContentNamespace)] public string ContentEncoded { get { return _contentEncoded; } set { _contentEncoded = value; } } /// <summary> /// Gets and sets the Uri to which comments can be POSTed /// </summary> [DefaultValue(null)] [XmlElement(WfwCommentElement, Namespace=WfwNamespace)] public string WfwComment { get { return ConvertToString(_wfwComment); } set { _wfwComment = ConvertToUri(value); } } /// <summary> /// Gets and sets the Uri at which a feed of comments can be found /// </summary> [DefaultValue(null)] [XmlElement(WfwCommentRssElement, Namespace=WfwNamespace)] public string WfwCommentRss { get { return ConvertToString(_wfwCommentRss); } set { _wfwCommentRss = ConvertToUri(value); } } /// <summary> /// Gets and sets the number of comments for this item /// </summary> [DefaultValue(null)] [XmlElement(SlashCommentsElement, Namespace=SlashNamespace)] public int SlashComments { get { if (!_slashComments.HasValue) { return 0; } return _slashComments.Value; } set { _slashComments = value; } } [XmlIgnore] public bool SlashCommentsSpecified { get { return _slashComments.HasValue; } set { } } /// <summary> /// Allows IWebFeedItem to access DublinCore /// </summary> /// <remarks> /// Note this only gets filled on first access /// </remarks> internal DublinCore DublinCore { get { if (_dublinCore == null) { _dublinCore = new DublinCore(); FillExtensions(_dublinCore); } return _dublinCore; } } Uri IFeedMetadata.ID { get { Uri id = ((IUriProvider)this).Uri; if (id == null) { Uri.TryCreate(About, UriKind.RelativeOrAbsolute, out id); } return id; } } string IFeedMetadata.Title { get { string title = Title; if (string.IsNullOrEmpty(title)) { title = DublinCore[DublinCore.TermName.Title]; } return title; } } string IFeedMetadata.Description { get { string description = _description; if (string.IsNullOrEmpty(description)) { description = ContentEncoded; if (string.IsNullOrEmpty(description)) { description = DublinCore[DublinCore.TermName.Description]; if (string.IsNullOrEmpty(description)) { description = DublinCore[DublinCore.TermName.Subject]; } } } return description; } } string IFeedMetadata.Author { get { string author = DublinCore[DublinCore.TermName.Creator]; if (string.IsNullOrEmpty(author)) { author = DublinCore[DublinCore.TermName.Contributor]; if (string.IsNullOrEmpty(author)) { author = DublinCore[DublinCore.TermName.Publisher]; } } return author; } } DateTime? IFeedMetadata.Published { get { string date = DublinCore[DublinCore.TermName.Date]; return ConvertToDateTime(date); } } DateTime? IFeedMetadata.Updated { get { string date = DublinCore[DublinCore.TermName.Date]; return ConvertToDateTime(date); } } Uri IFeedMetadata.Link => ((IUriProvider)this).Uri; Uri IFeedMetadata.ImageLink => null; string IFeedItem.Content => ContentEncoded; Uri IFeedItem.ThreadLink => _wfwCommentRss; int? IFeedItem.ThreadCount { get { if (!SlashCommentsSpecified) { return null; } return SlashComments; } } DateTime? IFeedItem.ThreadUpdated => null; public override void AddNamespaces(XmlSerializerNamespaces namespaces) { if (_contentEncoded != null) { namespaces.Add(ContentPrefix, ContentNamespace); } if (_wfwComment != null || _wfwCommentRss != null) { namespaces.Add(WfwPrefix, WfwNamespace); } base.AddNamespaces(namespaces); } } }
namespace VersionOne.VisualStudio.VSPackage.Controls { partial class RichTextEditorControl { /// <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.ctlHtmlEditor = new onlyconnect.HtmlEditor(); this.tsToolMenu = new System.Windows.Forms.ToolStrip(); this.btnBold = new System.Windows.Forms.ToolStripButton(); this.btnItalic = new System.Windows.Forms.ToolStripButton(); this.btnUnderline = new System.Windows.Forms.ToolStripButton(); this.btnStrikethrough = new System.Windows.Forms.ToolStripButton(); this.btnRemoveFormat = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.btnJustifyLeft = new System.Windows.Forms.ToolStripButton(); this.btnJustifyRight = new System.Windows.Forms.ToolStripButton(); this.btnJustifyCenter = new System.Windows.Forms.ToolStripButton(); this.btnJustifyFull = new System.Windows.Forms.ToolStripButton(); this.btnBulletedList = new System.Windows.Forms.ToolStripButton(); this.btnNumberedList = new System.Windows.Forms.ToolStripButton(); this.btnIncreaseIndent = new System.Windows.Forms.ToolStripButton(); this.btnDecreaseIndent = new System.Windows.Forms.ToolStripButton(); this.btnUndo = new System.Windows.Forms.ToolStripButton(); this.btnRedo = new System.Windows.Forms.ToolStripButton(); this.tsToolMenu.SuspendLayout(); this.SuspendLayout(); // // ctlHtmlEditor // this.ctlHtmlEditor.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.ctlHtmlEditor.DefaultComposeSettings.BackColor = System.Drawing.Color.White; this.ctlHtmlEditor.DefaultComposeSettings.DefaultFont = new System.Drawing.Font("Arial", 10F); this.ctlHtmlEditor.DefaultComposeSettings.Enabled = false; this.ctlHtmlEditor.DefaultComposeSettings.ForeColor = System.Drawing.Color.Black; this.ctlHtmlEditor.DefaultPreamble = onlyconnect.EncodingType.UTF8; this.ctlHtmlEditor.DocumentEncoding = onlyconnect.EncodingType.WindowsCurrent; this.ctlHtmlEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ctlHtmlEditor.IsDesignMode = true; this.ctlHtmlEditor.Location = new System.Drawing.Point(0, 28); this.ctlHtmlEditor.Name = "ctlHtmlEditor"; this.ctlHtmlEditor.SelectionAlignment = System.Windows.Forms.HorizontalAlignment.Left; this.ctlHtmlEditor.SelectionBackColor = System.Drawing.Color.Empty; this.ctlHtmlEditor.SelectionBullets = false; this.ctlHtmlEditor.SelectionFont = null; this.ctlHtmlEditor.SelectionForeColor = System.Drawing.Color.Empty; this.ctlHtmlEditor.SelectionNumbering = false; this.ctlHtmlEditor.Size = new System.Drawing.Size(459, 147); this.ctlHtmlEditor.TabIndex = 1; // // tsToolMenu // this.tsToolMenu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.tsToolMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnBold, this.btnItalic, this.btnUnderline, this.btnStrikethrough, this.btnRemoveFormat, this.toolStripSeparator1, this.btnJustifyLeft, this.btnJustifyRight, this.btnJustifyCenter, this.btnJustifyFull, this.btnBulletedList, this.btnNumberedList, this.btnIncreaseIndent, this.btnDecreaseIndent, this.btnUndo, this.btnRedo}); this.tsToolMenu.Location = new System.Drawing.Point(0, 0); this.tsToolMenu.Name = "tsToolMenu"; this.tsToolMenu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.tsToolMenu.Size = new System.Drawing.Size(459, 28); this.tsToolMenu.TabIndex = 2; this.tsToolMenu.Text = "toolStrip1"; // // btnBold // this.btnBold.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnBold.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Bold; this.btnBold.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnBold.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnBold.Name = "btnBold"; this.btnBold.Size = new System.Drawing.Size(25, 25); this.btnBold.Text = "Bold"; // // btnItalic // this.btnItalic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnItalic.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Italic; this.btnItalic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnItalic.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnItalic.Name = "btnItalic"; this.btnItalic.Size = new System.Drawing.Size(25, 25); this.btnItalic.Text = "Italic"; // // btnUnderline // this.btnUnderline.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnUnderline.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Underline; this.btnUnderline.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnUnderline.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnUnderline.Name = "btnUnderline"; this.btnUnderline.Size = new System.Drawing.Size(25, 25); this.btnUnderline.Text = "Underline"; // // btnStrikethrough // this.btnStrikethrough.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnStrikethrough.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Strikethrough; this.btnStrikethrough.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnStrikethrough.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnStrikethrough.Name = "btnStrikethrough"; this.btnStrikethrough.Size = new System.Drawing.Size(25, 25); this.btnStrikethrough.Text = "Strikethrough"; // // btnRemoveFormat // this.btnRemoveFormat.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnRemoveFormat.Image = global::VersionOne.VisualStudio.VSPackage.Resources.RemoveFormat; this.btnRemoveFormat.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnRemoveFormat.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnRemoveFormat.Name = "btnRemoveFormat"; this.btnRemoveFormat.Size = new System.Drawing.Size(25, 25); this.btnRemoveFormat.Text = "Remove format"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 28); // // btnJustifyLeft // this.btnJustifyLeft.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnJustifyLeft.Image = global::VersionOne.VisualStudio.VSPackage.Resources.JustifyLeft; this.btnJustifyLeft.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnJustifyLeft.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnJustifyLeft.Name = "btnJustifyLeft"; this.btnJustifyLeft.Size = new System.Drawing.Size(25, 25); this.btnJustifyLeft.Text = "Justify left"; // // btnJustifyRight // this.btnJustifyRight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnJustifyRight.Image = global::VersionOne.VisualStudio.VSPackage.Resources.JustifyRight; this.btnJustifyRight.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnJustifyRight.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnJustifyRight.Name = "btnJustifyRight"; this.btnJustifyRight.Size = new System.Drawing.Size(25, 25); this.btnJustifyRight.Text = "Justify right"; // // btnJustifyCenter // this.btnJustifyCenter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnJustifyCenter.Image = global::VersionOne.VisualStudio.VSPackage.Resources.JustifyCenter; this.btnJustifyCenter.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnJustifyCenter.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnJustifyCenter.Name = "btnJustifyCenter"; this.btnJustifyCenter.Size = new System.Drawing.Size(25, 25); this.btnJustifyCenter.Text = "Justify center"; // // btnJustifyFull // this.btnJustifyFull.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnJustifyFull.Image = global::VersionOne.VisualStudio.VSPackage.Resources.JustifyFull; this.btnJustifyFull.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnJustifyFull.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnJustifyFull.Name = "btnJustifyFull"; this.btnJustifyFull.Size = new System.Drawing.Size(25, 25); this.btnJustifyFull.Text = "Justify full"; // // btnBulletedList // this.btnBulletedList.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnBulletedList.Image = global::VersionOne.VisualStudio.VSPackage.Resources.BulletedList; this.btnBulletedList.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnBulletedList.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnBulletedList.Name = "btnBulletedList"; this.btnBulletedList.Size = new System.Drawing.Size(25, 25); this.btnBulletedList.Text = "Bulleted list"; // // btnNumberedList // this.btnNumberedList.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNumberedList.Image = global::VersionOne.VisualStudio.VSPackage.Resources.NumberedList; this.btnNumberedList.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnNumberedList.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNumberedList.Name = "btnNumberedList"; this.btnNumberedList.Size = new System.Drawing.Size(25, 25); this.btnNumberedList.Text = "Numbered list"; // // btnIncreaseIndent // this.btnIncreaseIndent.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnIncreaseIndent.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Indent; this.btnIncreaseIndent.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnIncreaseIndent.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnIncreaseIndent.Name = "btnIncreaseIndent"; this.btnIncreaseIndent.Size = new System.Drawing.Size(25, 25); this.btnIncreaseIndent.Text = "Increase indent"; // // btnDecreaseIndent // this.btnDecreaseIndent.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnDecreaseIndent.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Outdent; this.btnDecreaseIndent.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnDecreaseIndent.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnDecreaseIndent.Name = "btnDecreaseIndent"; this.btnDecreaseIndent.Size = new System.Drawing.Size(25, 25); this.btnDecreaseIndent.Text = "Decrease indent"; // // btnUndo // this.btnUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnUndo.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Undo; this.btnUndo.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnUndo.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnUndo.Name = "btnUndo"; this.btnUndo.Size = new System.Drawing.Size(25, 25); this.btnUndo.Text = "Undo"; // // btnRedo // this.btnRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnRedo.Image = global::VersionOne.VisualStudio.VSPackage.Resources.Redo; this.btnRedo.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.btnRedo.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnRedo.Name = "btnRedo"; this.btnRedo.Size = new System.Drawing.Size(25, 25); this.btnRedo.Text = "Redo"; // // RichTextEditorControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Controls.Add(this.tsToolMenu); this.Controls.Add(this.ctlHtmlEditor); this.Name = "RichTextEditorControl"; this.Size = new System.Drawing.Size(459, 175); this.tsToolMenu.ResumeLayout(false); this.tsToolMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private onlyconnect.HtmlEditor ctlHtmlEditor; private System.Windows.Forms.ToolStrip tsToolMenu; private System.Windows.Forms.ToolStripButton btnBold; private System.Windows.Forms.ToolStripButton btnItalic; private System.Windows.Forms.ToolStripButton btnUnderline; private System.Windows.Forms.ToolStripButton btnRemoveFormat; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton btnBulletedList; private System.Windows.Forms.ToolStripButton btnStrikethrough; private System.Windows.Forms.ToolStripButton btnNumberedList; private System.Windows.Forms.ToolStripButton btnIncreaseIndent; private System.Windows.Forms.ToolStripButton btnDecreaseIndent; private System.Windows.Forms.ToolStripButton btnJustifyCenter; private System.Windows.Forms.ToolStripButton btnJustifyLeft; private System.Windows.Forms.ToolStripButton btnJustifyRight; private System.Windows.Forms.ToolStripButton btnJustifyFull; private System.Windows.Forms.ToolStripButton btnUndo; private System.Windows.Forms.ToolStripButton btnRedo; } }
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System; using System.Globalization; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// This is the partial part of the class MsfsshttpbAdapterCapture for MS-FSSHTTPB knowledge part. /// </summary> public partial class MsfsshttpbAdapterCapture { /// <summary> /// This method is used to verify knowledge related requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyKnowledge(Knowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type Knowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R359, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 359, @"[In Knowledge] Knowledge Start (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1) that specifies a Knowledge (section 2.2.1.13) start."); // Directly capture requirement MS-FSSHTTPB_R360, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 360, @"[In Knowledge] Specialized Knowledge (variable): Zero or more Specialized Knowledge structures (section 2.2.1.13.1)."); // Verify the stream object header end related requirements. this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); // Directly capture requirement MS-FSSHTTPB_R361, if stream object end type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderEnd8bit), instance.StreamObjectHeaderEnd.GetType(), "MS-FSSHTTPB", 361, @"[In Knowledge] Knowledge End (1 byte): An 8-bit Stream Object Header (section 2.2.1.5.3) that specifies a Knowledge end."); } /// <summary> /// This method is used to test Specialized Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifySpecializedKnowledge(SpecializedKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Specialized Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type SpecializedKnowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R362, if stream object start type is StreamObjectHeaderStart32bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart32bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 362, @"[In Specialized Knowledge] Specialized Knowledge Start (4 bytes): A 32-bit Stream Object Header (section 2.2.1.5.2) that specifies A Specialized Knowledge start."); // Directly capture requirement MS-FSSHTTPB_R363, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 363, @"[In Specialized Knowledge] GUID (16 bytes): A GUID that specifies the type of Specialized Knowledge."); bool isVerifyR364 = instance.GUID == SpecializedKnowledge.CellKnowledgeGuid || instance.GUID == SpecializedKnowledge.ContentTagKnowledgeGuid || instance.GUID == SpecializedKnowledge.WaterlineKnowledgeGuid || instance.GUID == SpecializedKnowledge.FragmentKnowledgeGuid; site.Log.Add( LogEntryKind.Debug, "Actual GUID value {0}, expect the value either 327A35F6-0761-4414-9686-51E900667A4D, 3A76E90E-8032-4D0C-B9DD-F3C65029433E, 0ABE4F35-01DF-4134-A24A-7C79F0859844 or 10091F13-C882-40FB-9886-6533F934C21D or ,BF12E2C1-E64F-4959-8282-73B9A24A7C44 for MS-FSSHTTPB_R364.", instance.GUID.ToString()); // Capture requirement MS-FSSHTTPB_R364, if the GUID equals the mentioned four values {327A35F6-0761-4414-9686-51E900667A4D}, {3A76E90E-8032-4D0C-B9DD-F3C65029433E}, {0ABE4F35-01DF-4134-A24A-7C79F0859844}, {10091F13-C882-40FB-9886-6533F934C21D}. site.CaptureRequirementIfIsTrue( isVerifyR364, "MS-FSSHTTPB", 364, @"[In Specialized Knowledge] The following GUIDs detail the type of Knowledge contained: [Its value must be one of] {327A35F6-0761-4414-9686-51E900667A4D}, {3A76E90E-8032-4D0C-B9DD-F3C65029433E}, {0ABE4F35-01DF-4134-A24A-7C79F0859844}, {10091F13-C882-40FB-9886-6533F934C21D},{BF12E2C1-E64F-4959-8282-73B9A24A7C44}]."); switch (instance.GUID.ToString("D").ToUpper(CultureInfo.CurrentCulture)) { case "327A35F6-0761-4414-9686-51E900667A4D": // Capture requirement MS-FSSHTTPB_R365, if the knowledge data type is CellKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(CellKnowledge), instance.SpecializedKnowledgeData.GetType(), "MS-FSSHTTPB", 365, @"[In Specialized Knowledge][If the GUID field is set to ] {327A35F6-0761-4414-9686-51E900667A4D}, [it indicates the type of the Specialized Knowledge is]Cell Knowledge (section 2.2.1.13.2)."); break; case "3A76E90E-8032-4D0C-B9DD-F3C65029433E": // Capture requirement MS-FSSHTTPB_R366, if the knowledge data type is WaterlineKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(WaterlineKnowledge), instance.SpecializedKnowledgeData.GetType(), "MS-FSSHTTPB", 366, @"[In Specialized Knowledge][If the GUID field is set to ] {3A76E90E-8032-4D0C-B9DD-F3C65029433E}, [it indicates the type of the specialized knowledge is]Waterline Knowledge (section 2.2.1.13.4)."); break; case "0ABE4F35-01DF-4134-A24A-7C79F0859844": // Capture requirement MS-FSSHTTPB_R367, if the knowledge data type is FragmentKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(FragmentKnowledge), instance.SpecializedKnowledgeData.GetType(), "MS-FSSHTTPB", 367, @"[In Specialized Knowledge][If the GUID field is set to ] {0ABE4F35-01DF-4134-A24A-7C79F0859844}, [it indicates the type of the specialized knowledge is]Fragment Knowledge (section 2.2.1.13.3)."); break; case "10091F13-C882-40FB-9886-6533F934C21D": // Capture requirement MS-FSSHTTPB_R368, if the knowledge data type is ContentTagKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(ContentTagKnowledge), instance.SpecializedKnowledgeData.GetType(), "MS-FSSHTTPB", 368, @"[In Specialized Knowledge][If the GUID field is set to ] {10091F13-C882-40FB-9886-6533F934C21D}, [it indicates the type of the specialized knowledge is]Content Tag Knowledge (section 2.2.1.13.5)."); break; case "BF12E2C1-E64F-4959-8282-73B9A24A7C44": // Capture requirement MS-FSSHTTPB_R1212, if the knowledge data type is VersionTokenKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(VersionTokenKnowledge), instance.SpecializedKnowledgeData.GetType(), "MS-FSSHTTPB", 1212, @"[In Specialized Knowledge][If the GUID field is set to ] {BF12E2C1-E64F-4959-8282-73B9A24A7C44}, [it indicates the type of the specialized knowledge is]Version Token Knowledge (section 2.2.1.13.6)."); break; default: site.Assert.Fail("Unsupported specialized knowledge value " + instance.GUID.ToString()); break; } // Directly capture requirement MS-FSSHTTPB_R369, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 369, @"[In Specialized Knowledge] Specialized Knowledge Data (variable): The data for the specific Knowledge type."); // Verify the stream object header end related requirements. this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); // Capture requirement MS-FSSHTTPB_R370, if the stream object end type is StreamObjectHeaderEnd16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderEnd16bit), instance.StreamObjectHeaderEnd.GetType(), "MS-FSSHTTPB", 370, @"[In Specialized Knowledge] Specialized Knowledge End (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.4) that specifies Specialized Knowledge end."); } /// <summary> /// This method is used to test Cell Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyCellKnowledge(CellKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Cell Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type CellKnowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R372, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 372, @"[In Cell Knowledge] Cell Knowledge Start (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1) that specifies a Cell Knowledge start."); if (instance.CellKnowledgeEntryList != null && instance.CellKnowledgeEntryList.Count != 0) { // Directly capture requirement MS-FSSHTTPB_R373, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 373, @"[In Cell Knowledge] Cell Knowledge Data (variable): An array of Knowledge Entry (section 2.2.1.13.2.2) that specifies one data element Knowledge reference."); } else if (instance.CellKnowledgeRangeList != null && instance.CellKnowledgeRangeList.Count != 0) { // Directly capture requirement MS-FSSHTTPB_R3731, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 3731, @"[In Cell Knowledge] Cell Knowledge Data (variable): An array of Knowledge Range (section 2.2.1.13.2.1) that specifies one or more data element Knowledge references."); } else { site.Log.Add(LogEntryKind.Debug, "The CellKnowledgeEntryList and CellKnowledgeRangeList are same null or empty list in the same time."); } // Verify the stream object header end related requirements. this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); // Capture requirement MS-FSSHTTPB_R374, if the stream object end header is StreamObjectHeaderEnd8bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderEnd8bit), instance.StreamObjectHeaderEnd.GetType(), "MS-FSSHTTPB", 374, @"[In Cell Knowledge] Cell Knowledge End (1 byte): An 8-bit Stream Object Header (section 2.2.1.5.3) that specifies the Cell Knowledge end."); } /// <summary> /// This method is used to test Cell Knowledge Range related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyCellKnowledgeRange(CellKnowledgeRange instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Cell Knowledge Range related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type CellKnowledgeRange is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R376, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 376, @"[In Cell Knowledge Range] Cell Knowledge Range (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1) that specifies the start of a Cell Knowledge Range."); // Directly capture requirement MS-FSSHTTPB_R377, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 377, @"[In Cell Knowledge Range] GUID (16 bytes): A GUID that specifies the data element."); // Directly capture requirement MS-FSSHTTPB_R378, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 378, @"[In Cell Knowledge Range] From (variable): A compact unsigned 64-bit integer section 2.2.1.1() that specifies the starting Sequence Number."); // Directly capture requirement MS-FSSHTTPB_R558, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 558, @"[In Cell Knowledge Range] To (variable): A compact unsigned 64-bit integer that specifies the ending sequence number."); // Verify the stream object header end related requirements. this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Cell Knowledge Entry related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyCellKnowledgeEntry(CellKnowledgeEntry instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Cell Knowledge Entry related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type CellKnowledgeEntry is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R560, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 560, @"[In Cell Knowledge Entry] Cell Knowledge Entry (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1), that specifies a Cell Knowledge Entry."); // Directly capture requirement MS-FSSHTTPB_R561, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 561, @"[In Cell Knowledge Entry] Serial Number (variable): A Serial Number (section 2.2.1.9) that specifies the cell."); // Verify the stream object header end related requirements. this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Fragment Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyFragmentKnowledge(FragmentKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Fragment Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type FragmentKnowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R563, if stream object start type is StreamObjectHeaderStart32bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart32bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 563, @"[In Fragment Knowledge] Fragment Knowledge Start (4 bytes): A 32-bit Stream Object Header (section 2.2.1.5.2) that specifies a Fragment Knowledge start."); // Directly capture requirement MS-FSSHTTPB_R564, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 564, @"[In Fragment Knowledge] Fragment Knowledge Entries (variable): An optional array of Fragment Knowledge Entry (section 2.2.1.13.3.1) structures specifying the fragments which have been uploaded."); // Directly capture requirement MS-FSSHTTPB_R565, if the stream object end is StreamObjectHeaderEnd16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderEnd16bit), instance.StreamObjectHeaderEnd.GetType(), "MS-FSSHTTPB", 565, @"[In Fragment Knowledge] Fragment Knowledge End (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.4) that specifies a Fragment Knowledge end."); // Verify the stream object header end related requirements. this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); } /// <summary> /// This method is used to test Fragment Knowledge Entry related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyFragmentKnowledgeEntry(FragmentKnowledgeEntry instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Fragment Knowledge Entry related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type FragmentKnowledgeEntry is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R566, if stream object start type is StreamObjectHeaderStart32bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart32bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 566, @"[In Fragment Knowledge Entry] Fragment Descriptor (4 bytes): A 32-bit Stream Object Header (section 2.2.1.5.2) that specifies a Fragment Knowledge Entry."); // Directly capture requirement MS-FSSHTTPB_R567, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 567, @"[In Fragment Knowledge Entry] Extended GUID (variable): An Extended GUID (section 2.2.1.7) that specifies the data element this Fragment Knowledge Entry contains knowledge about."); // Directly capture requirement MS-FSSHTTPB_R568, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 568, @"[In Fragment Knowledge Entry] Data Element Size (variable): A compact unsigned 64-bit integer (section 2.2.1.1) specifying the size in bytes of the data element specified by the preceding Extended GUID."); // Directly capture requirement MS-FSSHTTPB_R569, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 569, @"[In Fragment Knowledge Entry] Data Element Chunk Reference (variable): A file chunk reference (section 2.2.1.2) specifying which part of the data element with the preceding GUID this Fragment Knowledge Entry contains knowledge about."); // Verify the stream object header end related requirements. this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Waterline Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyWaterlineKnowledge(WaterlineKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Waterline Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type WaterlineKnowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R572, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 572, @"[In Waterline Knowledge] Waterline Knowledge Start (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1) that specifies a Waterline Knowledge start."); // Directly capture requirement MS-FSSHTTPB_R573, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 573, @"[In Waterline Knowledge] Waterline Knowledge Data (variable): One or more Waterline Knowledge Entries (section 2.2.1.13.4.1) that specify what the server has already delivered to the client or what the client has already received from the server."); // Directly capture requirement MS-FSSHTTPB_R574, if the stream object end type is StreamObjectHeaderEnd8bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderEnd8bit), instance.StreamObjectHeaderEnd.GetType(), "MS-FSSHTTPB", 574, @"[In Waterline Knowledge] Waterline Knowledge End (1 byte): An 8-bit Stream Object Header (section 2.2.1.5.3) that specifies the Waterline Knowledge end."); // Verify the stream object header end related requirements. this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Waterline Knowledge Entry related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyWaterlineKnowledgeEntry(WaterlineKnowledgeEntry instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Waterline Knowledge Entry related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type WaterlineKnowledgeEntry is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R575, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 575, @"[In Waterline Knowledge Entry] Waterline Knowledge Entry (2 bytes): A 16-bit Stream Object Header (section 2.2.1.5.1) that specifies a Waterline Knowledge Entry."); // Directly capture requirement MS-FSSHTTPB_R576, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 576, @"[In Waterline Knowledge Entry] Cell Storage Extended GUID (variable): An Extended GUID (section 2.2.1.7) that specifies the cell storage this entry specifies the waterline for."); // Directly capture requirement MS-FSSHTTPB_R577, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 577, @"[In Waterline Knowledge Entry] Waterline (variable): A compact unsigned 64-bit integer (section 2.2.1.1) that specifies a sequential Serial Number (section 2.2.1.9)."); // Directly capture requirement MS-FSSHTTPB_R379, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 379, @"[In Waterline Knowledge Entry] Reserved (variable): A compact unsigned 64-bit integer that specifies a reserved field that MUST have value of zero."); // Verify the stream object header end related requirements. this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Content Tag Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyContentTagKnowledge(ContentTagKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Content Tag Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type ContentTagKnowledge is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); // Capture requirement MS-FSSHTTPB_R381, if stream object start type is StreamObjectHeaderStart16bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart16bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 381, @"[In Content Tag Knowledge] Content Tag Start (2 bytes): A 16-bit Stream Object Header that specifies the Content Tag Knowledge start."); // Directly capture requirement MS-FSSHTTPB_R382, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 382, @"[In Content Tag Knowledge] Content Tag Entry Array (variable): An array of Content Tag Knowledge Entry structures (section 2.2.1.13.5.1), each of which specifies changes for a BLOB."); // Directly capture requirement MS-FSSHTTPB_R383, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 383, @"[In Content Tag Knowledge] Content Tag Knowledge End (1 byte): An 8-bit Stream Object Header (section 2.2.1.5.3) that specifies the Content Tag Knowledge end."); // Verify the stream object header end related requirements. this.ExpectStreamObjectHeaderEnd(instance.StreamObjectHeaderEnd, instance.GetType(), site); this.ExpectCompoundObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Content Tag Knowledge Entry related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyContentTagKnowledgeEntry(ContentTagKnowledgeEntry instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Content Tag Knowledge Entry related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type ContentTagKnowledgeEntry is null due to parsing error or type casting error."); } // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); if(instance.StreamObjectHeaderStart.GetType() == typeof(StreamObjectHeaderStart16bit) || instance.StreamObjectHeaderStart.GetType() == typeof(StreamObjectHeaderStart32bit)) { // Capture requirement MS-FSSHTTPB_R385, if stream object start type is StreamObjectHeaderStart16bit or StreamObjectHeaderStart32bit. site.CaptureRequirement( "MS-FSSHTTPB", 385, @"[In Content Tag Knowledge Entry] Content Tag Knowledge Entry Start (variable): A 16-bit or 32-bit Stream Object Header (section 2.2.1.5.1) that specifies the start of a Content Tag Knowledge Entry."); } // Directly capture requirement MS-FSSHTTPB_R386, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 386, @"[In Content Tag Knowledge Entry] BLOB Heap Extended GUID (variable): An Extended GUID (section 2.2.1.7) that specifies the BLOB this content tag is for."); // Directly capture requirement MS-FSSHTTPB_R387, if there are no parsing errors. site.CaptureRequirement( "MS-FSSHTTPB", 387, @"[In Content Tag Knowledge Entry] Clock Data (variable): A binary item (section 2.2.1.3) that specifies changes for a BLOB on the server."); // Verify the stream object header end related requirements. this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } /// <summary> /// This method is used to test Version Token Knowledge related adapter requirements. /// </summary> /// <param name="instance">Specify the instance which need to be verified.</param> /// <param name="site">Specify the ITestSite instance.</param> public void VerifyVersionTokenKnowledge(VersionTokenKnowledge instance, ITestSite site) { // If the instance is not null and there are no parsing errors, then the Version Token Knowledge related adapter requirements can be directly captured. if (null == instance) { site.Assert.Fail("The instance of type VersionTokenKnowledge is null due to parsing error or type casting error."); } // Verify MS-FSSHTTPB requirement: MS-FSSHTTPB_R1345 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 1345, site)) { // Capture requirement MS-FSSHTTPB_R1345, if instance type is VersionTokenKnowledge. site.CaptureRequirementIfAreEqual<Type>( typeof(VersionTokenKnowledge), instance.GetType(), "MS-FSSHTTPB", 1345, @"[In Appendix A: Product Behavior]Implementation does support the Version Token Knowledge(SharePoint Server 2016 and above follow this behavior.)"); // Capture requirement MS-FSSHTTPB_R1214, if stream object start type is StreamObjectHeaderStart32bit. site.CaptureRequirementIfAreEqual<Type>( typeof(StreamObjectHeaderStart32bit), instance.StreamObjectHeaderStart.GetType(), "MS-FSSHTTPB", 1214, @"[In Version Token Knowledge]Version Token Knowledge (4 bytes): A 32-bit Stream Object Header (section 2.2.1.5.2) that specifies a Version Token Knowledge."); // Capture requirement MS-FSSHTTPB_R1215, if TokenData type is BinaryItem. site.CaptureRequirementIfAreEqual<Type>( typeof(BinaryItem), instance.TokenData.GetType(), "MS-FSSHTTPB", 1215, @"[In Version Token Knowledge]Token Data (variable): A byte stream that specifies the version token opaque to this protocol."); // Verify the stream object header related requirements. this.ExpectStreamObjectHeaderStart(instance.StreamObjectHeaderStart, instance.GetType(), site); this.ExpectSingleObject(instance.StreamObjectHeaderStart, site); } } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; #if BIT64 using nint = System.Int64; #else using nint = System.Int32; #endif namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct IntPtr : IEquatable<IntPtr>, ISerializable { // WARNING: We allow diagnostic tools to directly inspect this member (_value). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. private readonly unsafe void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly IntPtr Zero; [Intrinsic] [NonVersionable] public unsafe IntPtr(int value) { _value = (void*)value; } [Intrinsic] [NonVersionable] public unsafe IntPtr(long value) { #if BIT64 _value = (void*)value; #else _value = (void*)checked((int)value); #endif } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public unsafe IntPtr(void* value) { _value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long l = info.GetInt64("value"); if (Size == 4 && (l > int.MaxValue || l < int.MinValue)) throw new ArgumentException(SR.Serialization_InvalidPtrValue); _value = (void*)l; } unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); info.AddValue("value", ToInt64()); } public unsafe override bool Equals(object obj) { if (obj is IntPtr) { return (_value == ((IntPtr)obj)._value); } return false; } unsafe bool IEquatable<IntPtr>.Equals(IntPtr other) { return _value == other._value; } public unsafe override int GetHashCode() { #if BIT64 long l = (long)_value; return (unchecked((int)l) ^ (int)(l >> 32)); #else return unchecked((int)_value); #endif } [Intrinsic] [NonVersionable] public unsafe int ToInt32() { #if BIT64 long l = (long)_value; return checked((int)l); #else return (int)_value; #endif } [Intrinsic] [NonVersionable] public unsafe long ToInt64() { return (nint)_value; } [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(int value) { return new IntPtr(value); } [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(long value) { return new IntPtr(value); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static unsafe explicit operator IntPtr(void* value) { return new IntPtr(value); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static unsafe explicit operator void* (IntPtr value) { return value._value; } [Intrinsic] [NonVersionable] public static unsafe explicit operator int(IntPtr value) { #if BIT64 long l = (long)value._value; return checked((int)l); #else return (int)value._value; #endif } [Intrinsic] [NonVersionable] public static unsafe explicit operator long(IntPtr value) { return (nint)value._value; } [Intrinsic] [NonVersionable] public static unsafe bool operator ==(IntPtr value1, IntPtr value2) { return value1._value == value2._value; } [Intrinsic] [NonVersionable] public static unsafe bool operator !=(IntPtr value1, IntPtr value2) { return value1._value != value2._value; } [NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [Intrinsic] [NonVersionable] public static unsafe IntPtr operator +(IntPtr pointer, int offset) { return new IntPtr((nint)pointer._value + offset); } [NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [Intrinsic] [NonVersionable] public static unsafe IntPtr operator -(IntPtr pointer, int offset) { return new IntPtr((nint)pointer._value - offset); } public static int Size { [Intrinsic] [NonVersionable] get { return sizeof(nint); } } [CLSCompliant(false)] [Intrinsic] [NonVersionable] #if PROJECTN [System.Runtime.CompilerServices.DependencyReductionRootAttribute] #endif public unsafe void* ToPointer() { return _value; } public unsafe override string ToString() { return ((nint)_value).ToString(CultureInfo.InvariantCulture); } public unsafe string ToString(string format) { return ((nint)_value).ToString(format, CultureInfo.InvariantCulture); } } }
// Copyright 2020 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 DebuggerApi; using NUnit.Framework; using NSubstitute; using Microsoft.VisualStudio; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.Debugger.Interop; using YetiVSI.DebugEngine; using Microsoft.VisualStudio.Threading; using DebuggerGrpcClient.Interfaces; using YetiVSI.DebugEngine.Interfaces; namespace YetiVSI.Test.DebugEngine { [TestFixture] class DebugPendingBreakpoint_DeletedTests { IPendingBreakpoint pendingBreakpoint; [SetUp] public void SetUp() { var taskContext = new JoinableTaskContext(); IDebugBreakpointRequest2 mockBreakpointRequest = Substitute.For<IDebugBreakpointRequest2>(); mockBreakpointRequest.GetRequestInfo(Arg.Any<enum_BPREQI_FIELDS>(), Arg.Any<BP_REQUEST_INFO[]>()).Returns(x => { return VSConstants.S_OK; }); pendingBreakpoint = new DebugPendingBreakpoint.Factory(taskContext, null, null, null) .Create(null, null, mockBreakpointRequest, null); pendingBreakpoint.Delete(); } [Test] public void Bind() { Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.Bind()); } [Test] public void CanBind() { IEnumDebugErrorBreakpoints2 ppErrorEnum; Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.CanBind(out ppErrorEnum)); Assert.IsNull(ppErrorEnum); } [Test] public void Delete() { Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.Delete()); } [Test] public void Enable() { Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.Enable(1)); } [Test] public void EnumBoundBreakpoints() { IEnumDebugBoundBreakpoints2 boundBreakpointsEnum; Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.EnumBoundBreakpoints( out boundBreakpointsEnum)); Assert.IsNull(boundBreakpointsEnum); } [Test] public void EnumErrorBreakpoints() { IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.EnumErrorBreakpoints( enum_BP_ERROR_TYPE.BPET_ALL, out errorBreakpointsEnum)); Assert.IsNull(errorBreakpointsEnum); } [Test] public void GetBreakpointRequest() { IDebugBreakpointRequest2 breakpointRequest; Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.GetBreakpointRequest( out breakpointRequest)); Assert.IsNull(breakpointRequest); } [Test] public void SetPassCount() { Assert.AreEqual(AD7Constants.E_BP_DELETED, pendingBreakpoint.SetPassCount( new BP_PASSCOUNT())); } } [TestFixture] class DebugPendingBreakpointTests { const int INVALID_ID = -1; const int EXPECTED_ID = 1; const int BOUND_BREAKPOINT_ID = 0; const string TEST_FUNCTION_NAME = "testFunctionName"; const string TEST_FUNCTION_NAME_WITH_OFFSET = " { testFunctionName , , } + 10 "; const string TEST_FUNCTION_NAME_WITHOUT_OFFSET = "{testFunctionName,,}"; const string TEST_FILE_NAME = "testFileName"; uint COLUMN_NUMBER = 1; uint LINE_NUMBER = 2; ulong TEST_ADDRESS = 0xdeadbeef; string STR_TEST_ADDRESS = "0xdeadbeef"; DebugPendingBreakpoint.Factory debugPendingBreakpointFactory; DebugBoundBreakpoint.Factory mockBoundBreakpointFactory; IPendingBreakpoint pendingBreakpoint; IBreakpointManager mockBreakpointManager; IDebugBreakpointRequest2 mockBreakpointRequest; RemoteTarget mockTarget; IGgpDebugProgram mockProgram; Marshal mockMarshal; RemoteBreakpoint mockLldbBreakpoint; BP_REQUEST_INFO requestInfo; [SetUp] public void SetUp() { var taskContext = new JoinableTaskContext(); mockBreakpointManager = Substitute.For<IBreakpointManager>(); mockBreakpointRequest = Substitute.For<IDebugBreakpointRequest2>(); mockTarget = Substitute.For<RemoteTarget>(); mockProgram = Substitute.For<IGgpDebugProgram>(); mockMarshal = Substitute.For<Marshal>(); mockLldbBreakpoint = Substitute.For<RemoteBreakpoint>(); requestInfo = new BP_REQUEST_INFO(); mockBreakpointRequest.GetRequestInfo(Arg.Any<enum_BPREQI_FIELDS>(), Arg.Any<BP_REQUEST_INFO[]>()).Returns(x => { enum_BPREQI_FIELDS fields = (enum_BPREQI_FIELDS)x[0]; BP_REQUEST_INFO[] breakpointRequestInfo = (BP_REQUEST_INFO[])x[1]; if (breakpointRequestInfo == null || breakpointRequestInfo.Length == 0) { return 1; } return BuildBreakpointRequestInfo(fields, out breakpointRequestInfo[0]); }); mockLldbBreakpoint.GetId().Returns(EXPECTED_ID); SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE); mockBoundBreakpointFactory = Substitute.For<DebugBoundBreakpoint.Factory>(); debugPendingBreakpointFactory = new DebugPendingBreakpoint.Factory(taskContext, mockBoundBreakpointFactory, new BreakpointErrorEnumFactory(), new BoundBreakpointEnumFactory()); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); } [Test] public void BindUnsupportedType() { // Set a unsupported breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_NONE); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindLineBreakpoint() { MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindInvalidFile() { MockDocumentPosition(null, LINE_NUMBER, COLUMN_NUMBER); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindFunctionBreakpoint() { // Set a function breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(1); MockFunctionPosition(TEST_FUNCTION_NAME); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindFunctionBreakpointWithOffset() { SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(1); MockFunctionPosition(TEST_FUNCTION_NAME_WITH_OFFSET); uint offset = 10; mockTarget.CreateFunctionOffsetBreakpoint(TEST_FUNCTION_NAME, offset).Returns( new BreakpointErrorPair(mockLldbBreakpoint, BreakpointError.Success)); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindInvalidFunctionBreakpointWithOffset() { SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(1); MockFunctionPosition(TEST_FUNCTION_NAME_WITH_OFFSET); // OffsetBreakpoint returns null when it fails //mockLldbBreakpoint.OffsetBreakpoint(offset).Returns((RemoteBreakpoint)null); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(0, boundBreakpoints.Count); mockBreakpointManager.DidNotReceive().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindFunctionBreakpointWithoutOffset() { SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(1); MockFunctionPosition(TEST_FUNCTION_NAME_WITHOUT_OFFSET); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); mockTarget.Received().BreakpointCreateByName(TEST_FUNCTION_NAME); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); mockTarget.DidNotReceive().BreakpointDelete(Arg.Any<int>()); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindInvalidFunction() { // Set a function breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(1); MockFunctionPosition(null); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindAssemblyBreakpoint() { // Set code context breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_CONTEXT); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockAssemblyBreakpoint(1); MockCodeContext(TEST_ADDRESS); var result = pendingBreakpoint.Bind(); mockTarget.Received(1).BreakpointCreateByAddress(TEST_ADDRESS); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindCodeAddressBreakpoint() { // Set code address breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_ADDRESS); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockAssemblyBreakpoint(1); MockCodeAddress(STR_TEST_ADDRESS); var result = pendingBreakpoint.Bind(); mockTarget.Received(1).BreakpointCreateByAddress(TEST_ADDRESS); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindBreakpointFailed() { mockTarget.BreakpointCreateByLocation(TEST_FILE_NAME, LINE_NUMBER).Returns( (RemoteBreakpoint)null); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindNoLocations() { MockBreakpoint(0); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindInvalidLocation() { List<SbBreakpointLocation> invalidBreakpointLocations = new List<SbBreakpointLocation> { null }; MockBreakpoint(invalidBreakpointLocations); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreNotEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindNoSourceLine() { var mockDocumentPosition = Substitute.For<IDebugDocumentPosition2>(); string value; mockDocumentPosition.GetFileName(out value).Returns(x => { x[0] = TEST_FILE_NAME; return 0; }); mockDocumentPosition.GetRange(Arg.Any<TEXT_POSITION[]>(), null).Returns( VSConstants.E_FAIL); mockMarshal.GetDocumentPositionFromIntPtr(Arg.Any<IntPtr>()).Returns( mockDocumentPosition); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); Assert.That(GetBreakpointErrorMessage(breakpointError), Does.Contain("line number")); mockBreakpointManager.Received().ReportBreakpointError( Arg.Any<DebugBreakpointError>()); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void BindCondition() { // Set a condition on the request, and create a new pending breakpoint. var testCondition = "testCondition"; SetCondition(enum_BP_COND_STYLE.BP_COND_WHEN_TRUE, testCondition); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); List<SbBreakpointLocation> mockBreakpointLocations = CreateMockBreakpointLocations(1); MockBreakpoint(mockBreakpointLocations); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var mockBoundBreakpoint = Substitute.For<IBoundBreakpoint>(); mockBoundBreakpointFactory.Create(pendingBreakpoint, mockBreakpointLocations[0], mockProgram, Guid.Empty).Returns(mockBoundBreakpoint); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); Assert.AreSame(mockBoundBreakpoint, boundBreakpoints[0]); mockBoundBreakpoint.Received().SetCondition(requestInfo.bpCondition); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindPassCount() { // Set a pass count on the request, and create a new pending breakpoint. const uint PASS_COUNT = 3u; SetPassCount(enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL, PASS_COUNT); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); List<SbBreakpointLocation> mockBreakpointLocations = CreateMockBreakpointLocations(1); MockBreakpoint(mockBreakpointLocations); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var mockBoundBreakpoint = Substitute.For<IBoundBreakpoint>(); mockBoundBreakpointFactory.Create(pendingBreakpoint, mockBreakpointLocations[0], mockProgram, Guid.Empty).Returns(mockBoundBreakpoint); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); Assert.AreSame(mockBoundBreakpoint, boundBreakpoints[0]); mockBoundBreakpoint.Received().SetPassCount(requestInfo.bpPassCount); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindDisabled() { var mockBreakpointLocations = CreateMockBreakpointLocations(1); MockBreakpoint(mockBreakpointLocations); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var mockBoundBreakpoint = Substitute.For<IBoundBreakpoint>(); mockBoundBreakpointFactory.Create(pendingBreakpoint, mockBreakpointLocations[0], mockProgram, Guid.Empty).Returns(mockBoundBreakpoint); pendingBreakpoint.Enable(0); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); Assert.AreSame(mockBoundBreakpoint, boundBreakpoints[0]); mockBoundBreakpoint.Received().Enable(0); mockBreakpointManager.Received().RegisterPendingBreakpoint(pendingBreakpoint); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void CanBindDeleted() { pendingBreakpoint.Delete(); IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; var result = pendingBreakpoint.CanBind(out errorBreakpointsEnum); Assert.AreEqual(null, errorBreakpointsEnum); Assert.AreEqual(AD7Constants.E_BP_DELETED, result); } [Test] public void CanBindLineBreakpoint() { IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; var result = pendingBreakpoint.CanBind(out errorBreakpointsEnum); Assert.AreEqual(null, errorBreakpointsEnum); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void CanBindFunctionBreakpoint() { // Set a function breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; var result = pendingBreakpoint.CanBind(out errorBreakpointsEnum); Assert.AreEqual(null, errorBreakpointsEnum); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void CanBindUnsupportedType() { // Set a unsupported breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_NONE); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; var result = pendingBreakpoint.CanBind(out errorBreakpointsEnum); Assert.AreNotEqual(null, errorBreakpointsEnum); Assert.AreEqual(VSConstants.S_FALSE, result); } [Test] public void Delete() { var result = pendingBreakpoint.Delete(); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); Assert.AreEqual(enum_PENDING_BP_STATE.PBPS_DELETED, state[0].state); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindAndDelete() { var mockBreakpointLocations = MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); mockLldbBreakpoint.GetId().Returns(EXPECTED_ID); var mockBoundBreakpoint = Substitute.For<IBoundBreakpoint>(); mockBoundBreakpointFactory.Create(pendingBreakpoint, mockBreakpointLocations[0], mockProgram, Guid.Empty).Returns(mockBoundBreakpoint); pendingBreakpoint.Bind(); var result = pendingBreakpoint.Delete(); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); enum_BP_STATE[] bpState = new enum_BP_STATE[1]; mockTarget.Received().BreakpointDelete(EXPECTED_ID); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(0, boundBreakpoints.Count); mockBoundBreakpoint.Received().Delete(); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void Enable() { var result = pendingBreakpoint.Enable(1); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); Assert.AreEqual(enum_PENDING_BP_STATE.PBPS_ENABLED, state[0].state); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void Disable() { var result = pendingBreakpoint.Enable(0); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); Assert.AreEqual(enum_PENDING_BP_STATE.PBPS_DISABLED, state[0].state); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindAndEnable() { var mockBreakpointLocations = MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); var mockBoundBreakpoint = Substitute.For<IBoundBreakpoint>(); mockBoundBreakpointFactory.Create(pendingBreakpoint, mockBreakpointLocations[0], mockProgram, Guid.Empty).Returns(mockBoundBreakpoint); pendingBreakpoint.Bind(); var result = pendingBreakpoint.Enable(1); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); var boundBreakpoints = GetBoundBreakpoints(); Assert.AreEqual(1, boundBreakpoints.Count); Assert.AreSame(mockBoundBreakpoint, boundBreakpoints[0]); mockBoundBreakpoint.Received().Enable(1); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void BindAndDisable() { MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); pendingBreakpoint.Bind(); var result = pendingBreakpoint.Enable(0); PENDING_BP_STATE_INFO[] state = new PENDING_BP_STATE_INFO[1]; pendingBreakpoint.GetState(state); Assert.AreEqual(enum_PENDING_BP_STATE.PBPS_DISABLED, state[0].state); Assert.AreEqual(VSConstants.S_OK, result); } [Test] public void GetId() { int id = pendingBreakpoint.GetId(); Assert.AreEqual(INVALID_ID, id); MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); pendingBreakpoint.Bind(); id = pendingBreakpoint.GetId(); Assert.AreEqual(EXPECTED_ID, id); } [Test] public void GetBoundBreakpointById() { IBoundBreakpoint boundBreakpoint; bool result = pendingBreakpoint.GetBoundBreakpointById( BOUND_BREAKPOINT_ID, out boundBreakpoint); Assert.IsFalse(result); MockBreakpoint(1); MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); pendingBreakpoint.Bind(); result = pendingBreakpoint.GetBoundBreakpointById( BOUND_BREAKPOINT_ID, out boundBreakpoint); Assert.IsTrue(result); Assert.AreEqual(BOUND_BREAKPOINT_ID, boundBreakpoint.GetId()); } [Test] public void GetNumLocations() { int numLocations = 8; // Set a function breakpoint type and create a new pending breakpoint. SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_CODE_FUNC_OFFSET); pendingBreakpoint = debugPendingBreakpointFactory.Create( mockBreakpointManager, mockProgram, mockBreakpointRequest, mockTarget, mockMarshal); MockFunctionBreakpoint(numLocations); MockFunctionPosition(TEST_FUNCTION_NAME); var result = pendingBreakpoint.Bind(); IDebugErrorBreakpoint2 breakpointError = GetBreakpointError(); Assert.AreEqual(null, breakpointError); Assert.AreEqual(VSConstants.S_OK, result); Assert.AreEqual(numLocations, pendingBreakpoint.GetNumLocations()); } [Test] public void GetNumLocationsNoBreakpoint() { Assert.AreEqual(0, pendingBreakpoint.GetNumLocations()); } [Test] public void UpdateLocationsNewLocationsAdded() { MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); MockBreakpoint(1); pendingBreakpoint.Bind(); MockBreakpoint(3); pendingBreakpoint.UpdateLocations(); mockBreakpointManager.Received(1).EmitBreakpointBoundEvent( pendingBreakpoint, Arg.Is<IEnumerable<IDebugBoundBreakpoint2>>(a => a.Count() == 2), Arg.Any<BoundBreakpointEnumFactory>()); Assert.That(pendingBreakpoint.EnumBoundBreakpoints(out var boundBreakpoints), Is.EqualTo(VSConstants.S_OK)); Assert.That(boundBreakpoints.GetCount(out uint count), Is.EqualTo(VSConstants.S_OK)); Assert.That(count, Is.EqualTo(3)); // Test that locations are not updated and BreakpointBoundEvent is not emitted, // when locations state hasn't changed and UpdateLocations is executed. mockBreakpointManager.ClearReceivedCalls(); pendingBreakpoint.UpdateLocations(); mockBreakpointManager.DidNotReceive().EmitBreakpointBoundEvent( pendingBreakpoint, Arg.Any<IEnumerable<IDebugBoundBreakpoint2>>(), Arg.Any<BoundBreakpointEnumFactory>()); Assert.That(pendingBreakpoint.EnumBoundBreakpoints(out boundBreakpoints), Is.EqualTo(VSConstants.S_OK)); Assert.That(boundBreakpoints.GetCount(out count), Is.EqualTo(VSConstants.S_OK)); Assert.That(count, Is.EqualTo(3)); } [Test] public void UpdateLocationsLocationsRemoved() { MockDocumentPosition(TEST_FILE_NAME, LINE_NUMBER, COLUMN_NUMBER); MockBreakpoint(0); pendingBreakpoint.Bind(); MockBreakpoint(3); pendingBreakpoint.UpdateLocations(); mockBreakpointManager.ClearReceivedCalls(); MockBreakpoint(0); pendingBreakpoint.UpdateLocations(); mockBreakpointManager.DidNotReceiveWithAnyArgs().EmitBreakpointBoundEvent( Arg.Any<IPendingBreakpoint>(), Arg.Any<IEnumerable<IDebugBoundBreakpoint2>>(), Arg.Any<BoundBreakpointEnumFactory>()); mockBreakpointManager.Received(1) .ReportBreakpointError(Arg.Any<DebugBreakpointError>()); Assert.That(pendingBreakpoint.EnumBoundBreakpoints(out var boundBreakpoints), Is.EqualTo(VSConstants.S_OK)); Assert.That(boundBreakpoints.GetCount(out uint count), Is.EqualTo(VSConstants.S_OK)); Assert.That(count, Is.EqualTo(0)); } // Update the mock breakpoint request to return a specific breakpoint type. This must be // called before constructing the pending breakpoint. void SetBreakpointType(enum_BP_LOCATION_TYPE type) { requestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_BPLOCATION; requestInfo.bpLocation.bpLocationType = (uint)type; } // Update the mock breakpoint request to return a condition. This must be called before // constructing the pending breakpoint. void SetCondition(enum_BP_COND_STYLE conditionStyle, string conditionString) { requestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_CONDITION; requestInfo.bpCondition = new BP_CONDITION { styleCondition = conditionStyle, bstrCondition = conditionString, }; } // Update the mock breakpoint request to return a pass count. This must be called before // constructing the pending breakpoint. void SetPassCount(enum_BP_PASSCOUNT_STYLE passCountStyle, uint passCount) { requestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_PASSCOUNT; requestInfo.bpPassCount = new BP_PASSCOUNT { stylePassCount = passCountStyle, dwPassCount = passCount, }; } IDebugErrorBreakpoint2 GetBreakpointError() { IEnumDebugErrorBreakpoints2 errorBreakpointsEnum; pendingBreakpoint.EnumErrorBreakpoints(enum_BP_ERROR_TYPE.BPET_ALL, out errorBreakpointsEnum); uint numErrors; Assert.AreEqual(VSConstants.S_OK, errorBreakpointsEnum.GetCount(out numErrors)); if (numErrors == 0) { return null; } IDebugErrorBreakpoint2[] breakpointErrors = new IDebugErrorBreakpoint2[1]; uint fetchedIndex = 0; errorBreakpointsEnum.Next(1, breakpointErrors, ref fetchedIndex); return breakpointErrors[0]; } string GetBreakpointErrorMessage(IDebugErrorBreakpoint2 breakpointError) { IDebugErrorBreakpointResolution2 errorBreakpointResolution; Assert.NotNull(breakpointError); Assert.AreEqual(VSConstants.S_OK, breakpointError.GetBreakpointResolution(out errorBreakpointResolution), "Unable to verify breakpoint error message. Failed to get breakpoint error " + "resolution."); BP_ERROR_RESOLUTION_INFO[] errorResolutionInfo = new BP_ERROR_RESOLUTION_INFO[1]; Assert.AreEqual(VSConstants.S_OK, errorBreakpointResolution.GetResolutionInfo(enum_BPERESI_FIELDS.BPERESI_MESSAGE, errorResolutionInfo), "Unable to verify breakpoint error message. Failed to get breakpoint error " + "resolution info."); return errorResolutionInfo[0].bstrMessage; } List<IDebugBoundBreakpoint2> GetBoundBreakpoints() { IEnumDebugBoundBreakpoints2 boundBreakpointsEnum; pendingBreakpoint.EnumBoundBreakpoints(out boundBreakpointsEnum); if (boundBreakpointsEnum == null) { return new List<IDebugBoundBreakpoint2>(); } uint numBreakpoints; Assert.AreEqual(VSConstants.S_OK, boundBreakpointsEnum.GetCount(out numBreakpoints)); if (numBreakpoints == 0) { return new List<IDebugBoundBreakpoint2>(); } uint count, actualCount = 0; boundBreakpointsEnum.GetCount(out count); IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[count]; boundBreakpointsEnum.Next(count, boundBreakpoints, ref actualCount); return boundBreakpoints.ToList<IDebugBoundBreakpoint2>(); } // Create default mocks, and return values for the document position. void MockDocumentPosition(string filename, uint lineNumber, uint columnNumber) { var mockDocumentPosition = Substitute.For<IDebugDocumentPosition2>(); string value; mockDocumentPosition.GetFileName(out value).Returns(x => { if (filename != null) { x[0] = filename; return 0; } return 1; }); mockDocumentPosition.GetRange(Arg.Any<TEXT_POSITION[]>(), null).Returns(x => { TEXT_POSITION[] startTextPositions = (TEXT_POSITION[])x[0]; if (startTextPositions != null && startTextPositions.Length >= 1) { TEXT_POSITION startTextPosition = new TEXT_POSITION(); startTextPosition.dwColumn = columnNumber; startTextPosition.dwLine = lineNumber; startTextPositions[0] = startTextPosition; } return 0; }); mockMarshal.GetDocumentPositionFromIntPtr(Arg.Any<IntPtr>()).Returns( mockDocumentPosition); } // Create default mocks, and return values for the function position. void MockFunctionPosition(string functionName) { var mockFunctionPosition = Substitute.For<IDebugFunctionPosition2>(); string value; mockFunctionPosition.GetFunctionName(out value).Returns(x => { if (functionName != null) { x[0] = functionName; return 0; } return 1; }); mockMarshal.GetFunctionPositionFromIntPtr(Arg.Any<IntPtr>()).Returns( mockFunctionPosition); } // Create default mocks, and return values for the code context position. void MockCodeContext(ulong address) { // Create mock code context with the specified address. var mockCodeContext = Substitute.For<IGgpDebugCodeContext>(); mockCodeContext.Address.Returns(address); mockMarshal.GetCodeContextFromIntPtr(Arg.Any<IntPtr>()).Returns( mockCodeContext); } // Create return values for the address position. void MockCodeAddress(string address) { // Code address holds the address as a string mockMarshal.GetStringFromIntPtr(Arg.Any<IntPtr>()).Returns(address); } List<SbBreakpointLocation> CreateMockBreakpointLocations( int numBreakpointLocations) { List<SbBreakpointLocation> breakpointLocations = new List<SbBreakpointLocation>(numBreakpointLocations); for (int i = 0; i < numBreakpointLocations; i++) { var mockBreakpointLocation = Substitute.For<SbBreakpointLocation>(); mockBreakpointLocation.GetId().Returns(i); breakpointLocations.Add(mockBreakpointLocation); } return breakpointLocations; } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations. // numBreakpointLocations specifies how many mock breakpoint locations to return. List<SbBreakpointLocation> MockBreakpoint(int numBreakpointLocations) { List<SbBreakpointLocation> breakpointLocations = CreateMockBreakpointLocations(numBreakpointLocations); MockBreakpoint(breakpointLocations); return breakpointLocations; } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations. // breakpointLocations is a list of mock breakpoint locations that will be returned by the // mock lldb breakpoint. void MockBreakpoint(List<SbBreakpointLocation> breakpointLocations) { for (uint i = 0; i < breakpointLocations.Count; i++) { mockLldbBreakpoint.GetLocationAtIndex(i).Returns(breakpointLocations[(int)i]); } mockLldbBreakpoint.GetNumLocations().Returns((uint)breakpointLocations.Count); mockTarget.BreakpointCreateByLocation(TEST_FILE_NAME, LINE_NUMBER + 1).Returns( mockLldbBreakpoint); } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations // for a function breakpoint. numBreakpointLocations specifies how many mock breakpoint // locations to return. void MockFunctionBreakpoint(int numBreakpointLocations) { List<SbBreakpointLocation> breakpointLocations = CreateMockBreakpointLocations(numBreakpointLocations); MockFunctionBreakpoint(breakpointLocations); } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations // for a function breakpoint. breakpointLocations is a list of mock breakpoint locations // that will be returned by the mock lldb breakpoint. void MockFunctionBreakpoint(List<SbBreakpointLocation> breakpointLocations) { for (uint i = 0; i < breakpointLocations.Count; i++) { mockLldbBreakpoint.GetLocationAtIndex(i).Returns(breakpointLocations[(int)i]); } mockLldbBreakpoint.GetNumLocations().Returns((uint)breakpointLocations.Count); mockTarget.BreakpointCreateByName(TEST_FUNCTION_NAME).Returns(mockLldbBreakpoint); } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations // for an assembly breakpoint. numBreakpointLocations specifies how many mock breakpoint // locations to return. void MockAssemblyBreakpoint(int numBreakpointLocations) { List<SbBreakpointLocation> breakpointLocations = CreateMockBreakpointLocations(numBreakpointLocations); MockAssemblyBreakpoint(breakpointLocations); } // Create default mocks, and return values for the lldb breakpoint and breakpoint locations // for an assembly breakpoint. breakpointLocations is a list of mock breakpoint locations // that will be returned by the mock lldb breakpoint. void MockAssemblyBreakpoint(List<SbBreakpointLocation> breakpointLocations) { for (uint i = 0; i < breakpointLocations.Count; i++) { mockLldbBreakpoint.GetLocationAtIndex(i).Returns(breakpointLocations[(int)i]); } mockLldbBreakpoint.GetNumLocations().Returns((uint)breakpointLocations.Count); mockTarget.BreakpointCreateByAddress(TEST_ADDRESS).Returns(mockLldbBreakpoint); } int BuildBreakpointRequestInfo(enum_BPREQI_FIELDS fields, out BP_REQUEST_INFO breakpointRequestInfo) { breakpointRequestInfo = new BP_REQUEST_INFO(); if ((fields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0 && (requestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_BPLOCATION) != 0) { breakpointRequestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_BPLOCATION; breakpointRequestInfo.bpLocation = requestInfo.bpLocation; } if ((fields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0 && (requestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_CONDITION) != 0) { breakpointRequestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_CONDITION; breakpointRequestInfo.bpCondition = requestInfo.bpCondition; } if ((fields & enum_BPREQI_FIELDS.BPREQI_PASSCOUNT) != 0 && (requestInfo.dwFields & enum_BPREQI_FIELDS.BPREQI_PASSCOUNT) != 0) { breakpointRequestInfo.dwFields |= enum_BPREQI_FIELDS.BPREQI_PASSCOUNT; breakpointRequestInfo.bpPassCount = requestInfo.bpPassCount; } return 0; } } }
using UnityEngine; using System.Collections.Generic; namespace Lean.Touch { // This script allows you to select multiple LeanSelectable components while a finger is down public class LeanPressSelect : MonoBehaviour { public enum SelectType { Raycast3D, Overlap2D } public enum SearchType { GetComponent, GetComponentInParent, GetComponentInChildren } [Tooltip("Ignore fingers with StartedOverGui?")] public bool IgnoreGuiFingers = true; [Tooltip("Should the selected object automatically deselect if the selecting finger moves off it?")] public bool DeselectOnExit; public SelectType SelectUsing; [Tooltip("This stores the layers we want the raycast/overlap to hit (make sure this GameObject's layer is included!)")] public LayerMask LayerMask = Physics.DefaultRaycastLayers; [Tooltip("How should the selected GameObject be searched for the LeanSelectable component?")] public SearchType Search; [Tooltip("The currently selected LeanSelectables")] public List<LeanSelectable> CurrentSelectables; protected virtual void OnEnable() { // Hook events LeanTouch.OnFingerDown += FingerDown; LeanTouch.OnFingerSet += FingerSet; LeanTouch.OnFingerUp += FingerUp; } protected virtual void OnDisable() { // Unhook events LeanTouch.OnFingerDown -= FingerDown; LeanTouch.OnFingerSet -= FingerSet; LeanTouch.OnFingerUp -= FingerUp; } private void FingerDown(LeanFinger finger) { // Ignore this finger? if (IgnoreGuiFingers == true && finger.StartedOverGui == true) { return; } // Find the component under the finger var component = FindComponentUnder(finger); // Find the selectable associated with this component var selectable = FindSelectableFrom(component); // Select the found selectable with the selecting finger Select(finger, selectable); } private void FingerSet(LeanFinger finger) { if (DeselectOnExit == true) { // Run through all selected objects for (var i = CurrentSelectables.Count - 1; i >= 0; i--) { var currentSelectable = CurrentSelectables[i]; // Is it valid? if (currentSelectable != null) { // Is this object associated with this finger? if (currentSelectable.SelectingFinger == finger) { // Find the component under the finger var component = FindComponentUnder(finger); // Find the selectable associated with this component var selectable = FindSelectableFrom(component); // If the associated object is no longer under the finger, deselect it if (selectable != currentSelectable) { Deselect(currentSelectable); } } // Deselect in case the association was lost else if (currentSelectable.SelectingFinger == null) { Deselect(currentSelectable); } } // Remove invalid else { CurrentSelectables.RemoveAt(i); } } } } private void FingerUp(LeanFinger finger) { for (var i = CurrentSelectables.Count - 1; i >= 0; i--) { var currentSelectable = CurrentSelectables[i]; if (currentSelectable != null) { if (currentSelectable.SelectingFinger == finger || currentSelectable.SelectingFinger == null) { Deselect(currentSelectable); } } else { CurrentSelectables.RemoveAt(i); } } } public void Select(LeanFinger finger, LeanSelectable selectable) { // Something was selected? if (selectable != null) { if (CurrentSelectables == null) { CurrentSelectables = new List<LeanSelectable>(); } // Loop through all current selectables for (var i = CurrentSelectables.Count - 1; i >= 0; i--) { var currentSelectable = CurrentSelectables[i]; if (currentSelectable != null) { // Already selected? if (currentSelectable == selectable) { return; } } else { CurrentSelectables.RemoveAt(i); } } // Not selected yet, so select it CurrentSelectables.Add(selectable); selectable.Select(finger); } } [ContextMenu("Deselect All")] public void DeselectAll() { // Loop through all current selectables and deselect if not null if (CurrentSelectables != null) { for (var i = CurrentSelectables.Count - 1; i >= 0; i--) { var currentSelectable = CurrentSelectables[i]; if (currentSelectable != null) { currentSelectable.Deselect(); } } // Clear CurrentSelectables.Clear(); } } // Deselect the specified selectable, if it exists public void Deselect(LeanSelectable selectable) { // Loop through all current selectables if (CurrentSelectables != null) { for (var i = CurrentSelectables.Count - 1; i >= 0; i--) { var currentSelectable = CurrentSelectables[i]; if (currentSelectable != null) { // Match? if (currentSelectable == selectable) { selectable.Deselect(); CurrentSelectables.Remove(selectable); return; } } else { CurrentSelectables.RemoveAt(i); } } } } private Component FindComponentUnder(LeanFinger finger) { var component = default(Component); switch (SelectUsing) { case SelectType.Raycast3D: { // Get ray for finger var ray = finger.GetRay(); // Stores the raycast hit info var hit = default(RaycastHit); // Was this finger pressed down on a collider? if (Physics.Raycast(ray, out hit, float.PositiveInfinity, LayerMask) == true) { component = hit.collider; } } break; case SelectType.Overlap2D: { // Find the position under the current finger var point = finger.GetWorldPosition(1.0f); // Find the collider at this position component = Physics2D.OverlapPoint(point, LayerMask); } break; } return component; } private LeanSelectable FindSelectableFrom(Component component) { var selectable = default(LeanSelectable); if (component != null) { switch (Search) { case SearchType.GetComponent: selectable = component.GetComponent <LeanSelectable>(); break; case SearchType.GetComponentInParent: selectable = component.GetComponentInParent <LeanSelectable>(); break; case SearchType.GetComponentInChildren: selectable = component.GetComponentInChildren<LeanSelectable>(); break; } } return selectable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Globalization; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { internal sealed class Locator { // To disable public/protected constructors for this class private Locator() { } internal static DomainControllerInfo GetDomainControllerInfo(string computerName, string domainName, string siteName, long flags) { int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = DsGetDcNameWrapper(computerName, domainName, siteName, flags, out domainControllerInfo); if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode, domainName); } return domainControllerInfo; } internal static int DsGetDcNameWrapper(string computerName, string domainName, string siteName, long flags, out DomainControllerInfo domainControllerInfo) { IntPtr pDomainControllerInfo = IntPtr.Zero; int result = 0; // empty siteName/computerName should be treated as null if ((computerName != null) && (computerName.Length == 0)) { computerName = null; } if ((siteName != null) && (siteName.Length == 0)) { siteName = null; } result = NativeMethods.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, (int)(flags | (long)PrivateLocatorFlags.ReturnDNSName), out pDomainControllerInfo); if (result == 0) { try { // success case domainControllerInfo = new DomainControllerInfo(); Marshal.PtrToStructure(pDomainControllerInfo, domainControllerInfo); } finally { // free the buffer // what to do with error code?? if (pDomainControllerInfo != IntPtr.Zero) { result = NativeMethods.NetApiBufferFree(pDomainControllerInfo); } } } else { domainControllerInfo = new DomainControllerInfo(); } return result; } internal static ArrayList EnumerateDomainControllers(DirectoryContext context, string domainName, string siteName, long dcFlags) { Hashtable allDCs = null; ArrayList dcs = new ArrayList(); // // this api obtains the list of DCs/GCs based on dns records. The DCs/GCs that have registered // non site specific records for the domain/forest are returned. Additonally DCs/GCs that have registered site specific records // (site is either specified or defaulted to the site of the local machine) are also returned in this list. // if (siteName == null) { // // if the site name is not specified then we get the site specific records for the local machine's site (in the context of the domain/forest/application partition that is specified) // (sitename could still be null if the machine is not in any site for the specified domain/forest, in that case we don't look for any site specific records) // DomainControllerInfo domainControllerInfo; int errorCode = DsGetDcNameWrapper(null, domainName, null, dcFlags & (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DSWriteableRequired | PrivateLocatorFlags.OnlyLDAPNeeded), out domainControllerInfo); if (errorCode == 0) { siteName = domainControllerInfo.ClientSiteName; } else if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // return an empty collection return dcs; } else { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } } // this will get both the non site specific and the site specific records allDCs = DnsGetDcWrapper(domainName, siteName, dcFlags); foreach (string dcName in allDCs.Keys) { DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); if ((dcFlags & (long)PrivateLocatorFlags.GCRequired) != 0) { // add a GlobalCatalog object dcs.Add(new GlobalCatalog(dcContext, dcName)); } else { // add a domain controller object dcs.Add(new DomainController(dcContext, dcName)); } } return dcs; } private static Hashtable DnsGetDcWrapper(string domainName, string siteName, long dcFlags) { Hashtable domainControllers = new Hashtable(); int optionFlags = 0; IntPtr retGetDcContext = IntPtr.Zero; IntPtr dcDnsHostNamePtr = IntPtr.Zero; int sockAddressCount = 0; IntPtr sockAddressCountPtr = new IntPtr(sockAddressCount); IntPtr sockAddressList = IntPtr.Zero; string dcDnsHostName = null; int result = 0; result = NativeMethods.DsGetDcOpen(domainName, (int)optionFlags, siteName, IntPtr.Zero, null, (int)dcFlags, out retGetDcContext); if (result == 0) { try { result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr); if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } while (result != NativeMethods.ERROR_NO_MORE_ITEMS) { if (result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR) { try { dcDnsHostName = Marshal.PtrToStringUni(dcDnsHostNamePtr); string key = dcDnsHostName.ToLower(CultureInfo.InvariantCulture); if (!domainControllers.Contains(key)) { domainControllers.Add(key, null); } } finally { // what to do with the error? if (dcDnsHostNamePtr != IntPtr.Zero) { result = NativeMethods.NetApiBufferFree(dcDnsHostNamePtr); } } } result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr); if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } } } finally { NativeMethods.DsGetDcClose(retGetDcContext); } } else if (result != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } return domainControllers; } private static Hashtable DnsQueryWrapper(string domainName, string siteName, long dcFlags) { Hashtable domainControllers = new Hashtable(); string recordName = "_ldap._tcp."; int result = 0; int options = 0; IntPtr dnsResults = IntPtr.Zero; // construct the record name if ((siteName != null) && (!(siteName.Length == 0))) { // only looking for domain controllers / global catalogs within a // particular site recordName = recordName + siteName + "._sites."; } // check if gc or dc if (((long)dcFlags & (long)(PrivateLocatorFlags.GCRequired)) != 0) { // global catalog recordName += "gc._msdcs."; } else if (((long)dcFlags & (long)(PrivateLocatorFlags.DSWriteableRequired)) != 0) { // domain controller recordName += "dc._msdcs."; } // now add the domainName recordName = recordName + domainName; // set the BYPASS CACHE option is specified if (((long)dcFlags & (long)LocatorOptions.ForceRediscovery) != 0) { options |= NativeMethods.DnsQueryBypassCache; } // Call DnsQuery result = NativeMethods.DnsQuery(recordName, NativeMethods.DnsSrvData, options, IntPtr.Zero, out dnsResults, IntPtr.Zero); if (result == 0) { try { IntPtr currentDnsRecord = dnsResults; while (currentDnsRecord != IntPtr.Zero) { // partial marshalling of dns record data PartialDnsRecord partialDnsRecord = new PartialDnsRecord(); Marshal.PtrToStructure(currentDnsRecord, partialDnsRecord); //check if the record is of type DNS_SRV_DATA if (partialDnsRecord.type == NativeMethods.DnsSrvData) { // remarshal to get the srv record data DnsRecord dnsRecord = new DnsRecord(); Marshal.PtrToStructure(currentDnsRecord, dnsRecord); string targetName = dnsRecord.data.targetName; string key = targetName.ToLower(CultureInfo.InvariantCulture); if (!domainControllers.Contains(key)) { domainControllers.Add(key, null); } } // move to next record currentDnsRecord = partialDnsRecord.next; } } finally { // release the dns results buffer if (dnsResults != IntPtr.Zero) { NativeMethods.DnsRecordListFree(dnsResults, true); } } } else if (result != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } return domainControllers; } } }
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Umbraco.Extensions; using static Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement.SimilarNodeName; namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement { internal class SimilarNodeName { public int Id { get; set; } public string Name { get; set; } public static string GetUniqueName(IEnumerable<SimilarNodeName> names, int nodeId, string nodeName) { var items = names .Where(x => x.Id != nodeId) // ignore same node .Select(x => x.Name); var uniqueName = GetUniqueName(items, nodeName); return uniqueName; } public static string GetUniqueName(IEnumerable<string> names, string name) { var model = new StructuredName(name); var items = names .Where(x => x.InvariantStartsWith(model.Text)) // ignore non-matching names .Select(x => new StructuredName(x)); // name is empty, and there are no other names with suffixes, so just return " (1)" if (model.IsEmptyName() && !items.Any()) { model.Suffix = StructuredName.INITIAL_SUFFIX; return model.FullName; } // name is empty, and there are other names with suffixes if (model.IsEmptyName() && items.SuffixedNameExists()) { var emptyNameSuffix = GetSuffixNumber(items); if (emptyNameSuffix > 0) { model.Suffix = (uint?)emptyNameSuffix; return model.FullName; } } // no suffix - name without suffix does NOT exist - we can just use the name without suffix. if (!model.Suffix.HasValue && !items.SimpleNameExists(model.Text)) { model.Suffix = StructuredName.NO_SUFFIX; return model.FullName; } // suffix - name with suffix does NOT exist // We can just return the full name as it is as there's no conflict. if (model.Suffix.HasValue && !items.SimpleNameExists(model.FullName)) { return model.FullName; } // no suffix - name without suffix does NOT exist, AND name with suffix does NOT exist if (!model.Suffix.HasValue && !items.SimpleNameExists(model.Text) && !items.SuffixedNameExists()) { model.Suffix = StructuredName.NO_SUFFIX; return model.FullName; } // no suffix - name without suffix exists, however name with suffix does NOT exist if (!model.Suffix.HasValue && items.SimpleNameExists(model.Text) && !items.SuffixedNameExists()) { var firstSuffix = GetFirstSuffix(items); model.Suffix = (uint?)firstSuffix; return model.FullName; } // no suffix - name without suffix exists, AND name with suffix does exist if (!model.Suffix.HasValue && items.SimpleNameExists(model.Text) && items.SuffixedNameExists()) { var nextSuffix = GetSuffixNumber(items); model.Suffix = (uint?)nextSuffix; return model.FullName; } // no suffix - name without suffix does NOT exist, however name with suffix exists if (!model.Suffix.HasValue && !items.SimpleNameExists(model.Text) && items.SuffixedNameExists()) { var nextSuffix = GetSuffixNumber(items); model.Suffix = (uint?)nextSuffix; return model.FullName; } // has suffix - name without suffix exists if (model.Suffix.HasValue && items.SimpleNameExists(model.Text)) { var nextSuffix = GetSuffixNumber(items); model.Suffix = (uint?)nextSuffix; return model.FullName; } // has suffix - name without suffix does NOT exist // a case where the user added the suffix, so add a secondary suffix if (model.Suffix.HasValue && !items.SimpleNameExists(model.Text)) { model.Text = model.FullName; model.Suffix = StructuredName.NO_SUFFIX; // filter items based on full name with suffix items = items.Where(x => x.Text.InvariantStartsWith(model.FullName)); var secondarySuffix = GetFirstSuffix(items); model.Suffix = (uint?)secondarySuffix; return model.FullName; } // has suffix - name without suffix also exists, therefore we simply increment if (model.Suffix.HasValue && items.SimpleNameExists(model.Text)) { var nextSuffix = GetSuffixNumber(items); model.Suffix = (uint?)nextSuffix; return model.FullName; } return name; } private static int GetFirstSuffix(IEnumerable<StructuredName> items) { const int suffixStart = 1; if (!items.Any(x => x.Suffix == suffixStart)) { // none of the suffixes are the same as suffixStart, so we can use suffixStart! return suffixStart; } return GetSuffixNumber(items); } private static int GetSuffixNumber(IEnumerable<StructuredName> items) { int current = 1; foreach (var item in items.OrderBy(x => x.Suffix)) { if (item.Suffix == current) { current++; } else if (item.Suffix > current) { // do nothing - we found our number! // eg. when suffixes are 1 & 3, then this method is required to generate 2 break; } } return current; } internal class StructuredName { const string SPACE_CHARACTER = " "; const string SUFFIXED_PATTERN = @"(.*) \(([1-9]\d*)\)$"; internal const uint INITIAL_SUFFIX = 1; internal static readonly uint? NO_SUFFIX = default; internal string Text { get; set; } internal uint? Suffix { get; set; } public string FullName { get { string text = (Text == SPACE_CHARACTER) ? Text.Trim() : Text; return Suffix > 0 ? $"{text} ({Suffix})" : text; } } internal StructuredName(string name) { if (string.IsNullOrWhiteSpace(name)) { Text = SPACE_CHARACTER; return; } var rg = new Regex(SUFFIXED_PATTERN); var matches = rg.Matches(name); if (matches.Count > 0) { var match = matches[0]; Text = match.Groups[1].Value; int number = int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) ? number : 0; Suffix = (uint?)(number); return; } else { Text = name; } } internal bool IsEmptyName() { return string.IsNullOrWhiteSpace(Text); } } } internal static class ListExtensions { internal static bool Contains(this IEnumerable<StructuredName> items, StructuredName model) { return items.Any(x => x.FullName.InvariantEquals(model.FullName)); } internal static bool SimpleNameExists(this IEnumerable<StructuredName> items, string name) { return items.Any(x => x.FullName.InvariantEquals(name)); } internal static bool SuffixedNameExists(this IEnumerable<StructuredName> items) { return items.Any(x => x.Suffix.HasValue); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Implementation.Workspaces; using Microsoft.CodeAnalysis.Host; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public class ProjectCacheHostServiceFactoryTests { private void Test(Action<IProjectCacheHostService, ProjectId, ICachedObjectOwner, ObjectReference> action) { // Putting cacheService.CreateStrongReference in a using statement // creates a temporary local that isn't collected in Debug builds // Wrapping it in a lambda allows it to get collected. var cacheService = new ProjectCacheService(null, int.MaxValue); var projectId = ProjectId.CreateNewId(); var owner = new Owner(); var instance = new ObjectReference(); action(cacheService, projectId, owner, instance); } [Fact] public void TestCacheKeepsObjectAlive1() { Test((cacheService, projectId, owner, instance) => { ((Action)(() => { using (cacheService.EnableCaching(projectId)) { cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance.Strong); instance.Strong = null; CollectGarbage(); Assert.True(instance.Weak.IsAlive); } })).Invoke(); CollectGarbage(); Assert.False(instance.Weak.IsAlive); GC.KeepAlive(owner); }); } [Fact] public void TestCacheKeepsObjectAlive2() { Test((cacheService, projectId, owner, instance) => { ((Action)(() => { using (cacheService.EnableCaching(projectId)) { cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance.Strong); instance.Strong = null; CollectGarbage(); Assert.True(instance.Weak.IsAlive); } })).Invoke(); CollectGarbage(); Assert.False(instance.Weak.IsAlive); GC.KeepAlive(owner); }); } [Fact] public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected1() { Test((cacheService, projectId, owner, instance) => { using (cacheService.EnableCaching(projectId)) { cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance); owner = null; instance.Strong = null; CollectGarbage(); Assert.False(instance.Weak.IsAlive); } }); } [Fact] public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected2() { Test((cacheService, projectId, owner, instance) => { using (cacheService.EnableCaching(projectId)) { cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance); owner = null; instance.Strong = null; CollectGarbage(); Assert.False(instance.Weak.IsAlive); } }); } [Fact] public void TestImplicitCacheKeepsObjectAlive1() { var cacheService = new ProjectCacheService(null, int.MaxValue); var instance = new object(); var weak = new WeakReference(instance); cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, instance); instance = null; CollectGarbage(); Assert.True(weak.IsAlive); GC.KeepAlive(cacheService); } [Fact] public void TestImplicitCacheMonitoring() { var cacheService = new ProjectCacheService(null, 10, forceCleanup: true); var weak = PutObjectInImplicitCache(cacheService); var timeout = TimeSpan.FromSeconds(10); var current = DateTime.UtcNow; do { Thread.Sleep(100); CollectGarbage(); if (DateTime.UtcNow - current > timeout) { break; } } while (weak.IsAlive); Assert.False(weak.IsAlive); GC.KeepAlive(cacheService); } private static WeakReference PutObjectInImplicitCache(ProjectCacheService cacheService) { var instance = new object(); var weak = new WeakReference(instance); cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, instance); instance = null; return weak; } [Fact] public void TestP2PReference() { var workspace = new AdhocWorkspace(); var project1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp); var project2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id))); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 }); var solution = workspace.AddSolution(solutionInfo); var instance = new object(); var weak = new WeakReference(instance); var cacheService = new ProjectCacheService(workspace, int.MaxValue); using (var cache = cacheService.EnableCaching(project2.Id)) { cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, instance); instance = null; solution = null; workspace.OnProjectRemoved(project1.Id); workspace.OnProjectRemoved(project2.Id); } // make sure p2p reference doesnt go to implicit cache CollectGarbage(); Assert.False(weak.IsAlive); } [Fact] public void TestEjectFromImplicitCache() { List<Compilation> compilations = new List<Compilation>(); for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++) { compilations.Add(CSharpCompilation.Create(i.ToString())); } var weakFirst = new WeakReference(compilations[0]); var weakLast = new WeakReference(compilations[compilations.Count - 1]); var cache = new ProjectCacheService(null, int.MaxValue); for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++) { cache.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, compilations[i]); } compilations = null; CollectGarbage(); Assert.False(weakFirst.IsAlive); Assert.True(weakLast.IsAlive); GC.KeepAlive(cache); } [Fact] public void TestCacheCompilationTwice() { var comp1 = CSharpCompilation.Create("1"); var comp2 = CSharpCompilation.Create("2"); var comp3 = CSharpCompilation.Create("3"); var weak3 = new WeakReference(comp3); var weak1 = new WeakReference(comp1); var cache = new ProjectCacheService(null, int.MaxValue); var key = ProjectId.CreateNewId(); var owner = new object(); cache.CacheObjectIfCachingEnabledForKey(key, owner, comp1); cache.CacheObjectIfCachingEnabledForKey(key, owner, comp2); cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3); // When we cache 3 again, 1 should stay in the cache cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3); comp1 = null; comp2 = null; comp3 = null; CollectGarbage(); Assert.True(weak1.IsAlive); Assert.True(weak3.IsAlive); GC.KeepAlive(cache); } private class Owner : ICachedObjectOwner { object ICachedObjectOwner.CachedObject { get; set; } } private static void CollectGarbage() { for (var i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Avalonia.Diagnostics; namespace Avalonia.Collections { /// <summary> /// Describes the action notified on a clear of a <see cref="AvaloniaList{T}"/>. /// </summary> public enum ResetBehavior { /// <summary> /// Clearing the list notifies a with a /// <see cref="NotifyCollectionChangedAction.Reset"/>. /// </summary> Reset, /// <summary> /// Clearing the list notifies a with a /// <see cref="NotifyCollectionChangedAction.Remove"/>. /// </summary> Remove, } /// <summary> /// A notifying list. /// </summary> /// <typeparam name="T">The type of the list items.</typeparam> /// <remarks> /// <para> /// AvaloniaList is similar to <see cref="System.Collections.ObjectModel.ObservableCollection{T}"/> /// with a few added features: /// </para> /// /// <list type="bullet"> /// <item> /// It can be configured to notify the <see cref="CollectionChanged"/> event with a /// <see cref="NotifyCollectionChangedAction.Remove"/> action instead of a /// <see cref="NotifyCollectionChangedAction.Reset"/> when the list is cleared by /// setting <see cref="ResetBehavior"/> to <see cref="ResetBehavior.Remove"/>. /// removed /// </item> /// <item> /// A <see cref="Validate"/> function can be used to validate each item before insertion. /// removed /// </item> /// </list> /// </remarks> public class AvaloniaList<T> : IAvaloniaList<T>, IList, INotifyCollectionChangedDebug { private readonly List<T> _inner; private NotifyCollectionChangedEventHandler _collectionChanged; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> public AvaloniaList() { _inner = new List<T>(); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/>. /// </summary> /// <param name="capacity">Initial list capacity.</param> public AvaloniaList(int capacity) { _inner = new List<T>(capacity); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> /// <param name="items">The initial items for the collection.</param> public AvaloniaList(IEnumerable<T> items) { _inner = new List<T>(items); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> /// <param name="items">The initial items for the collection.</param> public AvaloniaList(params T[] items) { _inner = new List<T>(items); } /// <summary> /// Raised when a change is made to the collection's items. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged { add => _collectionChanged += value; remove => _collectionChanged -= value; } /// <summary> /// Raised when a property on the collection changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets the number of items in the collection. /// </summary> public int Count => _inner.Count; /// <summary> /// Gets or sets the reset behavior of the list. /// </summary> public ResetBehavior ResetBehavior { get; set; } /// <summary> /// Gets or sets a validation routine that can be used to validate items before they are /// added. /// </summary> public Action<T> Validate { get; set; } /// <inheritdoc/> bool IList.IsFixedSize => false; /// <inheritdoc/> bool IList.IsReadOnly => false; /// <inheritdoc/> int ICollection.Count => _inner.Count; /// <inheritdoc/> bool ICollection.IsSynchronized => false; /// <inheritdoc/> object ICollection.SyncRoot => null; /// <inheritdoc/> bool ICollection<T>.IsReadOnly => false; /// <summary> /// Gets or sets the item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The item.</returns> public T this[int index] { get { return _inner[index]; } set { Validate?.Invoke(value); T old = _inner[index]; if (!EqualityComparer<T>.Default.Equals(old, value)) { _inner[index] = value; if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, value, old, index); _collectionChanged(this, e); } } } } /// <summary> /// Gets or sets the item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The item.</returns> object IList.this[int index] { get { return this[index]; } set { this[index] = (T)value; } } /// <summary> /// Gets or sets the total number of elements the internal data structure can hold without resizing. /// </summary> public int Capacity { get => _inner.Capacity; set => _inner.Capacity = value; } /// <summary> /// Adds an item to the collection. /// </summary> /// <param name="item">The item.</param> public virtual void Add(T item) { Validate?.Invoke(item); int index = _inner.Count; _inner.Add(item); NotifyAdd(item, index); } /// <summary> /// Adds multiple items to the collection. /// </summary> /// <param name="items">The items.</param> public virtual void AddRange(IEnumerable<T> items) => InsertRange(_inner.Count, items); /// <summary> /// Removes all items from the collection. /// </summary> public virtual void Clear() { if (Count > 0) { if (_collectionChanged != null) { var e = ResetBehavior == ResetBehavior.Reset ? EventArgsCache.ResetCollectionChanged : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, _inner.ToList(), 0); _inner.Clear(); _collectionChanged(this, e); } else { _inner.Clear(); } NotifyCountChanged(); } } /// <summary> /// Tests if the collection contains the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the collection contains the item; otherwise false.</returns> public bool Contains(T item) { return _inner.Contains(item); } /// <summary> /// Copies the collection's contents to an array. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">The first index of the array to copy to.</param> public void CopyTo(T[] array, int arrayIndex) { _inner.CopyTo(array, arrayIndex); } /// <summary> /// Returns an enumerator that enumerates the items in the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/>.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(_inner); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_inner); } public Enumerator GetEnumerator() { return new Enumerator(_inner); } /// <summary> /// Gets a range of items from the collection. /// </summary> /// <param name="index">The zero-based <see cref="AvaloniaList{T}"/> index at which the range starts.</param> /// <param name="count">The number of elements in the range.</param> public IEnumerable<T> GetRange(int index, int count) { return _inner.GetRange(index, count); } /// <summary> /// Gets the index of the specified item in the collection. /// </summary> /// <param name="item">The item.</param> /// <returns> /// The index of the item or -1 if the item is not contained in the collection. /// </returns> public int IndexOf(T item) { return _inner.IndexOf(item); } /// <summary> /// Inserts an item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="item">The item.</param> public virtual void Insert(int index, T item) { Validate?.Invoke(item); _inner.Insert(index, item); NotifyAdd(item, index); } /// <summary> /// Inserts multiple items at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="items">The items.</param> public virtual void InsertRange(int index, IEnumerable<T> items) { Contract.Requires<ArgumentNullException>(items != null); bool willRaiseCollectionChanged = _collectionChanged != null; bool hasValidation = Validate != null; if (items is IList list) { if (list.Count > 0) { if (list is ICollection<T> collection) { if (hasValidation) { foreach (T item in collection) { Validate(item); } } _inner.InsertRange(index, collection); NotifyAdd(list, index); } else { EnsureCapacity(_inner.Count + list.Count); using (IEnumerator<T> en = items.GetEnumerator()) { int insertIndex = index; while (en.MoveNext()) { T item = en.Current; if (hasValidation) { Validate(item); } _inner.Insert(insertIndex++, item); } } NotifyAdd(list, index); } } } else { using (IEnumerator<T> en = items.GetEnumerator()) { if (en.MoveNext()) { // Avoid allocating list for collection notification if there is no event subscriptions. List<T> notificationItems = willRaiseCollectionChanged ? new List<T>() : null; int insertIndex = index; do { T item = en.Current; if (hasValidation) { Validate(item); } _inner.Insert(insertIndex++, item); if (willRaiseCollectionChanged) { notificationItems.Add(item); } } while (en.MoveNext()); NotifyAdd(notificationItems, index); } } } } /// <summary> /// Moves an item to a new index. /// </summary> /// <param name="oldIndex">The index of the item to move.</param> /// <param name="newIndex">The index to move the item to.</param> public void Move(int oldIndex, int newIndex) { var item = this[oldIndex]; _inner.RemoveAt(oldIndex); _inner.Insert(newIndex, item); if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, item, newIndex, oldIndex); _collectionChanged(this, e); } } /// <summary> /// Moves multiple items to a new index. /// </summary> /// <param name="oldIndex">The first index of the items to move.</param> /// <param name="count">The number of items to move.</param> /// <param name="newIndex">The index to move the items to.</param> public void MoveRange(int oldIndex, int count, int newIndex) { var items = _inner.GetRange(oldIndex, count); var modifiedNewIndex = newIndex; _inner.RemoveRange(oldIndex, count); if (newIndex > oldIndex) { modifiedNewIndex -= count; } _inner.InsertRange(modifiedNewIndex, items); if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, items, newIndex, oldIndex); _collectionChanged(this, e); } } /// <summary> /// Ensures that the capacity of the list is at least <see cref="Capacity"/>. /// </summary> /// <param name="capacity">The capacity.</param> public void EnsureCapacity(int capacity) { // Adapted from List<T> implementation. var currentCapacity = _inner.Capacity; if (currentCapacity < capacity) { var newCapacity = currentCapacity == 0 ? 4 : currentCapacity * 2; if (newCapacity < capacity) { newCapacity = capacity; } _inner.Capacity = newCapacity; } } /// <summary> /// Removes an item from the collection. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the item was found and removed, otherwise false.</returns> public virtual bool Remove(T item) { int index = _inner.IndexOf(item); if (index != -1) { _inner.RemoveAt(index); NotifyRemove(item , index); return true; } return false; } /// <summary> /// Removes multiple items from the collection. /// </summary> /// <param name="items">The items.</param> public virtual void RemoveAll(IEnumerable<T> items) { Contract.Requires<ArgumentNullException>(items != null); foreach (var i in items) { // TODO: Optimize to only send as many notifications as necessary. Remove(i); } } /// <summary> /// Removes the item at the specified index. /// </summary> /// <param name="index">The index.</param> public virtual void RemoveAt(int index) { T item = _inner[index]; _inner.RemoveAt(index); NotifyRemove(item , index); } /// <summary> /// Removes a range of elements from the collection. /// </summary> /// <param name="index">The first index to remove.</param> /// <param name="count">The number of items to remove.</param> public virtual void RemoveRange(int index, int count) { if (count > 0) { var list = _inner.GetRange(index, count); _inner.RemoveRange(index, count); NotifyRemove(list, index); } } /// <inheritdoc/> int IList.Add(object value) { int index = Count; Add((T)value); return index; } /// <inheritdoc/> bool IList.Contains(object value) { return Contains((T)value); } /// <inheritdoc/> void IList.Clear() { Clear(); } /// <inheritdoc/> int IList.IndexOf(object value) { return IndexOf((T)value); } /// <inheritdoc/> void IList.Insert(int index, object value) { Insert(index, (T)value); } /// <inheritdoc/> void IList.Remove(object value) { Remove((T)value); } /// <inheritdoc/> void IList.RemoveAt(int index) { RemoveAt(index); } /// <inheritdoc/> void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException("Multi-dimensional arrays are not supported."); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException("Non-zero lower bounds are not supported."); } if (index < 0) { throw new ArgumentException("Invalid index."); } if (array.Length - index < Count) { throw new ArgumentException("The target array is too small."); } if (array is T[] tArray) { _inner.CopyTo(tArray, index); } else { // // Catch the obvious case assignment will fail. // We can't find all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { throw new ArgumentException("Invalid array type"); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { throw new ArgumentException("Invalid array type"); } int count = _inner.Count; try { for (int i = 0; i < count; i++) { objects[index++] = _inner[i]; } } catch (ArrayTypeMismatchException) { throw new ArgumentException("Invalid array type"); } } } /// <inheritdoc/> Delegate[] INotifyCollectionChangedDebug.GetCollectionChangedSubscribers() => _collectionChanged?.GetInvocationList(); /// <summary> /// Raises the <see cref="CollectionChanged"/> event with an add action. /// </summary> /// <param name="t">The items that were added.</param> /// <param name="index">The starting index.</param> private void NotifyAdd(IList t, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a add action. /// </summary> /// <param name="item">The item that was added.</param> /// <param name="index">The starting index.</param> private void NotifyAdd(T item, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="PropertyChanged"/> event when the <see cref="Count"/> property /// changes. /// </summary> private void NotifyCountChanged() { PropertyChanged?.Invoke(this, EventArgsCache.CountPropertyChanged); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a remove action. /// </summary> /// <param name="t">The items that were removed.</param> /// <param name="index">The starting index.</param> private void NotifyRemove(IList t, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a remove action. /// </summary> /// <param name="item">The item that was removed.</param> /// <param name="index">The starting index.</param> private void NotifyRemove(T item, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Enumerates the elements of a <see cref="AvaloniaList{T}"/>. /// </summary> public struct Enumerator : IEnumerator<T> { private List<T>.Enumerator _innerEnumerator; public Enumerator(List<T> inner) { _innerEnumerator = inner.GetEnumerator(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_innerEnumerator).Reset(); } public T Current => _innerEnumerator.Current; object IEnumerator.Current => Current; public void Dispose() { _innerEnumerator.Dispose(); } } } internal static class EventArgsCache { internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs(nameof(AvaloniaList<object>.Count)); internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Watermark /// </summary> [DataContract] public partial class Watermark : IEquatable<Watermark>, IValidatableObject { public Watermark() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="Watermark" /> class. /// </summary> /// <param name="DisplayAngle">DisplayAngle.</param> /// <param name="Enabled">Enabled.</param> /// <param name="Font">The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default..</param> /// <param name="FontColor">The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White..</param> /// <param name="FontSize">The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72..</param> /// <param name="Id">Id.</param> /// <param name="ImageBase64">ImageBase64.</param> /// <param name="Transparency">Transparency.</param> /// <param name="WatermarkText">WatermarkText.</param> public Watermark(string DisplayAngle = default(string), string Enabled = default(string), string Font = default(string), string FontColor = default(string), string FontSize = default(string), string Id = default(string), string ImageBase64 = default(string), string Transparency = default(string), string WatermarkText = default(string)) { this.DisplayAngle = DisplayAngle; this.Enabled = Enabled; this.Font = Font; this.FontColor = FontColor; this.FontSize = FontSize; this.Id = Id; this.ImageBase64 = ImageBase64; this.Transparency = Transparency; this.WatermarkText = WatermarkText; } /// <summary> /// Gets or Sets DisplayAngle /// </summary> [DataMember(Name="displayAngle", EmitDefaultValue=false)] public string DisplayAngle { get; set; } /// <summary> /// Gets or Sets Enabled /// </summary> [DataMember(Name="enabled", EmitDefaultValue=false)] public string Enabled { get; set; } /// <summary> /// The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default. /// </summary> /// <value>The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.</value> [DataMember(Name="font", EmitDefaultValue=false)] public string Font { get; set; } /// <summary> /// The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White. /// </summary> /// <value>The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.</value> [DataMember(Name="fontColor", EmitDefaultValue=false)] public string FontColor { get; set; } /// <summary> /// The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72. /// </summary> /// <value>The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.</value> [DataMember(Name="fontSize", EmitDefaultValue=false)] public string FontSize { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets ImageBase64 /// </summary> [DataMember(Name="imageBase64", EmitDefaultValue=false)] public string ImageBase64 { get; set; } /// <summary> /// Gets or Sets Transparency /// </summary> [DataMember(Name="transparency", EmitDefaultValue=false)] public string Transparency { get; set; } /// <summary> /// Gets or Sets WatermarkText /// </summary> [DataMember(Name="watermarkText", EmitDefaultValue=false)] public string WatermarkText { 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 Watermark {\n"); sb.Append(" DisplayAngle: ").Append(DisplayAngle).Append("\n"); sb.Append(" Enabled: ").Append(Enabled).Append("\n"); sb.Append(" Font: ").Append(Font).Append("\n"); sb.Append(" FontColor: ").Append(FontColor).Append("\n"); sb.Append(" FontSize: ").Append(FontSize).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ImageBase64: ").Append(ImageBase64).Append("\n"); sb.Append(" Transparency: ").Append(Transparency).Append("\n"); sb.Append(" WatermarkText: ").Append(WatermarkText).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) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Watermark); } /// <summary> /// Returns true if Watermark instances are equal /// </summary> /// <param name="other">Instance of Watermark to be compared</param> /// <returns>Boolean</returns> public bool Equals(Watermark other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.DisplayAngle == other.DisplayAngle || this.DisplayAngle != null && this.DisplayAngle.Equals(other.DisplayAngle) ) && ( this.Enabled == other.Enabled || this.Enabled != null && this.Enabled.Equals(other.Enabled) ) && ( this.Font == other.Font || this.Font != null && this.Font.Equals(other.Font) ) && ( this.FontColor == other.FontColor || this.FontColor != null && this.FontColor.Equals(other.FontColor) ) && ( this.FontSize == other.FontSize || this.FontSize != null && this.FontSize.Equals(other.FontSize) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ImageBase64 == other.ImageBase64 || this.ImageBase64 != null && this.ImageBase64.Equals(other.ImageBase64) ) && ( this.Transparency == other.Transparency || this.Transparency != null && this.Transparency.Equals(other.Transparency) ) && ( this.WatermarkText == other.WatermarkText || this.WatermarkText != null && this.WatermarkText.Equals(other.WatermarkText) ); } /// <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 etc, of course :) if (this.DisplayAngle != null) hash = hash * 59 + this.DisplayAngle.GetHashCode(); if (this.Enabled != null) hash = hash * 59 + this.Enabled.GetHashCode(); if (this.Font != null) hash = hash * 59 + this.Font.GetHashCode(); if (this.FontColor != null) hash = hash * 59 + this.FontColor.GetHashCode(); if (this.FontSize != null) hash = hash * 59 + this.FontSize.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.ImageBase64 != null) hash = hash * 59 + this.ImageBase64.GetHashCode(); if (this.Transparency != null) hash = hash * 59 + this.Transparency.GetHashCode(); if (this.WatermarkText != null) hash = hash * 59 + this.WatermarkText.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
//----------------------------------------------------------------------- // <copyright file="SafeDataReaderTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading; using Csla.Test.DataBinding; using System.Data; using System.Data.SqlClient; using System.Configuration; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; using System.Configuration; #endif #if DEBUG namespace Csla.Test.SafeDataReader { [TestClass()] public class SafeDataReaderTests { [TestInitialize] public void Initialize() { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); } private static string CONNECTION_STRING = WellKnownValues.DataPortalTestDatabase; public void ClearDataBase() { SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = new SqlCommand("DELETE FROM Table2", cn); try { cn.Open(); cm.ExecuteNonQuery(); } catch (Exception) { //do nothing } finally { cn.Close(); } } [TestMethod()] [TestCategory("SkipWhenLiveUnitTesting")] public void CloseSafeDataReader() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName FROM Table2"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { Assert.AreEqual(false, dr.IsClosed); dr.Close(); Assert.AreEqual(true, dr.IsClosed); } } } [TestMethod()] public void TestFieldCount() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName, LastName FROM Table2"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { Assert.IsTrue(dr.FieldCount > 0); Assert.AreEqual(false, dr.NextResult()); dr.Close(); } cn.Close(); } } [TestMethod()] public void GetSchemaTable() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); DataTable dtSchema = null; cm.CommandText = "SELECT * FROM MultiDataTypes"; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dtSchema = dr.GetSchemaTable(); dr.Close(); } } cn.Close(); Assert.AreEqual("BIGINTFIELD", dtSchema.Rows[0][0]); Assert.AreEqual(typeof(System.Int64), dtSchema.Rows[0][12]); Assert.AreEqual(typeof(System.Byte[]), dtSchema.Rows[1][12]); } [TestMethod()] public void IsDBNull() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); cm.CommandText = "SELECT TEXT, BIGINTFIELD, IMAGEFIELD FROM MultiDataTypes"; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dr.Read(); Assert.AreEqual(true, dr.IsDBNull(2)); Assert.AreEqual(false, dr.IsDBNull(1)); dr.Close(); } } cn.Close(); } [TestMethod()] public void GetDataTypes() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); SqlCommand cm = cn.CreateCommand(); cm.CommandText = "SELECT BITFIELD, CHARFIELD, DATETIMEFIELD, UNIQUEIDENTIFIERFIELD, SMALLINTFIELD, INTFIELD, BIGINTFIELD, TEXT FROM MultiDataTypes"; bool bitfield; char charfield; Csla.SmartDate datetimefield; Guid uniqueidentifierfield; System.Int16 smallintfield; System.Int32 intfield; System.Int64 bigintfield; System.String text; cn.Open(); using (cm) { using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { dr.Read(); bitfield = dr.GetBoolean("BITFIELD"); //this causes an error in vb version (char array initialized to nothing in vb version //and it's initialized with new Char[1] in c# version) charfield = dr.GetChar("CHARFIELD"); datetimefield = dr.GetSmartDate("DATETIMEFIELD"); uniqueidentifierfield = dr.GetGuid("UNIQUEIDENTIFIERFIELD"); smallintfield = dr.GetInt16("SMALLINTFIELD"); intfield = dr.GetInt32("INTFIELD"); bigintfield = dr.GetInt64("BIGINTFIELD"); text = dr.GetString("TEXT"); dr.Close(); } } cn.Close(); Assert.AreEqual(false, bitfield); Assert.AreEqual('z', charfield); Assert.AreEqual("12/13/2005", datetimefield.ToString()); Assert.AreEqual("c0f92820-61b5-11da-8cd6-0800200c9a66", uniqueidentifierfield.ToString()); Assert.AreEqual(32767, smallintfield); Assert.AreEqual(2147483647, intfield); Assert.AreEqual(92233720368547111, bigintfield); Assert.AreEqual("a bunch of text...a bunch of text...a bunch of text...a bunch of text...", text); } [TestMethod()] [ExpectedException(typeof(SqlException))] public void ThrowSqlException() { // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT FirstName FROM NonExistantTable"; Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader()); } } [TestMethod()] public void TestSafeDataReader() { List<string> list = new List<string>(); // TODO: Connection strings were lost, and I don't know how to set them correctly SqlConnection cn = new SqlConnection(CONNECTION_STRING); cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandText = "SELECT Name, Date, Age FROM Table1"; using (Csla.Data.SafeDataReader dr = new Csla.Data.SafeDataReader(cm.ExecuteReader())) { while (dr.Read()) //returns two results { string output = dr.GetString("Name") + ", age " + dr.GetInt32("Age") + ", added on " + dr.GetSmartDate("Date"); Assert.AreEqual("varchar", dr.GetDataTypeName("Name")); Assert.AreEqual(false, dr.IsClosed); list.Add(output); Console.WriteLine(output); } dr.Close(); Assert.AreEqual(true, dr.IsClosed); } cn.Close(); } Assert.AreEqual("Bill, age 56, added on 12/23/2004", list[0]); Assert.AreEqual("Jim, age 33, added on 1/14/2003", list[1]); } } } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class output by Measure-Object. /// </summary> public abstract class MeasureInfo { /// <summary> /// Property name. /// </summary> public string Property { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class GenericMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="GenericMeasureInfo"/> class. /// </summary> public GenericMeasureInfo() { Average = Sum = Maximum = Minimum = StandardDeviation = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int Count { get; set; } /// <summary> /// The average of property values. /// </summary> public double? Average { get; set; } /// <summary> /// The sum of property values. /// </summary> public double? Sum { get; set; } /// <summary> /// The max of property values. /// </summary> public double? Maximum { get; set; } /// <summary> /// The min of property values. /// </summary> public double? Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> /// <remarks> /// This class is created to make 'Measure-Object -MAX -MIN' work with ANYTHING that supports 'CompareTo'. /// GenericMeasureInfo class is shipped with PowerShell V2. Fixing this bug requires, changing the type of /// Maximum and Minimum properties which would be a breaking change. Hence created a new class to not /// have an appcompat issues with PS V2. /// </remarks> public sealed class GenericObjectMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="GenericObjectMeasureInfo"/> class. /// Default ctor. /// </summary> public GenericObjectMeasureInfo() { Average = Sum = StandardDeviation = null; Maximum = Minimum = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int Count { get; set; } /// <summary> /// The average of property values. /// </summary> public double? Average { get; set; } /// <summary> /// The sum of property values. /// </summary> public double? Sum { get; set; } /// <summary> /// The max of property values. /// </summary> public object Maximum { get; set; } /// <summary> /// The min of property values. /// </summary> public object Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class TextMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="TextMeasureInfo"/> class. /// Default ctor. /// </summary> public TextMeasureInfo() { Lines = Words = Characters = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int? Lines { get; set; } /// <summary> /// The average of property values. /// </summary> public int? Words { get; set; } /// <summary> /// The sum of property values. /// </summary> public int? Characters { get; set; } } /// <summary> /// Measure object cmdlet. /// </summary> [Cmdlet(VerbsDiagnostic.Measure, "Object", DefaultParameterSetName = GenericParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096617", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(GenericMeasureInfo), typeof(TextMeasureInfo), typeof(GenericObjectMeasureInfo))] public sealed class MeasureObjectCommand : PSCmdlet { /// <summary> /// Dictionary to be used by Measure-Object implementation. /// Keys are strings. Keys are compared with OrdinalIgnoreCase. /// </summary> /// <typeparam name="TValue">Value type.</typeparam> private sealed class MeasureObjectDictionary<TValue> : Dictionary<string, TValue> where TValue : new() { /// <summary> /// Initializes a new instance of the <see cref="MeasureObjectDictionary{TValue}"/> class. /// Default ctor. /// </summary> internal MeasureObjectDictionary() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Attempt to look up the value associated with the /// the specified key. If a value is not found, associate /// the key with a new value created via the value type's /// default constructor. /// </summary> /// <param name="key">The key to look up.</param> /// <returns> /// The existing value, or a newly-created value. /// </returns> public TValue EnsureEntry(string key) { TValue val; if (!TryGetValue(key, out val)) { val = new TValue(); this[key] = val; } return val; } } /// <summary> /// Convenience class to track statistics without having /// to maintain two sets of MeasureInfo and constantly checking /// what mode we're in. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class Statistics { // Common properties internal int count = 0; // Generic/Numeric statistics internal double sum = 0.0; internal double sumPrevious = 0.0; internal double variance = 0.0; internal object max = null; internal object min = null; // Text statistics internal int characters = 0; internal int words = 0; internal int lines = 0; } /// <summary> /// Initializes a new instance of the <see cref="MeasureObjectCommand"/> class. /// Default constructor. /// </summary> public MeasureObjectCommand() : base() { } #region Command Line Switches #region Common parameters in both sets /// <summary> /// Incoming object. /// </summary> /// <value></value> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { get; set; } = AutomationNull.Value; /// <summary> /// Properties to be examined. /// </summary> /// <value></value> [ValidateNotNullOrEmpty] [Parameter(Position = 0)] public PSPropertyExpression[] Property { get; set; } #endregion Common parameters in both sets /// <summary> /// Set to true if Standard Deviation is to be returned. /// </summary> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter StandardDeviation { get { return _measureStandardDeviation; } set { _measureStandardDeviation = value; } } private bool _measureStandardDeviation; /// <summary> /// Set to true is Sum is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Sum { get { return _measureSum; } set { _measureSum = value; } } private bool _measureSum; /// <summary> /// Gets or sets the value indicating if all statistics should be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter AllStats { get { return _allStats; } set { _allStats = value; } } private bool _allStats; /// <summary> /// Set to true is Average is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Average { get { return _measureAverage; } set { _measureAverage = value; } } private bool _measureAverage; /// <summary> /// Set to true is Max is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Maximum { get { return _measureMax; } set { _measureMax = value; } } private bool _measureMax; /// <summary> /// Set to true is Min is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Minimum { get { return _measureMin; } set { _measureMin = value; } } private bool _measureMin; #region TextMeasure ParameterSet /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Line { get { return _measureLines; } set { _measureLines = value; } } private bool _measureLines = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Word { get { return _measureWords; } set { _measureWords = value; } } private bool _measureWords = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Character { get { return _measureCharacters; } set { _measureCharacters = value; } } private bool _measureCharacters = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter IgnoreWhiteSpace { get { return _ignoreWhiteSpace; } set { _ignoreWhiteSpace = value; } } private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet #endregion Command Line Switches /// <summary> /// Which parameter set the Cmdlet is in. /// </summary> private bool IsMeasuringGeneric { get { return string.Equals(ParameterSetName, GenericParameterSet, StringComparison.Ordinal); } } /// <summary> /// Does the begin part of the cmdlet. /// </summary> protected override void BeginProcessing() { // Sets all other generic parameters to true to get all statistics. if (_allStats) { _measureSum = _measureStandardDeviation = _measureAverage = _measureMax = _measureMin = true; } // finally call the base class. base.BeginProcessing(); } /// <summary> /// Collect data about each record that comes in. /// Side effects: Updates totalRecordCount. /// </summary> protected override void ProcessRecord() { if (InputObject == null || InputObject == AutomationNull.Value) { return; } _totalRecordCount++; if (Property == null) AnalyzeValue(null, InputObject.BaseObject); else AnalyzeObjectProperties(InputObject); } /// <summary> /// Analyze an object on a property-by-property basis instead /// of as a simple value. /// Side effects: Updates statistics. /// </summary> /// <param name="inObj">The object to analyze.</param> private void AnalyzeObjectProperties(PSObject inObj) { // Keep track of which properties are counted for an // input object so that repeated properties won't be // counted twice. MeasureObjectDictionary<object> countedProperties = new(); // First iterate over the user-specified list of // properties... foreach (var expression in Property) { List<PSPropertyExpression> resolvedNames = expression.ResolveNames(inObj); if (resolvedNames == null || resolvedNames.Count == 0) { // Insert a blank entry so we can track // property misses in EndProcessing. if (!expression.HasWildCardCharacters) { string propertyName = expression.ToString(); _statistics.EnsureEntry(propertyName); } continue; } // Each property value can potentially refer // to multiple properties via globbing. Iterate over // the actual property names. foreach (PSPropertyExpression resolvedName in resolvedNames) { string propertyName = resolvedName.ToString(); // skip duplicated properties if (countedProperties.ContainsKey(propertyName)) { continue; } List<PSPropertyExpressionResult> tempExprRes = resolvedName.GetValues(inObj); if (tempExprRes == null || tempExprRes.Count == 0) { // Shouldn't happen - would somehow mean // that the property went away between when // we resolved it and when we tried to get its // value. continue; } AnalyzeValue(propertyName, tempExprRes[0].Result); // Remember resolved propertyNames that have been counted countedProperties[propertyName] = null; } } } /// <summary> /// Analyze a value for generic/text statistics. /// Side effects: Updates statistics. May set nonNumericError. /// </summary> /// <param name="propertyName">The property this value corresponds to.</param> /// <param name="objValue">The value to analyze.</param> private void AnalyzeValue(string propertyName, object objValue) { if (propertyName == null) propertyName = thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); // Update common properties. stat.count++; if (_measureCharacters || _measureWords || _measureLines) { string strValue = (objValue == null) ? string.Empty : objValue.ToString(); AnalyzeString(strValue, stat); } if (_measureAverage || _measureSum || _measureStandardDeviation) { double numValue = 0.0; if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { _nonNumericError = true; ErrorRecord errorRecord = new( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", ErrorCategory.InvalidType, objValue); WriteError(errorRecord); return; } AnalyzeNumber(numValue, stat); } // Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo if (_measureMin) { stat.min = Compare(objValue, stat.min, true); } if (_measureMax) { stat.max = Compare(objValue, stat.max, false); } } /// <summary> /// Compare is a helper function used to find the min/max between the supplied input values. /// </summary> /// <param name="objValue"> /// Current input value. /// </param> /// <param name="statMinOrMaxValue"> /// Current minimum or maximum value in the statistics. /// </param> /// <param name="isMin"> /// Indicates if minimum or maximum value has to be found. /// If true is passed in then the minimum of the two values would be returned. /// If false is passed in then maximum of the two values will be returned.</param> /// <returns></returns> private static object Compare(object objValue, object statMinOrMaxValue, bool isMin) { object currentValue = objValue; object statValue = statMinOrMaxValue; double temp; currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo<double>(objValue, out temp)) ? temp : currentValue; statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo<double>(statValue, out temp)) ? temp : statValue; if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) { currentValue = PSObject.AsPSObject(currentValue).ToString(); statValue = PSObject.AsPSObject(statValue).ToString(); } if (statValue == null) { return objValue; } int comparisonResult = LanguagePrimitives.Compare(statValue, currentValue, ignoreCase: false, CultureInfo.CurrentCulture); return (isMin ? comparisonResult : -comparisonResult) > 0 ? objValue : statMinOrMaxValue; } /// <summary> /// Class contains util static functions. /// </summary> private static class TextCountUtilities { /// <summary> /// Count chars in inStr. /// </summary> /// <param name="inStr">String whose chars are counted.</param> /// <param name="ignoreWhiteSpace">True to discount white space.</param> /// <returns>Number of chars in inStr.</returns> internal static int CountChar(string inStr, bool ignoreWhiteSpace) { if (string.IsNullOrEmpty(inStr)) { return 0; } if (!ignoreWhiteSpace) { return inStr.Length; } int len = 0; foreach (char c in inStr) { if (!char.IsWhiteSpace(c)) { len++; } } return len; } /// <summary> /// Count words in inStr. /// </summary> /// <param name="inStr">String whose words are counted.</param> /// <returns>Number of words in inStr.</returns> internal static int CountWord(string inStr) { if (string.IsNullOrEmpty(inStr)) { return 0; } int wordCount = 0; bool wasAWhiteSpace = true; foreach (char c in inStr) { if (char.IsWhiteSpace(c)) { wasAWhiteSpace = true; } else { if (wasAWhiteSpace) { wordCount++; } wasAWhiteSpace = false; } } return wordCount; } /// <summary> /// Count lines in inStr. /// </summary> /// <param name="inStr">String whose lines are counted.</param> /// <returns>Number of lines in inStr.</returns> internal static int CountLine(string inStr) { if (string.IsNullOrEmpty(inStr)) { return 0; } int numberOfLines = 0; foreach (char c in inStr) { if (c == '\n') { numberOfLines++; } } // 'abc\nd' has two lines // but 'abc\n' has one line if (inStr[inStr.Length - 1] != '\n') { numberOfLines++; } return numberOfLines; } } /// <summary> /// Update text statistics. /// </summary> /// <param name="strValue">The text to analyze.</param> /// <param name="stat">The Statistics object to update.</param> private void AnalyzeString(string strValue, Statistics stat) { if (_measureCharacters) stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); if (_measureWords) stat.words += TextCountUtilities.CountWord(strValue); if (_measureLines) stat.lines += TextCountUtilities.CountLine(strValue); } /// <summary> /// Update number statistics. /// </summary> /// <param name="numValue">The number to analyze.</param> /// <param name="stat">The Statistics object to update.</param> private void AnalyzeNumber(double numValue, Statistics stat) { if (_measureSum || _measureAverage || _measureStandardDeviation) { stat.sumPrevious = stat.sum; stat.sum += numValue; } if (_measureStandardDeviation && stat.count > 1) { // Based off of iterative method of calculating variance on // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm double avgPrevious = stat.sumPrevious / (stat.count - 1); stat.variance *= (stat.count - 2.0) / (stat.count - 1); stat.variance += (numValue - avgPrevious) * (numValue - avgPrevious) / stat.count; } } /// <summary> /// WriteError when a property is not found. /// </summary> /// <param name="propertyName">The missing property.</param> /// <param name="errorId">The error ID to write.</param> private void WritePropertyNotFoundError(string propertyName, string errorId) { Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException(propertyName), errorId, ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails( this, "MeasureObjectStrings", "PropertyNotFound", propertyName); WriteError(errorRecord); } /// <summary> /// Output collected statistics. /// Side effects: Updates statistics. Writes objects to stream. /// </summary> protected override void EndProcessing() { // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. if (_totalRecordCount == 0 && Property == null) { _statistics.EnsureEntry(thisObject); } foreach (string propertyName in _statistics.Keys) { Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { if (Context.IsStrictVersion(2)) { string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; WritePropertyNotFoundError(propertyName, errorId); } continue; } MeasureInfo mi = null; if (IsMeasuringGeneric) { double temp; if ((stat.min == null || LanguagePrimitives.TryConvertTo<double>(stat.min, out temp)) && (stat.max == null || LanguagePrimitives.TryConvertTo<double>(stat.max, out temp))) { mi = CreateGenericMeasureInfo(stat, true); } else { mi = CreateGenericMeasureInfo(stat, false); } } else mi = CreateTextMeasureInfo(stat); // Set common properties. if (Property != null) mi.Property = propertyName; WriteObject(mi); } } /// <summary> /// Create a MeasureInfo object for generic stats. /// </summary> /// <param name="stat">The statistics to use.</param> /// <param name="shouldUseGenericMeasureInfo"></param> /// <returns>A new GenericMeasureInfo object.</returns> private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGenericMeasureInfo) { double? sum = null; double? average = null; double? StandardDeviation = null; object max = null; object min = null; if (!_nonNumericError) { if (_measureSum) sum = stat.sum; if (_measureAverage && stat.count > 0) average = stat.sum / stat.count; if (_measureStandardDeviation) { StandardDeviation = Math.Sqrt(stat.variance); } } if (_measureMax) { if (shouldUseGenericMeasureInfo && (stat.max != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.max, out temp); max = temp; } else { max = stat.max; } } if (_measureMin) { if (shouldUseGenericMeasureInfo && (stat.min != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.min, out temp); min = temp; } else { min = stat.min; } } if (shouldUseGenericMeasureInfo) { GenericMeasureInfo gmi = new(); gmi.Count = stat.count; gmi.Sum = sum; gmi.Average = average; gmi.StandardDeviation = StandardDeviation; if (max != null) { gmi.Maximum = (double)max; } if (min != null) { gmi.Minimum = (double)min; } return gmi; } else { GenericObjectMeasureInfo gomi = new(); gomi.Count = stat.count; gomi.Sum = sum; gomi.Average = average; gomi.Maximum = max; gomi.Minimum = min; return gomi; } } /// <summary> /// Create a MeasureInfo object for text stats. /// </summary> /// <param name="stat">The statistics to use.</param> /// <returns>A new TextMeasureInfo object.</returns> private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) { TextMeasureInfo tmi = new(); if (_measureCharacters) tmi.Characters = stat.characters; if (_measureWords) tmi.Words = stat.words; if (_measureLines) tmi.Lines = stat.lines; return tmi; } /// <summary> /// The observed statistics keyed by property name. /// If Property is not set, then the key used will be the value of thisObject. /// </summary> private readonly MeasureObjectDictionary<Statistics> _statistics = new(); /// <summary> /// Whether or not a numeric conversion error occurred. /// If true, then average/sum/standard deviation will not be output. /// </summary> private bool _nonNumericError = false; /// <summary> /// The total number of records encountered. /// </summary> private int _totalRecordCount = 0; /// <summary> /// Parameter set name for measuring objects. /// </summary> private const string GenericParameterSet = "GenericMeasure"; /// <summary> /// Parameter set name for measuring text. /// </summary> private const string TextParameterSet = "TextMeasure"; /// <summary> /// Key that statistics are stored under when Property is not set. /// </summary> private const string thisObject = "$_"; } }
// 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.IO.PortsTests; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class ReadChar_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random characters to receive private const int numRndChar = 8; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadChar()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); var t = new Task(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadChar(); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndChar - 2); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1)); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndChar]; char[] expectedChars = new char[numRndChar]; char[] actualChars = new char[numRndChar + 1]; int actualCharIndex = 0; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); while (true) { int charRead; try { charRead = com1.ReadChar(); } catch (TimeoutException) { break; } actualChars[actualCharIndex] = (char)charRead; actualCharIndex++; } Assert.Equal(expectedChars, actualChars.Take(expectedChars.Length).ToArray()); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; Assert.Throws<TimeoutException>(() => com.ReadChar()); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadChar()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadChar()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] byteBuffer = new byte[numRndChar]; char[] charBuffer = new char[numRndChar]; int expectedChar; //Genrate random characters without an parity error for (int i = 0; i < byteBuffer.Length; i++) { int randChar = rndGen.Next(0, 128); byteBuffer[i] = (byte)randChar; charBuffer[i] = (char)randChar; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedChar = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedChar = charBuffer[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedChar = parityReplace; } //Create an parity error by setting the highest order bit to true byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); charBuffer[parityErrorIndex] = (char)expectedChar; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); VerifyRead(com1, com2, byteBuffer, charBuffer); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { break; } //While their are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then we expecte Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedChars[i]) { //If the character read is not the expected character Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); } i++; } Assert.Equal(expectedChars.Length, i); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateSnapshotGetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pSnapshotName = new RuntimeDefinedParameter(); pSnapshotName.Name = "SnapshotName"; pSnapshotName.ParameterType = typeof(string); pSnapshotName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pSnapshotName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("SnapshotName", pSnapshotName); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 3, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteSnapshotGetMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string snapshotName = (string)ParseParameter(invokeMethodInputParameters[1]); if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(snapshotName)) { var result = SnapshotsClient.Get(resourceGroupName, snapshotName); WriteObject(result); } else if (!string.IsNullOrEmpty(resourceGroupName)) { var result = SnapshotsClient.ListByResourceGroup(resourceGroupName); var resultList = result.ToList(); var nextPageLink = result.NextPageLink; while (!string.IsNullOrEmpty(nextPageLink)) { var pageResult = SnapshotsClient.ListByResourceGroupNext(nextPageLink); foreach (var pageItem in pageResult) { resultList.Add(pageItem); } nextPageLink = pageResult.NextPageLink; } WriteObject(resultList, true); } else { var result = SnapshotsClient.List(); var resultList = result.ToList(); var nextPageLink = result.NextPageLink; while (!string.IsNullOrEmpty(nextPageLink)) { var pageResult = SnapshotsClient.ListNext(nextPageLink); foreach (var pageItem in pageResult) { resultList.Add(pageItem); } nextPageLink = pageResult.NextPageLink; } WriteObject(resultList, true); } } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateSnapshotGetParameters() { string resourceGroupName = string.Empty; string snapshotName = string.Empty; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "SnapshotName" }, new object[] { resourceGroupName, snapshotName }); } } [Cmdlet(VerbsCommon.Get, "AzureRmSnapshot", DefaultParameterSetName = "DefaultParameter")] [OutputType(typeof(PSSnapshot))] public partial class GetAzureRmSnapshot : ComputeAutomationBaseCmdlet { protected override void ProcessRecord() { ExecuteClientAction(() => { string resourceGroupName = this.ResourceGroupName; string snapshotName = this.SnapshotName; if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(snapshotName)) { var result = SnapshotsClient.Get(resourceGroupName, snapshotName); var psObject = new PSSnapshot(); ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshot>(result, psObject); WriteObject(psObject); } else if (!string.IsNullOrEmpty(resourceGroupName)) { var result = SnapshotsClient.ListByResourceGroup(resourceGroupName); var resultList = result.ToList(); var nextPageLink = result.NextPageLink; while (!string.IsNullOrEmpty(nextPageLink)) { var pageResult = SnapshotsClient.ListByResourceGroupNext(nextPageLink); foreach (var pageItem in pageResult) { resultList.Add(pageItem); } nextPageLink = pageResult.NextPageLink; } var psObject = new List<PSSnapshotList>(); foreach (var r in resultList) { psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshotList>(r)); } WriteObject(psObject, true); } else { var result = SnapshotsClient.List(); var resultList = result.ToList(); var nextPageLink = result.NextPageLink; while (!string.IsNullOrEmpty(nextPageLink)) { var pageResult = SnapshotsClient.ListNext(nextPageLink); foreach (var pageItem in pageResult) { resultList.Add(pageItem); } nextPageLink = pageResult.NextPageLink; } var psObject = new List<PSSnapshotList>(); foreach (var r in resultList) { psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Snapshot, PSSnapshotList>(r)); } WriteObject(psObject, true); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] [ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleter()] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string SnapshotName { get; set; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Verify.V2.Service.Entity { /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Delete a specific Factor. /// </summary> public class DeleteFactorOptions : IOptions<FactorResource> { /// <summary> /// Service Sid. /// </summary> public string PathServiceSid { get; } /// <summary> /// Unique external identifier of the Entity /// </summary> public string PathIdentity { get; } /// <summary> /// A string that uniquely identifies this Factor. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteFactorOptions /// </summary> /// <param name="pathServiceSid"> Service Sid. </param> /// <param name="pathIdentity"> Unique external identifier of the Entity </param> /// <param name="pathSid"> A string that uniquely identifies this Factor. </param> public DeleteFactorOptions(string pathServiceSid, string pathIdentity, string pathSid) { PathServiceSid = pathServiceSid; PathIdentity = pathIdentity; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Fetch a specific Factor. /// </summary> public class FetchFactorOptions : IOptions<FactorResource> { /// <summary> /// Service Sid. /// </summary> public string PathServiceSid { get; } /// <summary> /// Unique external identifier of the Entity /// </summary> public string PathIdentity { get; } /// <summary> /// A string that uniquely identifies this Factor. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchFactorOptions /// </summary> /// <param name="pathServiceSid"> Service Sid. </param> /// <param name="pathIdentity"> Unique external identifier of the Entity </param> /// <param name="pathSid"> A string that uniquely identifies this Factor. </param> public FetchFactorOptions(string pathServiceSid, string pathIdentity, string pathSid) { PathServiceSid = pathServiceSid; PathIdentity = pathIdentity; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a list of all Factors for an Entity. /// </summary> public class ReadFactorOptions : ReadOptions<FactorResource> { /// <summary> /// Service Sid. /// </summary> public string PathServiceSid { get; } /// <summary> /// Unique external identifier of the Entity /// </summary> public string PathIdentity { get; } /// <summary> /// Construct a new ReadFactorOptions /// </summary> /// <param name="pathServiceSid"> Service Sid. </param> /// <param name="pathIdentity"> Unique external identifier of the Entity </param> public ReadFactorOptions(string pathServiceSid, string pathIdentity) { PathServiceSid = pathServiceSid; PathIdentity = pathIdentity; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Update a specific Factor. This endpoint can be used to Verify a Factor if passed an `AuthPayload` param. /// </summary> public class UpdateFactorOptions : IOptions<FactorResource> { /// <summary> /// Service Sid. /// </summary> public string PathServiceSid { get; } /// <summary> /// Unique external identifier of the Entity /// </summary> public string PathIdentity { get; } /// <summary> /// A string that uniquely identifies this Factor. /// </summary> public string PathSid { get; } /// <summary> /// Optional payload to verify the Factor for the first time /// </summary> public string AuthPayload { get; set; } /// <summary> /// The friendly name of this Factor /// </summary> public string FriendlyName { get; set; } /// <summary> /// For APN, the device token. For FCM, the registration token /// </summary> public string ConfigNotificationToken { get; set; } /// <summary> /// The Verify Push SDK version used to configure the factor /// </summary> public string ConfigSdkVersion { get; set; } /// <summary> /// How often, in seconds, are TOTP codes generated /// </summary> public int? ConfigTimeStep { get; set; } /// <summary> /// The number of past and future time-steps valid at a given time /// </summary> public int? ConfigSkew { get; set; } /// <summary> /// Number of digits for generated TOTP codes /// </summary> public int? ConfigCodeLength { get; set; } /// <summary> /// The algorithm used to derive the TOTP codes /// </summary> public FactorResource.TotpAlgorithmsEnum ConfigAlg { get; set; } /// <summary> /// The transport technology used to generate the Notification Token /// </summary> public string ConfigNotificationPlatform { get; set; } /// <summary> /// Construct a new UpdateFactorOptions /// </summary> /// <param name="pathServiceSid"> Service Sid. </param> /// <param name="pathIdentity"> Unique external identifier of the Entity </param> /// <param name="pathSid"> A string that uniquely identifies this Factor. </param> public UpdateFactorOptions(string pathServiceSid, string pathIdentity, string pathSid) { PathServiceSid = pathServiceSid; PathIdentity = pathIdentity; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (AuthPayload != null) { p.Add(new KeyValuePair<string, string>("AuthPayload", AuthPayload)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (ConfigNotificationToken != null) { p.Add(new KeyValuePair<string, string>("Config.NotificationToken", ConfigNotificationToken)); } if (ConfigSdkVersion != null) { p.Add(new KeyValuePair<string, string>("Config.SdkVersion", ConfigSdkVersion)); } if (ConfigTimeStep != null) { p.Add(new KeyValuePair<string, string>("Config.TimeStep", ConfigTimeStep.ToString())); } if (ConfigSkew != null) { p.Add(new KeyValuePair<string, string>("Config.Skew", ConfigSkew.ToString())); } if (ConfigCodeLength != null) { p.Add(new KeyValuePair<string, string>("Config.CodeLength", ConfigCodeLength.ToString())); } if (ConfigAlg != null) { p.Add(new KeyValuePair<string, string>("Config.Alg", ConfigAlg.ToString())); } if (ConfigNotificationPlatform != null) { p.Add(new KeyValuePair<string, string>("Config.NotificationPlatform", ConfigNotificationPlatform)); } return p; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Rooms; using osu.Game.Rulesets; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Online { [HeadlessTest] public class TestSceneOnlinePlayBeatmapAvailabilityTracker : OsuTestScene { private RulesetStore rulesets; private TestBeatmapManager beatmaps; private TestBeatmapModelDownloader beatmapDownloader; private string testBeatmapFile; private BeatmapInfo testBeatmapInfo; private BeatmapSetInfo testBeatmapSet; private readonly Bindable<PlaylistItem> selectedItem = new Bindable<PlaylistItem>(); private OnlinePlayBeatmapAvailabilityTracker availabilityTracker; [BackgroundDependencyLoader] private void load(AudioManager audio, GameHost host) { Dependencies.Cache(rulesets = new RealmRulesetStore(Realm)); Dependencies.CacheAs<BeatmapManager>(beatmaps = new TestBeatmapManager(LocalStorage, Realm, rulesets, API, audio, Resources, host, Beatmap.Default)); Dependencies.CacheAs<BeatmapModelDownloader>(beatmapDownloader = new TestBeatmapModelDownloader(beatmaps, API)); } [SetUp] public void SetUp() => Schedule(() => { ((DummyAPIAccess)API).HandleRequest = req => { switch (req) { case GetBeatmapsRequest beatmapsReq: var beatmap = CreateAPIBeatmap(); beatmap.OnlineID = testBeatmapInfo.OnlineID; beatmap.OnlineBeatmapSetID = testBeatmapSet.OnlineID; beatmap.Checksum = testBeatmapInfo.MD5Hash; beatmap.BeatmapSet!.OnlineID = testBeatmapSet.OnlineID; beatmapsReq.TriggerSuccess(new GetBeatmapsResponse { Beatmaps = new List<APIBeatmap> { beatmap } }); return true; default: return false; } }; beatmaps.AllowImport = new TaskCompletionSource<bool>(); testBeatmapFile = TestResources.GetQuickTestBeatmapForImport(); testBeatmapInfo = getTestBeatmapInfo(testBeatmapFile); testBeatmapSet = testBeatmapInfo.BeatmapSet; Realm.Write(r => r.RemoveAll<BeatmapSetInfo>()); Realm.Write(r => r.RemoveAll<BeatmapInfo>()); selectedItem.Value = new PlaylistItem(testBeatmapInfo) { RulesetID = testBeatmapInfo.Ruleset.OnlineID, }; recreateChildren(); }); private void recreateChildren() { var beatmapLookupCache = new BeatmapLookupCache(); Child = new DependencyProvidingContainer { CachedDependencies = new[] { (typeof(BeatmapLookupCache), (object)beatmapLookupCache) }, Children = new Drawable[] { beatmapLookupCache, availabilityTracker = new OnlinePlayBeatmapAvailabilityTracker { SelectedItem = { BindTarget = selectedItem, } } } }; } [Test] public void TestBeatmapDownloadingFlow() { AddAssert("ensure beatmap unavailable", () => !beatmaps.IsAvailableLocally(testBeatmapSet)); addAvailabilityCheckStep("state not downloaded", BeatmapAvailability.NotDownloaded); AddStep("start downloading", () => beatmapDownloader.Download(testBeatmapSet)); addAvailabilityCheckStep("state downloading 0%", () => BeatmapAvailability.Downloading(0.0f)); AddStep("set progress 40%", () => ((TestDownloadRequest)beatmapDownloader.GetExistingDownload(testBeatmapSet)).SetProgress(0.4f)); addAvailabilityCheckStep("state downloading 40%", () => BeatmapAvailability.Downloading(0.4f)); AddStep("finish download", () => ((TestDownloadRequest)beatmapDownloader.GetExistingDownload(testBeatmapSet)).TriggerSuccess(testBeatmapFile)); addAvailabilityCheckStep("state importing", BeatmapAvailability.Importing); AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddUntilStep("wait for import", () => beatmaps.CurrentImport != null); AddAssert("ensure beatmap available", () => beatmaps.IsAvailableLocally(testBeatmapSet)); addAvailabilityCheckStep("state is locally available", BeatmapAvailability.LocallyAvailable); } [Test] public void TestTrackerRespectsSoftDeleting() { AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddStep("import beatmap", () => beatmaps.Import(testBeatmapFile).WaitSafely()); addAvailabilityCheckStep("state locally available", BeatmapAvailability.LocallyAvailable); AddStep("delete beatmap", () => beatmaps.Delete(beatmaps.QueryBeatmapSet(b => b.OnlineID == testBeatmapSet.OnlineID)!.Value)); addAvailabilityCheckStep("state not downloaded", BeatmapAvailability.NotDownloaded); AddStep("undelete beatmap", () => beatmaps.Undelete(beatmaps.QueryBeatmapSet(b => b.OnlineID == testBeatmapSet.OnlineID)!.Value)); addAvailabilityCheckStep("state locally available", BeatmapAvailability.LocallyAvailable); } [Test] public void TestTrackerRespectsChecksum() { AddStep("allow importing", () => beatmaps.AllowImport.SetResult(true)); AddStep("import beatmap", () => beatmaps.Import(testBeatmapFile).WaitSafely()); addAvailabilityCheckStep("initially locally available", BeatmapAvailability.LocallyAvailable); AddStep("import altered beatmap", () => { beatmaps.Import(TestResources.GetTestBeatmapForImport(true)).WaitSafely(); }); addAvailabilityCheckStep("state not downloaded", BeatmapAvailability.NotDownloaded); AddStep("recreate tracker", recreateChildren); addAvailabilityCheckStep("state not downloaded as well", BeatmapAvailability.NotDownloaded); AddStep("reimport original beatmap", () => beatmaps.Import(TestResources.GetQuickTestBeatmapForImport()).WaitSafely()); addAvailabilityCheckStep("locally available after re-import", BeatmapAvailability.LocallyAvailable); } private void addAvailabilityCheckStep(string description, Func<BeatmapAvailability> expected) { AddUntilStep(description, () => availabilityTracker.Availability.Value.Equals(expected.Invoke())); } private static BeatmapInfo getTestBeatmapInfo(string archiveFile) { BeatmapInfo info; using (var archive = new ZipArchiveReader(File.OpenRead(archiveFile))) using (var stream = archive.GetStream("Soleily - Renatus (Gamu) [Insane].osu")) using (var reader = new LineBufferedReader(stream)) { var decoder = Decoder.GetDecoder<Beatmap>(reader); var beatmap = decoder.Decode(reader); info = beatmap.BeatmapInfo; Debug.Assert(info.BeatmapSet != null); info.BeatmapSet.Beatmaps.Add(info); info.MD5Hash = stream.ComputeMD5Hash(); info.Hash = stream.ComputeSHA2Hash(); } return info; } private class TestBeatmapManager : BeatmapManager { public TaskCompletionSource<bool> AllowImport = new TaskCompletionSource<bool>(); public Live<BeatmapSetInfo> CurrentImport { get; private set; } public TestBeatmapManager(Storage storage, RealmAccess realm, RulesetStore rulesets, IAPIProvider api, [NotNull] AudioManager audioManager, IResourceStore<byte[]> resources, GameHost host = null, WorkingBeatmap defaultBeatmap = null) : base(storage, realm, rulesets, api, audioManager, resources, host, defaultBeatmap) { } protected override BeatmapModelManager CreateBeatmapModelManager(Storage storage, RealmAccess realm, RulesetStore rulesets, BeatmapOnlineLookupQueue onlineLookupQueue) { return new TestBeatmapModelManager(this, storage, realm, onlineLookupQueue); } internal class TestBeatmapModelManager : BeatmapModelManager { private readonly TestBeatmapManager testBeatmapManager; public TestBeatmapModelManager(TestBeatmapManager testBeatmapManager, Storage storage, RealmAccess databaseAccess, BeatmapOnlineLookupQueue beatmapOnlineLookupQueue) : base(databaseAccess, storage, beatmapOnlineLookupQueue) { this.testBeatmapManager = testBeatmapManager; } public override Live<BeatmapSetInfo> Import(BeatmapSetInfo item, ArchiveReader archive = null, bool lowPriority = false, CancellationToken cancellationToken = default) { testBeatmapManager.AllowImport.Task.WaitSafely(); return (testBeatmapManager.CurrentImport = base.Import(item, archive, lowPriority, cancellationToken)); } } } internal class TestBeatmapModelDownloader : BeatmapModelDownloader { public TestBeatmapModelDownloader(IModelImporter<BeatmapSetInfo> importer, IAPIProvider apiProvider) : base(importer, apiProvider) { } protected override ArchiveDownloadRequest<IBeatmapSetInfo> CreateDownloadRequest(IBeatmapSetInfo set, bool minimiseDownloadSize) => new TestDownloadRequest(set); } private class TestDownloadRequest : ArchiveDownloadRequest<IBeatmapSetInfo> { public new void SetProgress(float progress) => base.SetProgress(progress); public new void TriggerSuccess(string filename) => base.TriggerSuccess(filename); public TestDownloadRequest(IBeatmapSetInfo model) : base(model) { } protected override string Target => null; } } }
//------------------------------------------------------------------------------ // <copyright file="_AuthenticationManager2.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net.Configuration; using System.Reflection; using System.Security.Authentication.ExtendedProtection; internal class AuthenticationManager2 : AuthenticationManagerBase { private PrefixLookup moduleBinding = null; private ConcurrentDictionary<string, IAuthenticationModule> moduleList = null; public AuthenticationManager2() { this.moduleBinding = new PrefixLookup(); InitializeModuleList(); } public AuthenticationManager2(int maxPrefixLookupEntries) { this.moduleBinding = new PrefixLookup(maxPrefixLookupEntries); InitializeModuleList(); } /// <devdoc> /// <para>Call each registered authentication module to determine the first module that /// can respond to the authentication request.</para> /// </devdoc> public override Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials) { // // parameter validation // if (request == null) { throw new ArgumentNullException("request"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } if (challenge == null) { throw new ArgumentNullException("challenge"); } GlobalLog.Print("AuthenticationManager::Authenticate() challenge:[" + challenge + "]"); Authorization response = null; HttpWebRequest httpWebRequest = request as HttpWebRequest; if (httpWebRequest != null && httpWebRequest.CurrentAuthenticationState.Module != null) { response = httpWebRequest.CurrentAuthenticationState.Module.Authenticate(challenge, request, credentials); } else { // This is the case where we would try to find the module on the first server challenge foreach (IAuthenticationModule authenticationModule in this.moduleList.Values) { // // the AuthenticationModule will // 1) return a valid string on success // 2) return null if it knows it cannot respond // 3) throw if it could have responded but unexpectedly failed to do so // if (httpWebRequest != null) { httpWebRequest.CurrentAuthenticationState.Module = authenticationModule; } response = authenticationModule.Authenticate(challenge, request, credentials); if (response != null) { // // found the Authentication Module, return it // GlobalLog.Print("AuthenticationManager::Authenticate() found IAuthenticationModule:[" + authenticationModule.AuthenticationType + "]"); break; } } } return response; } /// <devdoc> /// <para>Pre-authenticates a request.</para> /// </devdoc> public override Authorization PreAuthenticate(WebRequest request, ICredentials credentials) { GlobalLog.Print("AuthenticationManager::PreAuthenticate() request:" + ValidationHelper.HashString(request) + " credentials:" + ValidationHelper.HashString(credentials)); if (request == null) { throw new ArgumentNullException("request"); } if (credentials == null) { return null; } HttpWebRequest httpWebRequest = request as HttpWebRequest; IAuthenticationModule authenticationModule; if (httpWebRequest == null) { return null; } // // PrefixLookup is thread-safe // string moduleName = moduleBinding.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as string; GlobalLog.Print("AuthenticationManager::PreAuthenticate() s_ModuleBinding.Lookup returns:" + ValidationHelper.ToString(moduleName)); if (moduleName == null) { return null; } if (!this.moduleList.TryGetValue(moduleName.ToUpperInvariant(), out authenticationModule)) { // The module could have been unregistered // No preauthentication is possible return null; } // prepopulate the channel binding token so we can try preauth (but only for modules that actually need it!) if (httpWebRequest.ChallengedUri.Scheme == Uri.UriSchemeHttps) { object binding = httpWebRequest.ServicePoint.CachedChannelBinding; #if DEBUG // the ModuleRequiresChannelBinding method is only compiled in DEBUG so the assert must be restricted to DEBUG // as well // If the authentication module does CBT, we require that it also caches channel bindings. System.Diagnostics.Debug.Assert(!(binding == null && ModuleRequiresChannelBinding(authenticationModule))); #endif // can also be DBNull.Value, indicating "we previously succeeded without getting a CBT." // (ie, unpatched SSP talking to a partially-hardened server) ChannelBinding channelBinding = binding as ChannelBinding; if (channelBinding != null) { httpWebRequest.CurrentAuthenticationState.TransportContext = new CachedTransportContext(channelBinding); } } // Otherwise invoke the PreAuthenticate method // we're guaranteed that CanPreAuthenticate is true because we check before calling BindModule() Authorization authorization = authenticationModule.PreAuthenticate(request, credentials); if (authorization != null && !authorization.Complete && httpWebRequest != null) { httpWebRequest.CurrentAuthenticationState.Module = authenticationModule; } GlobalLog.Print( "AuthenticationManager::PreAuthenticate() IAuthenticationModule.PreAuthenticate()" + " returned authorization:" + ValidationHelper.HashString(authorization)); return authorization; } /// <devdoc> /// <para>Registers an authentication module with the authentication manager.</para> /// </devdoc> public override void Register(IAuthenticationModule authenticationModule) { if (authenticationModule == null) { throw new ArgumentNullException("authenticationModule"); } GlobalLog.Print( "AuthenticationManager::Register() registering :[" + authenticationModule.AuthenticationType + "]"); string normalizedAuthenticationType = authenticationModule.AuthenticationType.ToUpperInvariant(); this.moduleList.AddOrUpdate( normalizedAuthenticationType, authenticationModule, (key, value) => authenticationModule); } /// <devdoc> /// <para>Unregisters authentication modules for an authentication scheme.</para> /// </devdoc> public override void Unregister(IAuthenticationModule authenticationModule) { if (authenticationModule == null) { throw new ArgumentNullException("authenticationModule"); } GlobalLog.Print( "AuthenticationManager::Unregister() unregistering :[" + authenticationModule.AuthenticationType + "]"); string normalizedAuthenticationType = authenticationModule.AuthenticationType.ToUpperInvariant(); UnregisterInternal(normalizedAuthenticationType); } /// <devdoc> /// <para>Unregisters authentication modules for an authentication scheme.</para> /// </devdoc> public override void Unregister(string authenticationScheme) { if (authenticationScheme == null) { throw new ArgumentNullException("authenticationScheme"); } GlobalLog.Print("AuthenticationManager::Unregister() unregistering :[" + authenticationScheme + "]"); string normalizedAuthenticationType = authenticationScheme.ToUpperInvariant(); UnregisterInternal(normalizedAuthenticationType); } /// <devdoc> /// <para> /// Returns a list of registered authentication modules. /// </para> /// </devdoc> public override IEnumerator RegisteredModules { get { return this.moduleList.Values.GetEnumerator(); } } /// <devdoc> /// <para> /// Binds an authentication response to a request for pre-authentication. /// </para> /// </devdoc> // Create binding between an authorization response and the module // generating that response // This association is used for deciding which module to invoke // for preauthentication purposes public override void BindModule(Uri uri, Authorization response, IAuthenticationModule module) { GlobalLog.Assert( module.CanPreAuthenticate, "AuthenticationManager::BindModule()|module.CanPreAuthenticate == false"); if (response.ProtectionRealm != null) { // The authentication module specified which Uri prefixes // will be preauthenticated string[] prefix = response.ProtectionRealm; for (int k = 0; k < prefix.Length; k++) { // // PrefixLookup is thread-safe // moduleBinding.Add(prefix[k], module.AuthenticationType.ToUpperInvariant()); } } else { // Otherwise use the default policy for "fabricating" // some protection realm generalizing the particular Uri string prefix = generalize(uri); // // PrefixLookup is thread-safe // moduleBinding.Add(prefix, module.AuthenticationType); } } [SuppressMessage( "Microsoft.Design", "CA1031", Justification = "Previous behavior of AuthenticationManager is to catch all exceptions thrown by all " + "IAuthenticationModule plugins.")] #if !TRAVE [SuppressMessage( "Microsoft.Performance", "CA1804", Justification = "Variable exception is used for logging purposes.")] #endif private void InitializeModuleList() { GlobalLog.Print( "AuthenticationManager::Initialize(): calling ConfigurationManager.GetSection()"); // This will never come back as null. Additionally, it will // have the items the user wants available. List<Type> authenticationModuleTypes = AuthenticationModulesSectionInternal.GetSection().AuthenticationModules; // // Should be registered in a growing list of encryption/algorithm strengths // basically, walk through a list of Types, and create new Auth objects // from them. // // order is meaningful here: // load the registered list of auth types // with growing level of encryption. // this.moduleList = new ConcurrentDictionary<string, IAuthenticationModule>(); IAuthenticationModule moduleToRegister; foreach (Type type in authenticationModuleTypes) { try { moduleToRegister = Activator.CreateInstance(type, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, // Binder new object[0], // no arguments CultureInfo.InvariantCulture ) as IAuthenticationModule; if (moduleToRegister != null) { GlobalLog.Print( "WebRequest::Initialize(): Register:" + moduleToRegister.AuthenticationType); string normalizedAuthenticationType = moduleToRegister.AuthenticationType.ToUpperInvariant(); this.moduleList.AddOrUpdate( normalizedAuthenticationType, moduleToRegister, (key, value) => moduleToRegister); } } catch (Exception exception) { // // ignore failure (log exception for debugging) // GlobalLog.Print( "AuthenticationManager::constructor failed to initialize: " + exception.ToString()); } } } private void UnregisterInternal(string normalizedAuthenticationType) { IAuthenticationModule removedModule; if (!this.moduleList.TryRemove(normalizedAuthenticationType, out removedModule)) { throw new InvalidOperationException(SR.GetString(SR.net_authmodulenotregistered)); } } } // class AuthenticationManager2 } // namespace System.Net
using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; using FeedBuilder.Properties; namespace FeedBuilder { public class FeedBuilderSettingsProvider : SettingsProvider, IApplicationSettingsProvider { //XML Root Node private const string SETTINGSROOT = "Settings"; public void SaveAs(string filename) { try { Settings.Default.Save(); string source = Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()); File.Copy(source, filename, true); } catch (Exception ex) { string msg = string.Format("An error occurred while saving the file: {0}{0}{1}", Environment.NewLine, ex.Message); MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void LoadFrom(string filename) { try { string dest = Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()); if (filename == dest) return; Settings.Default.Reset(); File.Copy(filename, dest, true); } catch (Exception ex) { string msg = string.Format("An error occurred while loading the file: {0}{0}{1}", Environment.NewLine, ex.Message); MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public override void Initialize(string name, NameValueCollection col) { base.Initialize(ApplicationName, col); if (!Directory.Exists(GetAppSettingsPath())) { try { Directory.CreateDirectory(GetAppSettingsPath()); } catch (IOException) { } } } public override string ApplicationName { get { return "FeedBuilder"; } //Do nothing set { } } public virtual string GetAppSettingsPath() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationName); } public virtual string GetAppSettingsFilename() { return "Settings.xml"; } public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals) { //Iterate through the settings to be stored //Only dirty settings are included in propvals, and only ones relevant to this provider foreach (SettingsPropertyValue propval in propvals) { SetValue(propval); } try { if (!Directory.Exists(GetAppSettingsPath())) Directory.CreateDirectory(GetAppSettingsPath()); SettingsXML.Save(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename())); } catch (Exception) { //Ignore if cant save, device been ejected } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection props) { //Create new collection of values SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //Iterate through the settings to be retrieved foreach (SettingsProperty setting in props) { SettingsPropertyValue value = new SettingsPropertyValue(setting) { IsDirty = false, SerializedValue = GetValue(setting) }; values.Add(value); } return values; } private XmlDocument m_SettingsXML; private XmlDocument SettingsXML { get { //If we dont hold an xml document, try opening one. //If it doesnt exist then create a new one ready. if (m_SettingsXML == null) { m_SettingsXML = new XmlDocument(); try { m_SettingsXML.Load(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename())); XmlNode node = m_SettingsXML.SelectSingleNode(string.Format("{0}/*", SETTINGSROOT)); // Adopt configuration if it is from another machine. if (node != null && node.Name != Environment.MachineName) { XmlNode machineNode = m_SettingsXML.CreateElement(Environment.MachineName); while (node.ChildNodes.Count > 0) { machineNode.AppendChild(node.FirstChild); } node.ParentNode.AppendChild(machineNode); node.ParentNode.RemoveChild(node); } } catch (Exception) { //Create new document XmlDeclaration dec = m_SettingsXML.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_SettingsXML.AppendChild(dec); XmlNode nodeRoot = m_SettingsXML.CreateNode(XmlNodeType.Element, SETTINGSROOT, ""); m_SettingsXML.AppendChild(nodeRoot); } } return m_SettingsXML; } } private string GetValue(SettingsProperty setting) { string ret = null; try { string path = IsRoaming(setting) ? string.Format("{0}/{1}", SETTINGSROOT, setting.Name) : string.Format("{0}/{1}/{2}", SETTINGSROOT, Environment.MachineName, setting.Name); if (setting.PropertyType.BaseType != null && setting.PropertyType.BaseType.Name == "CollectionBase") { XmlNode selectSingleNode = SettingsXML.SelectSingleNode(path); if (selectSingleNode != null) ret = selectSingleNode.InnerXml; } else { XmlNode singleNode = SettingsXML.SelectSingleNode(path); if (singleNode != null) ret = singleNode.InnerText; } } catch (Exception) { ret = (setting.DefaultValue != null) ? setting.DefaultValue.ToString() : string.Empty; } return ret; } private void SetValue(SettingsPropertyValue propVal) { XmlElement SettingNode; //Determine if the setting is roaming. //If roaming then the value is stored as an element under the root //Otherwise it is stored under a machine name node try { if (IsRoaming(propVal.Property)) { SettingNode = (XmlElement) SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + propVal.Name); } else { SettingNode = (XmlElement) SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName + "/" + propVal.Name); } } catch (Exception) { SettingNode = null; } //Check to see if the node exists, if so then set its new value if ((SettingNode != null)) { //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); } else { if (IsRoaming(propVal.Property)) { //Store the value as an element of the Settings Root Node SettingNode = SettingsXML.CreateElement(propVal.Name); //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(SettingNode); } else { //Its machine specific, store as an element of the machine name node, //creating a new machine name node if one doesnt exist. XmlElement MachineNode; try { MachineNode = (XmlElement) SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName); } catch (Exception) { MachineNode = SettingsXML.CreateElement(Environment.MachineName); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(MachineNode); } if (MachineNode == null) { MachineNode = SettingsXML.CreateElement(Environment.MachineName); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(MachineNode); } SettingNode = SettingsXML.CreateElement(propVal.Name); //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); MachineNode.AppendChild(SettingNode); } } } private void SetSerializedValue(XmlElement node, SettingsPropertyValue propVal) { if (propVal.Property.PropertyType.BaseType != null && propVal.Property.PropertyType.BaseType.Name == "CollectionBase") { StringBuilder builder = new StringBuilder(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); XmlWriterSettings xsettings = new XmlWriterSettings(); ns.Add("", ""); xsettings.OmitXmlDeclaration = true; XmlWriter xmlWriter = XmlWriter.Create(builder, xsettings); XmlSerializer s = new XmlSerializer(propVal.Property.PropertyType); s.Serialize(xmlWriter, propVal.PropertyValue, ns); xmlWriter.Close(); node.InnerXml = builder.ToString(); } else node.InnerText = propVal.SerializedValue != null ? propVal.SerializedValue.ToString() : string.Empty; } private bool IsRoaming(SettingsProperty prop) { //Determine if the setting is marked as Roaming foreach (DictionaryEntry d in prop.Attributes) { Attribute a = (Attribute) d.Value; if (a is SettingsManageabilityAttribute) return true; } return false; } public void Reset(SettingsContext context) { string settingsFilePath = Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()); File.Delete(settingsFilePath); m_SettingsXML = null; } public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property) { return null; } public void Upgrade(SettingsContext context, SettingsPropertyCollection properties) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ItemLevelRecoveryConnectionsOperations operations. /// </summary> internal partial class ItemLevelRecoveryConnectionsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IItemLevelRecoveryConnectionsOperations { /// <summary> /// Initializes a new instance of the ItemLevelRecoveryConnectionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ItemLevelRecoveryConnectionsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Revokes an iSCSI connection which can be used to download a script. /// Executing this script opens a file explorer displaying all recoverable /// files and folders. This is an asynchronous operation. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose files/folders are to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents backed up data. iSCSI connection will /// be revoked for this backed up data. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RevokeWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Revoke", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/revokeInstantItemRecovery").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Provisions a script which invokes an iSCSI connection to the backup data. /// Executing this script opens a file explorer displaying all the /// recoverable files and folders. This is an asynchronous operation. To know /// the status of provisioning, call GetProtectedItemOperationResult API. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose files/folders are to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents backed up data. iSCSI connection will /// be provisioned for this backed up data. /// </param> /// <param name='resourceILRRequest'> /// resource ILR request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> ProvisionWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, ILRRequestResource resourceILRRequest, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId"); } if (resourceILRRequest == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceILRRequest"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("resourceILRRequest", resourceILRRequest); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Provision", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/provisionInstantItemRecovery").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceILRRequest != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceILRRequest, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Globalization; using System.Linq; using System.Numerics; namespace CalcIP { public abstract class IPNetwork<TAddress> where TAddress : struct, IIPAddress<TAddress> { public TAddress BaseAddress { get; } public TAddress SubnetMask { get; } public int? CidrPrefix { get; } public IPNetwork(TAddress address, TAddress subnetMask) { // calculate base address by ANDing address with subnet mask TAddress baseAddress = address.BitwiseAnd(subnetMask); BaseAddress = baseAddress; SubnetMask = subnetMask; CidrPrefix = CalcIPUtils.CidrPrefixFromSubnetMaskBytes(subnetMask.Bytes); } public IPNetwork(TAddress address, int cidrPrefix) : this(address, address.SubnetMaskFromCidrPrefix(cidrPrefix)) { SubnetMask = address.SubnetMaskFromCidrPrefix(cidrPrefix); TAddress baseAddress = address.BitwiseAnd(SubnetMask); BaseAddress = baseAddress; CidrPrefix = cidrPrefix; } public TAddress CiscoWildcard => SubnetMask.BitwiseNot(); public BigInteger AddressCount { get { var ret = BigInteger.One; var two = new BigInteger(2); foreach (byte b in CiscoWildcard.Bytes) { int popCount = CalcIPUtils.BytePopCount[b]; for (int i = 0; i < popCount; ++i) { ret *= two; } } return ret; } } public BigInteger HostCount => AddressCount - 2; // minus network, minus broadcast public TAddress? FirstHostAddress { get { int hostBitsAvailable = CiscoWildcard.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]); if (hostBitsAvailable < 2) { // all ones: the base address is the network // all ones except one zero: 0 is the network, 1 is broadcast // => at least two zeroes necessary for a non-degenerate subnet return null; } var unraveledBaseAddress = CalcIPUtils.UnravelAddress(BaseAddress, SubnetMask); var unraveledFirstHostAddress = unraveledBaseAddress.Add(1); return CalcIPUtils.WeaveAddress(unraveledFirstHostAddress, SubnetMask); } } public TAddress? BroadcastAddress { get { int hostBitsAvailable = CiscoWildcard.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]); if (hostBitsAvailable < 1) { // all ones: the base address is the network // => at least one zero necessary for a subnet with a broadcast address return null; } var unraveledBaseAddress = CalcIPUtils.UnravelAddress(BaseAddress, SubnetMask); var hostCountAddress = BaseAddress .SubnetMaskFromCidrPrefix(BaseAddress.Bytes.Length * 8 - hostBitsAvailable) .BitwiseNot(); var unraveledBroadcastAddress = unraveledBaseAddress.Add(hostCountAddress); return CalcIPUtils.WeaveAddress(unraveledBroadcastAddress, SubnetMask); } } public TAddress? LastHostAddress { get { int hostBitsAvailable = CiscoWildcard.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]); if (hostBitsAvailable < 2) { // all ones: the base address is the network // all ones except one zero: 0 is the network, 1 is broadcast // => at least two zeroes necessary for a non-degenerate subnet return null; } var unraveledBaseAddress = CalcIPUtils.UnravelAddress(BaseAddress, SubnetMask); var hostCountAddress = BaseAddress .SubnetMaskFromCidrPrefix(BaseAddress.Bytes.Length * 8 - hostBitsAvailable) .BitwiseNot(); var unraveledBroadcastAddress = unraveledBaseAddress.Add(hostCountAddress); var unraveledLastHostAddress = unraveledBroadcastAddress.Subtract(1); return CalcIPUtils.WeaveAddress(unraveledLastHostAddress, SubnetMask); } } public TAddress NextSubnetBaseAddress { get { int hostBitsAvailable = CiscoWildcard.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]); var unraveledBaseAddress = CalcIPUtils.UnravelAddress(BaseAddress, SubnetMask); var hostCountAddress = BaseAddress .SubnetMaskFromCidrPrefix(BaseAddress.Bytes.Length * 8 - hostBitsAvailable) .BitwiseNot(); var unraveledBroadcastAddress = unraveledBaseAddress.Add(hostCountAddress); var unraveledNextSubnetBaseAddress = unraveledBroadcastAddress.Add(1); return CalcIPUtils.WeaveAddress(unraveledNextSubnetBaseAddress, SubnetMask); } } public TAddress LastAddressOfSubnet => BroadcastAddress ?? BaseAddress; public override int GetHashCode() { return 2*BaseAddress.GetHashCode() + 3*SubnetMask.GetHashCode(); } public override string ToString() { if (CidrPrefix.HasValue) { return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", BaseAddress, CidrPrefix.Value); } else { return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", BaseAddress, SubnetMask); } } public bool Contains(TAddress address) { return address.BitwiseAnd(SubnetMask).Equals(BaseAddress); } public bool IsSupersetOf(IPNetwork<TAddress> other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } // a network A is a superset of a network B if: // 1. the base address of B bitwise AND with the subnet mask of A returns the base address of A // (B is contained in A) // 2. the subnet mask of A bitwise AND with the subnet mask of B returns the subnet mask of A // (all host bits in B are host bits in A) return (other.BaseAddress.BitwiseAnd(this.SubnetMask).Equals(this.BaseAddress)) && (other.SubnetMask.BitwiseAnd(this.SubnetMask).Equals(this.SubnetMask)); } public bool IsSubsetOf(IPNetwork<TAddress> other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } return other.IsSupersetOf(this); } public bool Intersects(IPNetwork<TAddress> other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } TAddress thisFirst = this.BaseAddress; TAddress thisLast = this.LastAddressOfSubnet; TAddress otherFirst = other.BaseAddress; TAddress otherLast = other.LastAddressOfSubnet; // thisFirst <= otherLast && otherFirst <= thisLast int comp1 = thisFirst.CompareTo(otherLast); int comp2 = otherFirst.CompareTo(thisLast); return comp1 <= 0 && comp2 <= 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundCurrentDirectionDouble() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundCurrentDirectionDouble { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar; private Vector128<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static SimpleUnaryOpTest__RoundCurrentDirectionDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__RoundCurrentDirectionDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.RoundCurrentDirection( Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.RoundCurrentDirection( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.RoundCurrentDirection( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)); var result = Sse41.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionDouble(); var result = Sse41.RoundCurrentDirection(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.RoundCurrentDirection(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirection)}<Double>(Vector128<Double>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }