context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // MassStorageSource.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Collections; using Banshee.IO; using Banshee.Dap; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Library; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Hardware; using Banshee.Playlists.Formats; using Banshee.Playlist; namespace Banshee.Dap.MassStorage { public class MassStorageSource : DapSource { private Banshee.Collection.Gui.ArtworkManager artwork_manager = ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> (); private MassStorageDevice ms_device; private IVolume volume; private IUsbDevice usb_device; public override void DeviceInitialize (IDevice device) { base.DeviceInitialize (device); volume = device as IVolume; if (volume == null || (usb_device = volume.ResolveRootUsbDevice ()) == null) { throw new InvalidDeviceException (); } ms_device = DeviceMapper.Map (this); try { if (ms_device.ShouldIgnoreDevice () || !ms_device.LoadDeviceConfiguration ()) { ms_device = null; } } catch { ms_device = null; } if (!HasMediaCapabilities && ms_device == null) { throw new InvalidDeviceException (); } // Ignore iPods, except ones with .is_audio_player files if (MediaCapabilities != null && MediaCapabilities.IsType ("ipod")) { if (ms_device != null && ms_device.HasIsAudioPlayerFile) { Log.Information ( "Mass Storage Support Loading iPod", "The USB mass storage audio player support is loading an iPod because it has an .is_audio_player file. " + "If you aren't running Rockbox or don't know what you're doing, things might not behave as expected." ); } else { throw new InvalidDeviceException (); } } Name = ms_device == null ? volume.Name : ms_device.Name; mount_point = volume.MountPoint; Initialize (); if (ms_device != null) { ms_device.SourceInitialize (); } AddDapProperties (); // TODO differentiate between Audio Players and normal Disks, and include the size, eg "2GB Audio Player"? //GenericName = Catalog.GetString ("Audio Player"); } private void AddDapProperties () { if (AudioFolders.Length > 0 && !String.IsNullOrEmpty (AudioFolders[0])) { AddDapProperty (String.Format ( Catalog.GetPluralString ("Audio Folder", "Audio Folders", AudioFolders.Length), AudioFolders.Length), System.String.Join ("\n", AudioFolders) ); } if (VideoFolders.Length > 0 && !String.IsNullOrEmpty (VideoFolders[0])) { AddDapProperty (String.Format ( Catalog.GetPluralString ("Video Folder", "Video Folders", VideoFolders.Length), VideoFolders.Length), System.String.Join ("\n", VideoFolders) ); } if (FolderDepth != -1) { AddDapProperty (Catalog.GetString ("Required Folder Depth"), FolderDepth.ToString ()); } AddYesNoDapProperty (Catalog.GetString ("Supports Playlists"), PlaylistTypes.Count > 0); /*if (AcceptableMimeTypes.Length > 0) { AddDapProperty (String.Format ( Catalog.GetPluralString ("Audio Format", "Audio Formats", PlaybackFormats.Length), PlaybackFormats.Length), System.String.Join (", ", PlaybackFormats) ); }*/ } private System.Threading.ManualResetEvent import_reset_event; private DatabaseImportManager importer; // WARNING: This will be called from a thread! protected override void LoadFromDevice () { import_reset_event = new System.Threading.ManualResetEvent (false); importer = new DatabaseImportManager (this) { KeepUserJobHidden = true, SkipHiddenChildren = false }; importer.Finished += OnImportFinished; foreach (string audio_folder in BaseDirectories) { importer.Enqueue (audio_folder); } import_reset_event.WaitOne (); } private void OnImportFinished (object o, EventArgs args) { importer.Finished -= OnImportFinished; if (CanSyncPlaylists) { var insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand ( "INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)"); int [] psources = new int [] {DbId}; foreach (string playlist_path in PlaylistFiles) { IPlaylistFormat loaded_playlist = PlaylistFileUtil.Load (playlist_path, new Uri (PlaylistsPath)); if (loaded_playlist == null) continue; PlaylistSource playlist = new PlaylistSource (System.IO.Path.GetFileNameWithoutExtension (playlist_path), this); playlist.Save (); //Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = true; foreach (Dictionary<string, object> element in loaded_playlist.Elements) { string track_path = (element["uri"] as Uri).LocalPath; int track_id = DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (track_path), psources); if (track_id == 0) { Log.DebugFormat ("Failed to find track {0} in DAP library to load it into playlist {1}", track_path, playlist_path); } else { ServiceManager.DbConnection.Execute (insert_cmd, playlist.DbId, track_id); } } //Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = false; playlist.UpdateCounts (); AddChildSource (playlist); } } import_reset_event.Set (); } public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job) { if (track.PrimarySourceId == DbId) { Banshee.IO.File.Copy (track.Uri, uri, false); } } public override void Import () { var importer = new LibraryImportManager (true) { SkipHiddenChildren = false }; foreach (string audio_folder in BaseDirectories) { importer.Enqueue (audio_folder); } } public IVolume Volume { get { return volume; } } public IUsbDevice UsbDevice { get { return usb_device; } } private string mount_point; public override string BaseDirectory { get { return mount_point; } } protected override IDeviceMediaCapabilities MediaCapabilities { get { return ms_device ?? ( volume.Parent == null ? base.MediaCapabilities : volume.Parent.MediaCapabilities ?? base.MediaCapabilities ); } } #region Properties and Methods for Supporting Syncing of Playlists private string playlists_path; private string PlaylistsPath { get { if (playlists_path == null) { if (MediaCapabilities == null || MediaCapabilities.PlaylistPath == null) { playlists_path = WritePath; } else { playlists_path = System.IO.Path.Combine (WritePath, MediaCapabilities.PlaylistPath); playlists_path = playlists_path.Replace ("%File", String.Empty); } if (!Directory.Exists (playlists_path)) { Directory.Create (playlists_path); } } return playlists_path; } } private string [] playlist_formats; private string [] PlaylistFormats { get { if (playlist_formats == null && MediaCapabilities != null) { playlist_formats = MediaCapabilities.PlaylistFormats; } return playlist_formats; } set { playlist_formats = value; } } private List<PlaylistFormatDescription> playlist_types; private IList<PlaylistFormatDescription> PlaylistTypes { get { if (playlist_types == null) { playlist_types = new List<PlaylistFormatDescription> (); if (PlaylistFormats != null) { foreach (PlaylistFormatDescription desc in Banshee.Playlist.PlaylistFileUtil.ExportFormats) { foreach (string mimetype in desc.MimeTypes) { if (Array.IndexOf (PlaylistFormats, mimetype) != -1) { playlist_types.Add (desc); break; } } } } } SupportsPlaylists &= CanSyncPlaylists; return playlist_types; } } private IEnumerable<string> PlaylistFiles { get { foreach (string file_name in Directory.GetFiles (PlaylistsPath)) { foreach (PlaylistFormatDescription desc in playlist_types) { if (file_name.EndsWith (desc.FileExtension)) { yield return file_name; break; } } } } } private bool CanSyncPlaylists { get { return PlaylistsPath != null && playlist_types.Count > 0; } } public override void SyncPlaylists () { if (!CanSyncPlaylists) { return; } foreach (string file_name in PlaylistFiles) { try { Banshee.IO.File.Delete (new SafeUri (file_name)); } catch (Exception e) { Log.Exception (e); } } // Add playlists from Banshee to the device PlaylistFormatBase playlist_format = null; List<Source> children = new List<Source> (Children); foreach (Source child in children) { PlaylistSource from = child as PlaylistSource; string escaped_name = StringUtil.EscapeFilename (child.Name); if (from != null && !String.IsNullOrEmpty (escaped_name)) { from.Reload (); if (playlist_format == null) { playlist_format = Activator.CreateInstance (PlaylistTypes[0].Type) as PlaylistFormatBase; } SafeUri playlist_path = new SafeUri (System.IO.Path.Combine ( PlaylistsPath, String.Format ("{0}.{1}", escaped_name, PlaylistTypes[0].FileExtension))); System.IO.Stream stream = null; try { stream = Banshee.IO.File.OpenWrite (playlist_path, true); playlist_format.BaseUri = new Uri (PlaylistsPath); playlist_format.Save (stream, from); } catch (Exception e) { Log.Exception (e); } finally { stream.Close (); } } } } #endregion protected override string [] GetIconNames () { string [] names = ms_device != null ? ms_device.GetIconNames () : null; return names == null ? base.GetIconNames () : names; } public override long BytesUsed { get { return BytesCapacity - volume.Available; } } public override long BytesCapacity { get { return (long) volume.Capacity; } } private bool had_write_error = false; public override bool IsReadOnly { get { return volume.IsReadOnly || had_write_error; } } private string write_path = null; public string WritePath { get { if (write_path == null) { write_path = BaseDirectory; // According to the HAL spec, the first folder listed in the audio_folders property // is the folder to write files to. if (AudioFolders.Length > 0) { write_path = Hyena.Paths.Combine (write_path, AudioFolders[0]); } } return write_path; } set { write_path = value; } } private string write_path_video = null; public string WritePathVideo { get { if (write_path_video == null) { write_path_video = BaseDirectory; // Some Devices May Have a Separate Video Directory if (VideoFolders.Length > 0) { write_path_video = Hyena.Paths.Combine (write_path_video, VideoFolders[0]); } else if (AudioFolders.Length > 0) { write_path_video = Hyena.Paths.Combine (write_path_video, AudioFolders[0]); write_path_video = Hyena.Paths.Combine (write_path_video, "Videos"); } } return write_path_video; } set { write_path_video = value; } } private string [] audio_folders; protected string [] AudioFolders { get { if (audio_folders == null) { audio_folders = HasMediaCapabilities ? MediaCapabilities.AudioFolders : new string[0]; } return audio_folders; } set { audio_folders = value; } } private string [] video_folders; protected string [] VideoFolders { get { if (video_folders == null) { video_folders = HasMediaCapabilities ? MediaCapabilities.VideoFolders : new string[0]; } return video_folders; } set { video_folders = value; } } protected IEnumerable<string> BaseDirectories { get { if (AudioFolders.Length == 0) { yield return BaseDirectory; } else { foreach (string audio_folder in AudioFolders) { yield return Paths.Combine (BaseDirectory, audio_folder); } } } } private int folder_depth = -1; protected int FolderDepth { get { if (folder_depth == -1) { folder_depth = HasMediaCapabilities ? MediaCapabilities.FolderDepth : -1; } return folder_depth; } set { folder_depth = value; } } private int cover_art_size = -1; protected int CoverArtSize { get { if (cover_art_size == -1) { cover_art_size = HasMediaCapabilities ? MediaCapabilities.CoverArtSize : 0; } return cover_art_size; } set { cover_art_size = value; } } private string cover_art_file_name = null; protected string CoverArtFileName { get { if (cover_art_file_name == null) { cover_art_file_name = HasMediaCapabilities ? MediaCapabilities.CoverArtFileName : null; } return cover_art_file_name; } set { cover_art_file_name = value; } } private string cover_art_file_type = null; protected string CoverArtFileType { get { if (cover_art_file_type == null) { cover_art_file_type = HasMediaCapabilities ? MediaCapabilities.CoverArtFileType : null; } return cover_art_file_type; } set { cover_art_file_type = value; } } protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri) { if (track.PrimarySourceId == DbId) return; SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (fromUri.LocalPath))); // If it already is on the device but it's out of date, remove it //if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri)) //RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri))); if (!File.Exists (new_uri)) { Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath)); File.Copy (fromUri, new_uri, false); DatabaseTrackInfo copied_track = new DatabaseTrackInfo (track); copied_track.PrimarySource = this; copied_track.Uri = new_uri; // Write the metadata in db to the file on the DAP if it has changed since file was modified // to ensure that when we load it next time, it's data will match what's in the database // and the MetadataHash will actually match. We do this by comparing the time // stamps on files for last update of the db metadata vs the sync to file. // The equals on the inequality below is necessary for podcasts who often have a sync and // update time that are the same to the second, even though the album metadata has changed in the // DB to the feedname instead of what is in the file. It should be noted that writing the metadata // is a small fraction of the total copy time anyway. if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime (track.FileModifiedStamp)) { Log.DebugFormat ("Copying Metadata to File Since Sync time >= Updated Time"); bool write_metadata = Metadata.SaveTrackMetadataService.WriteMetadataEnabled.Value; bool write_ratings_and_playcounts = Metadata.SaveTrackMetadataService.WriteRatingsAndPlayCountsEnabled.Value; Banshee.Streaming.StreamTagger.SaveToFile (copied_track, write_metadata, write_ratings_and_playcounts); } copied_track.Save (false); } if (CoverArtSize > -1 && !String.IsNullOrEmpty (CoverArtFileType) && !String.IsNullOrEmpty (CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0)) { SafeUri cover_uri = new SafeUri (System.IO.Path.Combine (System.IO.Path.GetDirectoryName (new_uri.LocalPath), CoverArtFileName)); string coverart_id = track.ArtworkId; if (!File.Exists (cover_uri) && CoverArtSpec.CoverExists (coverart_id)) { Gdk.Pixbuf pic = null; if (CoverArtSize == 0) { if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg") { SafeUri local_cover_uri = new SafeUri (Banshee.Base.CoverArtSpec.GetPath (coverart_id)); Banshee.IO.File.Copy (local_cover_uri, cover_uri, false); } else { pic = artwork_manager.LookupPixbuf (coverart_id); } } else { pic = artwork_manager.LookupScalePixbuf (coverart_id, CoverArtSize); } if (pic != null) { try { byte [] bytes = pic.SaveToBuffer (CoverArtFileType); System.IO.Stream cover_art_file = File.OpenWrite (cover_uri, true); cover_art_file.Write (bytes, 0, bytes.Length); cover_art_file.Close (); } catch (GLib.GException){ Log.DebugFormat ("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType); } finally { Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic); } } } } } protected override bool DeleteTrack (DatabaseTrackInfo track) { try { if (ms_device != null && !ms_device.DeleteTrackHook (track)) { return false; } string track_file = System.IO.Path.GetFileName (track.Uri.LocalPath); string track_dir = System.IO.Path.GetDirectoryName (track.Uri.LocalPath); int files = 0; // Count how many files remain in the track's directory, // excluding self or cover art foreach (string file in System.IO.Directory.GetFiles (track_dir)) { string relative = System.IO.Path.GetFileName (file); if (relative != track_file && relative != CoverArtFileName) { files++; } } // If we are the last track, go ahead and delete the artwork // to ensure that the directory tree can get trimmed away too if (files == 0 && CoverArtFileName != null) { System.IO.File.Delete (Paths.Combine (track_dir, CoverArtFileName)); } Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri); } catch (System.IO.FileNotFoundException) { } catch (System.IO.DirectoryNotFoundException) { } return true; } protected override void Eject () { base.Eject (); if (volume.CanUnmount) { volume.Unmount (); } if (volume.CanEject) { volume.Eject (); } } protected override bool CanHandleDeviceCommand (DeviceCommand command) { try { SafeUri uri = new SafeUri (command.DeviceId); return BaseDirectory.StartsWith (uri.LocalPath); } catch { return false; } } private string GetTrackPath (TrackInfo track, string ext) { string file_path = null; if (track.HasAttribute (TrackMediaAttributes.Podcast)) { string album = FileNamePattern.Escape (track.DisplayAlbumTitle); string title = FileNamePattern.Escape (track.DisplayTrackTitle); file_path = System.IO.Path.Combine ("Podcasts", album); file_path = System.IO.Path.Combine (file_path, title); } else if (track.HasAttribute (TrackMediaAttributes.VideoStream)) { string album = FileNamePattern.Escape (track.DisplayAlbumTitle); string title = FileNamePattern.Escape (track.DisplayTrackTitle); file_path = System.IO.Path.Combine (album, title); } else if (ms_device == null || !ms_device.GetTrackPath (track, out file_path)) { // If the folder_depth property exists, we have to put the files in a hiearchy of // the exact given depth (not including the mount point/audio_folder). if (FolderDepth != -1) { int depth = FolderDepth; string album_artist = FileNamePattern.Escape (track.DisplayAlbumArtistName); string track_album = FileNamePattern.Escape (track.DisplayAlbumTitle); string track_number = FileNamePattern.Escape (String.Format ("{0:00}", track.TrackNumber)); string track_title = FileNamePattern.Escape (track.DisplayTrackTitle); if (depth == 0) { // Artist - Album - 01 - Title string track_artist = FileNamePattern.Escape (track.DisplayArtistName); file_path = String.Format ("{0} - {1} - {2} - {3}", track_artist, track_album, track_number, track_title); } else if (depth == 1) { // Artist - Album/01 - Title file_path = String.Format ("{0} - {1}", album_artist, track_album); file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title)); } else if (depth == 2) { // Artist/Album/01 - Title file_path = album_artist; file_path = System.IO.Path.Combine (file_path, track_album); file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title)); } else { // If the *required* depth is more than 2..go nuts! for (int i = 0; i < depth - 2; i++) { if (i == 0) { file_path = album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim (); } else { file_path = System.IO.Path.Combine (file_path, album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ()); } } // Finally add on the Artist/Album/01 - Track file_path = System.IO.Path.Combine (file_path, album_artist); file_path = System.IO.Path.Combine (file_path, track_album); file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title)); } } else { file_path = MusicLibrarySource.MusicFileNamePattern.CreateFromTrackInfo (track); } } if (track.HasAttribute (TrackMediaAttributes.VideoStream)) { file_path = System.IO.Path.Combine (WritePathVideo, file_path); } else { file_path = System.IO.Path.Combine (WritePath, file_path); } file_path += ext; return file_path; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Web; using ASC.Common.Web; using ASC.Core; using ASC.Core.Tenants; using ASC.Files.Core; using ASC.MessagingSystem; using ASC.Security.Cryptography; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Helpers; using ASC.Web.Files.Resources; using ASC.Web.Files.Utils; using ASC.Web.Studio.Core; using Newtonsoft.Json; using File = ASC.Files.Core.File; namespace ASC.Web.Files.HttpHandlers { public class ChunkedUploaderHandler : AbstractHttpAsyncHandler { public override void OnProcessRequest(HttpContext context) { if (context.Request.HttpMethod == "OPTIONS") { context.Response.StatusCode = 200; context.Response.End(); return; } try { var request = new ChunkedRequestHelper(context.Request); if (!TryAuthorize(request)) { WriteError(context, "Can't authorize given initiate session request or session with specified upload id already expired"); return; } if (CoreContext.TenantManager.GetCurrentTenant().Status != TenantStatus.Active) { WriteError(context, "Can't perform upload for deleted or transfering portals"); return; } switch (request.Type) { case ChunkedRequestType.Abort: FileUploader.AbortUpload(request.UploadId); WriteSuccess(context, null); return; case ChunkedRequestType.Initiate: var createdSession = FileUploader.InitiateUpload(request.FolderId, request.FileId, request.FileName, request.FileSize, request.Encrypted); WriteSuccess(context, ToResponseObject(createdSession, true)); return; case ChunkedRequestType.Upload: var resumedSession = FileUploader.UploadChunk(request.UploadId, request.ChunkStream, request.ChunkSize); if (resumedSession.BytesUploaded == resumedSession.BytesTotal) { WriteSuccess(context, ToResponseObject(resumedSession.File), (int)HttpStatusCode.Created); FilesMessageService.Send(resumedSession.File, context.Request, MessageAction.FileUploaded, resumedSession.File.Title); } else { WriteSuccess(context, ToResponseObject(resumedSession)); } return; default: WriteError(context, "Unknown request type."); return; } } catch (FileNotFoundException error) { Global.Logger.Error(error); WriteError(context, FilesCommonResource.ErrorMassage_FileNotFound); } catch (Exception error) { Global.Logger.Error(error); WriteError(context, error.Message); } } private static bool TryAuthorize(ChunkedRequestHelper request) { if (request.Type == ChunkedRequestType.Initiate) { CoreContext.TenantManager.SetCurrentTenant(request.TenantId); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(request.AuthKey)); if (request.CultureInfo != null) Thread.CurrentThread.CurrentUICulture = request.CultureInfo; return true; } if (!string.IsNullOrEmpty(request.UploadId)) { var uploadSession = ChunkedUploadSessionHolder.GetSession(request.UploadId); if (uploadSession != null) { CoreContext.TenantManager.SetCurrentTenant(uploadSession.TenantId); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(uploadSession.UserId)); var culture = SetupInfo.GetPersonalCulture(uploadSession.CultureName).Value; if (culture != null) Thread.CurrentThread.CurrentUICulture = culture; return true; } } return false; } private static void WriteError(HttpContext context, string message) { WriteResponse(context, false, null, message, (int)HttpStatusCode.OK); } private static void WriteSuccess(HttpContext context, object data, int statusCode = (int)HttpStatusCode.OK) { WriteResponse(context, true, data, string.Empty, statusCode); } private static void WriteResponse(HttpContext context, bool success, object data, string message, int statusCode) { context.Response.StatusCode = statusCode; context.Response.Write(JsonConvert.SerializeObject(new { success, data, message })); context.Response.ContentType = "application/json"; } public static object ToResponseObject(ChunkedUploadSession session, bool appendBreadCrumbs = false) { var pathFolder = appendBreadCrumbs ? EntryManager.GetBreadCrumbs(session.FolderId).Select(f => { //todo: check how? if (f == null) { Global.Logger.ErrorFormat("GetBreadCrumbs {0} with null", session.FolderId); return string.Empty; } return f.ID; }) : new List<object> { session.FolderId }; return new { id = session.Id, path = pathFolder, created = session.Created, expired = session.Expired, location = session.Location, bytes_uploaded = session.BytesUploaded, bytes_total = session.BytesTotal }; } private static object ToResponseObject(File file) { return new { id = file.ID, folderId = file.FolderID, version = file.Version, title = file.Title, provider_key = file.ProviderKey, uploaded = true }; } private enum ChunkedRequestType { None, Initiate, Abort, Upload } [DebuggerDisplay("{Type} ({UploadId})")] private class ChunkedRequestHelper { private readonly HttpRequest _request; private HttpPostedFileBase _file; private int? _tenantId; private long? _fileContentLength; private Guid? _authKey; private CultureInfo _cultureInfo; public ChunkedRequestType Type { get { if (_request["initiate"] == "true" && IsAuthDataSet() && IsFileDataSet()) return ChunkedRequestType.Initiate; if (_request["abort"] == "true" && !string.IsNullOrEmpty(UploadId)) return ChunkedRequestType.Abort; return !string.IsNullOrEmpty(UploadId) ? ChunkedRequestType.Upload : ChunkedRequestType.None; } } public string UploadId { get { return _request["uid"]; } } public int TenantId { get { if (!_tenantId.HasValue) { int v; if (int.TryParse(_request["tid"], out v)) _tenantId = v; else _tenantId = -1; } return _tenantId.Value; } } public Guid AuthKey { get { if (!_authKey.HasValue) { _authKey = !string.IsNullOrEmpty(_request["userid"]) ? new Guid(InstanceCrypto.Decrypt(_request["userid"])) : Guid.Empty; } return _authKey.Value; } } public string FolderId { get { return _request[FilesLinkUtility.FolderId]; } } public string FileId { get { return _request[FilesLinkUtility.FileId]; } } public string FileName { get { return _request[FilesLinkUtility.FileTitle]; } } public long FileSize { get { if (!_fileContentLength.HasValue) { long v; long.TryParse(_request["fileSize"], out v); _fileContentLength = v; } return _fileContentLength.Value; } } public long ChunkSize { get { return File.ContentLength; } } public Stream ChunkStream { get { return File.InputStream; } } public CultureInfo CultureInfo { get { if (_cultureInfo != null) return _cultureInfo; var culture = _request["culture"]; if (string.IsNullOrEmpty(culture)) culture = "en-US"; return _cultureInfo = SetupInfo.GetPersonalCulture(culture).Value; } } public bool Encrypted { get { return _request["encrypted"] == "true"; } } private HttpPostedFileBase File { get { if (_file != null) return _file; if (_request.Files.Count > 0) return _file = new HttpPostedFileWrapper(_request.Files[0]); throw new Exception("HttpRequest.Files is empty"); } } public ChunkedRequestHelper(HttpRequest request) { if (request == null) throw new ArgumentNullException("request"); _request = request; } private bool IsAuthDataSet() { return TenantId > -1 && AuthKey != Guid.Empty; } private bool IsFileDataSet() { return !string.IsNullOrEmpty(FileName) && !string.IsNullOrEmpty(FolderId); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: This is the implementation of the DataCollector /// functionality. To enable safe access to the DataCollector from /// untrusted code, there is one thread-local instance of this structure /// per thread. The instance must be Enabled before any data is written to /// it. The instance must be Finished before the data is passed to /// EventWrite. The instance must be Disabled before the arrays referenced /// by the pointers are freed or unpinned. /// </summary> internal unsafe struct DataCollector { [ThreadStatic] internal static DataCollector ThreadInstance; private byte* scratchEnd; private EventSource.EventData* datasEnd; private GCHandle* pinsEnd; private EventSource.EventData* datasStart; private byte* scratch; private EventSource.EventData* datas; private GCHandle* pins; private byte[] buffer; private int bufferPos; private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this. private bool writingScalars; internal void Enable( byte* scratch, int scratchSize, EventSource.EventData* datas, int dataCount, GCHandle* pins, int pinCount) { this.datasStart = datas; this.scratchEnd = scratch + scratchSize; this.datasEnd = datas + dataCount; this.pinsEnd = pins + pinCount; this.scratch = scratch; this.datas = datas; this.pins = pins; this.writingScalars = false; } internal void Disable() { this = new DataCollector(); } /// <summary> /// Completes the list of scalars. Finish must be called before the data /// descriptor array is passed to EventWrite. /// </summary> /// <returns> /// A pointer to the next unused data descriptor, or datasEnd if they were /// all used. (Descriptors may be unused if a string or array was null.) /// </returns> internal EventSource.EventData* Finish() { this.ScalarsEnd(); return this.datas; } internal void AddScalar(void* value, int size) { var pb = (byte*)value; if (this.bufferNesting == 0) { var scratchOld = this.scratch; var scratchNew = scratchOld + size; if (this.scratchEnd < scratchNew) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange")); } this.ScalarsBegin(); this.scratch = scratchNew; for (int i = 0; i != size; i++) { scratchOld[i] = pb[i]; } } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); for (int i = 0; i != size; i++, oldPos++) { this.buffer[oldPos] = pb[i]; } } } internal void AddBinary(string value, int size) { if (size > ushort.MaxValue) { size = ushort.MaxValue - 1; } if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&size, 2); if (size != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); fixed (void* p = value) { Marshal.Copy((IntPtr)p, this.buffer, oldPos, size); } } } } internal void AddBinary(Array value, int size) { this.AddArray(value, size, 1); } internal void AddArray(Array value, int length, int itemSize) { if (length > ushort.MaxValue) { length = ushort.MaxValue; } var size = length * itemSize; if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&length, 2); if (length != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } } /// <summary> /// Marks the start of a non-blittable array or enumerable. /// </summary> /// <returns>Bookmark to be passed to EndBufferedArray.</returns> internal int BeginBufferedArray() { this.BeginBuffered(); this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable) return this.bufferPos; } /// <summary> /// Marks the end of a non-blittable array or enumerable. /// </summary> /// <param name="bookmark">The value returned by BeginBufferedArray.</param> /// <param name="count">The number of items in the array.</param> internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); } /// <summary> /// Marks the start of dynamically-buffered data. /// </summary> internal void BeginBuffered() { this.ScalarsEnd(); this.bufferNesting += 1; } /// <summary> /// Marks the end of dynamically-buffered data. /// </summary> internal void EndBuffered() { this.bufferNesting -= 1; if (this.bufferNesting == 0) { /* TODO (perf): consider coalescing adjacent buffered regions into a single buffer, similar to what we're already doing for adjacent scalars. In addition, if a type contains a buffered region adjacent to a blittable array, and the blittable array is small, it would be more efficient to buffer the array instead of pinning it. */ this.EnsureBuffer(); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; } } private void EnsureBuffer() { var required = this.bufferPos; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void EnsureBuffer(int additionalSize) { var required = this.bufferPos + additionalSize; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void GrowBuffer(int required) { var newSize = this.buffer == null ? 64 : this.buffer.Length; do { newSize *= 2; } while (newSize < required); Array.Resize(ref this.buffer, newSize); } private void PinArray(object value, int size) { var pinsTemp = this.pins; if (this.pinsEnd <= pinsTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange")); } var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } this.pins = pinsTemp + 1; this.datas = datasTemp + 1; *pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned); datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject(); datasTemp->m_Size = size; } private void ScalarsBegin() { if (!this.writingScalars) { var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch; this.writingScalars = true; } } private void ScalarsEnd() { if (this.writingScalars) { var datasTemp = this.datas; datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr)); this.datas = datasTemp + 1; this.writingScalars = false; } } } }
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_CheckPointDS { public PRO_CheckPointDS() { } private const string THIS = "PCSComProduction.DCP.DS.PRO_CheckPointDS"; /// <summary> /// This method uses to add data to PRO_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { PRO_CheckPointVO objObject = (PRO_CheckPointVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO PRO_CheckPoint(" + PRO_CheckPointTable.PRODUCTID_FLD + "," + PRO_CheckPointTable.CCNID_FLD + "," + PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + ")" + "VALUES(?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.WORKCENTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.SAMPLEPATTERN_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.SAMPLEPATTERN_FLD].Value = objObject.SamplePattern; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.SAMPLERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_CheckPointTable.SAMPLERATE_FLD].Value = objObject.SampleRate; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.DELAYTIME_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_CheckPointTable.DELAYTIME_FLD].Value = objObject.DelayTime; 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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + PRO_CheckPointTable.TABLE_NAME + " WHERE " + "CheckPointID" + "=" + 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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 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_CheckPointTable.CHECKPOINTID_FLD + "," + PRO_CheckPointTable.PRODUCTID_FLD + "," + PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + " FROM " + PRO_CheckPointTable.TABLE_NAME +" WHERE " + PRO_CheckPointTable.CHECKPOINTID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_CheckPointVO objObject = new PRO_CheckPointVO(); while (odrPCS.Read()) { objObject.CheckPointID = int.Parse(odrPCS[PRO_CheckPointTable.CHECKPOINTID_FLD].ToString().Trim()); objObject.ProductID = int.Parse(odrPCS[PRO_CheckPointTable.PRODUCTID_FLD].ToString().Trim()); objObject.WorkCenterID = int.Parse(odrPCS[PRO_CheckPointTable.WORKCENTERID_FLD].ToString().Trim()); objObject.SamplePattern = int.Parse(odrPCS[PRO_CheckPointTable.SAMPLEPATTERN_FLD].ToString().Trim()); objObject.SampleRate = Decimal.Parse(odrPCS[PRO_CheckPointTable.SAMPLERATE_FLD].ToString().Trim()); objObject.DelayTime = Decimal.Parse(odrPCS[PRO_CheckPointTable.DELAYTIME_FLD].ToString().Trim()); } 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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; PRO_CheckPointVO objObject = (PRO_CheckPointVO) 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_CheckPoint SET " + PRO_CheckPointTable.PRODUCTID_FLD + "= ?" + "," + PRO_CheckPointTable.WORKCENTERID_FLD + "= ?" + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "= ?" + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "= ?" + "," + PRO_CheckPointTable.DELAYTIME_FLD + "= ?" +" WHERE " + PRO_CheckPointTable.CHECKPOINTID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.WORKCENTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.SAMPLEPATTERN_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.SAMPLEPATTERN_FLD].Value = objObject.SamplePattern; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.SAMPLERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_CheckPointTable.SAMPLERATE_FLD].Value = objObject.SampleRate; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.DELAYTIME_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_CheckPointTable.DELAYTIME_FLD].Value = objObject.DelayTime; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_CheckPointTable.CHECKPOINTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_CheckPointTable.CHECKPOINTID_FLD].Value = objObject.CheckPointID; 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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 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_CheckPointTable.CHECKPOINTID_FLD + "," + PRO_CheckPointTable.PRODUCTID_FLD + "," + PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + " FROM " + PRO_CheckPointTable.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_CheckPointTable.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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 2005 /// </History> public DataSet ListByCCNID(int pintCCNID) { const string METHOD_NAME = THIS + ".ListByCCNID()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT " + "ITR."+ MST_WorkCenterTable.CODE_FLD + " As " + MST_WorkCenterTable.TABLE_NAME + MST_WorkCenterTable.CODE_FLD + "," + "CK."+ PRO_CheckPointTable.CCNID_FLD + "," + PRO_CheckPointTable.CHECKPOINTID_FLD + "," + "CK."+ PRO_CheckPointTable.PRODUCTID_FLD + "," + "P." + ITM_ProductTable.CODE_FLD + "," + "P." + ITM_ProductTable.DESCRIPTION_FLD + "," + "P." + ITM_ProductTable.REVISION_FLD + "," + "UM." + MST_UnitOfMeasureTable.CODE_FLD + " as " + MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD + "," + "ITR."+ PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + " FROM " + PRO_CheckPointTable.TABLE_NAME + " CK " + " INNER JOIN " + ITM_ProductTable.TABLE_NAME + " P on CK." + PRO_CheckPointTable.PRODUCTID_FLD + "=" + "P." + ITM_ProductTable.PRODUCTID_FLD + " INNER JOIN " + MST_UnitOfMeasureTable.TABLE_NAME + " UM on UM." + MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD + "=" + "P." + ITM_ProductTable.STOCKUMID_FLD + " INNER JOIN " + MST_WorkCenterTable.TABLE_NAME + " ITR on ITR." + MST_WorkCenterTable.WORKCENTERID_FLD + "=" + "CK." + PRO_CheckPointTable.WORKCENTERID_FLD + " WHERE CK." + PRO_CheckPointTable.CCNID_FLD + "=" + pintCCNID; 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_CheckPointTable.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_CheckPoint by CCNID, WorkCenterID /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 2005 /// </History> public DataSet ListByWorkCenterID(int pintCCNID, int pintWorkCenterID) { const string METHOD_NAME = THIS + ".ListByWorkCenterID()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT " + "ITR."+ MST_WorkCenterTable.CODE_FLD + " As " + MST_WorkCenterTable.TABLE_NAME + MST_WorkCenterTable.CODE_FLD + "," + "CK."+ PRO_CheckPointTable.CCNID_FLD + "," + PRO_CheckPointTable.CHECKPOINTID_FLD + "," + "CK."+ PRO_CheckPointTable.PRODUCTID_FLD + "," + "P." + ITM_ProductTable.CODE_FLD + "," + "P." + ITM_ProductTable.DESCRIPTION_FLD + "," + "P." + ITM_ProductTable.REVISION_FLD + "," + "CA." + ITM_CategoryTable.CODE_FLD + " ITM_CategoryCode," + "UM." + MST_UnitOfMeasureTable.CODE_FLD + " as " + MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD + "," + "ITR."+ PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + " FROM " + PRO_CheckPointTable.TABLE_NAME + " CK " + " INNER JOIN " + ITM_ProductTable.TABLE_NAME + " P on CK." + PRO_CheckPointTable.PRODUCTID_FLD + "=" + "P." + ITM_ProductTable.PRODUCTID_FLD + " INNER JOIN " + MST_UnitOfMeasureTable.TABLE_NAME + " UM on UM." + MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD + "=" + "P." + ITM_ProductTable.STOCKUMID_FLD + " INNER JOIN " + MST_WorkCenterTable.TABLE_NAME + " ITR on ITR." + MST_WorkCenterTable.WORKCENTERID_FLD + "=" + "CK." + PRO_CheckPointTable.WORKCENTERID_FLD + " LEFT JOIN " + ITM_CategoryTable.TABLE_NAME + " CA ON CA." + ITM_CategoryTable.CATEGORYID_FLD + " = P." + ITM_ProductTable.CATEGORYID_FLD + " WHERE CK." + PRO_CheckPointTable.CCNID_FLD + "=" + pintCCNID + " AND CK." + PRO_CheckPointTable.WORKCENTERID_FLD + "=" + pintWorkCenterID; 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_CheckPointTable.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_CheckPoint /// </summary> /// <Inputs> /// PRO_CheckPointVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Friday, August 12, 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_CheckPointTable.CHECKPOINTID_FLD + "," + PRO_CheckPointTable.PRODUCTID_FLD + "," + PRO_CheckPointTable.CCNID_FLD + "," + PRO_CheckPointTable.WORKCENTERID_FLD + "," + PRO_CheckPointTable.SAMPLEPATTERN_FLD + "," + PRO_CheckPointTable.SAMPLERATE_FLD + "," + PRO_CheckPointTable.DELAYTIME_FLD + " FROM " + PRO_CheckPointTable.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_CheckPointTable.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(); } } } } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using static Microsoft.AspNetCore.Components.BindConverter; namespace Microsoft.AspNetCore.Components { /// <summary> /// Contains extension methods for two-way binding using <see cref="EventCallback"/>. For internal use only. /// </summary> // // NOTE: for number parsing, the HTML5 spec dictates that <input type="number"> the DOM will represent // number values as floating point numbers using `.` as the period separator. This is NOT culture sensitive. // Put another way, the user might see `,` as their decimal separator, but the value available in events // to JS code is always similar to what .NET parses with InvariantCulture. // // See: https://www.w3.org/TR/html5/sec-forms.html#number-state-typenumber // See: https://www.w3.org/TR/html5/infrastructure.html#valid-floating-point-number // // For now we're not necessarily handling this correctly since we parse the same way for number and text. public static class EventCallbackFactoryBinderExtensions { /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<string?> setter, string existingValue, CultureInfo? culture = null) { return CreateBinderCore<string?>(factory, receiver, setter, culture, ConvertToString); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<bool> setter, bool existingValue, CultureInfo? culture = null) { return CreateBinderCore<bool>(factory, receiver, setter, culture, ConvertToBool); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<bool?> setter, bool? existingValue, CultureInfo? culture = null) { return CreateBinderCore<bool?>(factory, receiver, setter, culture, ConvertToNullableBool); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<int> setter, int existingValue, CultureInfo? culture = null) { return CreateBinderCore<int>(factory, receiver, setter, culture, ConvertToInt); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<int?> setter, int? existingValue, CultureInfo? culture = null) { return CreateBinderCore<int?>(factory, receiver, setter, culture, ConvertToNullableInt); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<long> setter, long existingValue, CultureInfo? culture = null) { return CreateBinderCore<long>(factory, receiver, setter, culture, ConvertToLong); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<short> setter, short existingValue, CultureInfo? culture = null) { return CreateBinderCore<short>(factory, receiver, setter, culture, ConvertToShort); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<long?> setter, long? existingValue, CultureInfo? culture = null) { return CreateBinderCore<long?>(factory, receiver, setter, culture, ConvertToNullableLong); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<short?> setter, short? existingValue, CultureInfo? culture = null) { return CreateBinderCore<short?>(factory, receiver, setter, culture, ConvertToNullableShort); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<float> setter, float existingValue, CultureInfo? culture = null) { return CreateBinderCore<float>(factory, receiver, setter, culture, ConvertToFloat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<float?> setter, float? existingValue, CultureInfo? culture = null) { return CreateBinderCore<float?>(factory, receiver, setter, culture, ConvertToNullableFloat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<double> setter, double existingValue, CultureInfo? culture = null) { return CreateBinderCore<double>(factory, receiver, setter, culture, ConvertToDoubleDelegate); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<double?> setter, double? existingValue, CultureInfo? culture = null) { return CreateBinderCore<double?>(factory, receiver, setter, culture, ConvertToNullableDoubleDelegate); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<decimal> setter, decimal existingValue, CultureInfo? culture = null) { return CreateBinderCore<decimal>(factory, receiver, setter, culture, ConvertToDecimal); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<decimal?> setter, decimal? existingValue, CultureInfo? culture = null) { return CreateBinderCore<decimal?>(factory, receiver, setter, culture, ConvertToNullableDecimal); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTime> setter, DateTime existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateTime>(factory, receiver, setter, culture, ConvertToDateTime); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTime> setter, DateTime existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateTime>(factory, receiver, setter, culture, format, ConvertToDateTimeWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTime?> setter, DateTime? existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateTime?>(factory, receiver, setter, culture, ConvertToNullableDateTime); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTime?> setter, DateTime? existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateTime?>(factory, receiver, setter, culture, format, ConvertToNullableDateTimeWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTimeOffset> setter, DateTimeOffset existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateTimeOffset>(factory, receiver, setter, culture, ConvertToDateTimeOffset); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTimeOffset> setter, DateTimeOffset existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateTimeOffset>(factory, receiver, setter, culture, format, ConvertToDateTimeOffsetWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTimeOffset?> setter, DateTimeOffset? existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateTimeOffset?>(factory, receiver, setter, culture, ConvertToNullableDateTimeOffset); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateTimeOffset?> setter, DateTimeOffset? existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateTimeOffset?>(factory, receiver, setter, culture, format, ConvertToNullableDateTimeOffsetWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateOnly> setter, DateOnly existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateOnly>(factory, receiver, setter, culture, ConvertToDateOnly); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateOnly> setter, DateOnly existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateOnly>(factory, receiver, setter, culture, format, ConvertToDateOnlyWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateOnly?> setter, DateOnly? existingValue, CultureInfo? culture = null) { return CreateBinderCore<DateOnly?>(factory, receiver, setter, culture, ConvertToNullableDateOnly); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<DateOnly?> setter, DateOnly? existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<DateOnly?>(factory, receiver, setter, culture, format, ConvertToNullableDateOnlyWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<TimeOnly> setter, TimeOnly existingValue, CultureInfo? culture = null) { return CreateBinderCore<TimeOnly>(factory, receiver, setter, culture, ConvertToTimeOnly); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<TimeOnly> setter, TimeOnly existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<TimeOnly>(factory, receiver, setter, culture, format, ConvertToTimeOnlyWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<TimeOnly?> setter, TimeOnly? existingValue, CultureInfo? culture = null) { return CreateBinderCore<TimeOnly?>(factory, receiver, setter, culture, ConvertToNullableTimeOnly); } /// <summary> /// For internal use only. /// </summary> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="format"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder( this EventCallbackFactory factory, object receiver, Action<TimeOnly?> setter, TimeOnly? existingValue, string format, CultureInfo? culture = null) { return CreateBinderCore<TimeOnly?>(factory, receiver, setter, culture, format, ConvertToNullableTimeOnlyWithFormat); } /// <summary> /// For internal use only. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="factory"></param> /// <param name="receiver"></param> /// <param name="setter"></param> /// <param name="existingValue"></param> /// <param name="culture"></param> /// <returns></returns> [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static EventCallback<ChangeEventArgs> CreateBinder<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>( this EventCallbackFactory factory, object receiver, Action<T> setter, T existingValue, CultureInfo? culture = null) { return CreateBinderCore<T>(factory, receiver, setter, culture, ParserDelegateCache.Get<T>()); } private static EventCallback<ChangeEventArgs> CreateBinderCore<T>( this EventCallbackFactory factory, object receiver, Action<T> setter, CultureInfo? culture, BindConverter.BindParser<T> converter) { Action<ChangeEventArgs> callback = e => { T? value = default; var converted = false; try { converted = converter(e.Value, culture, out value); } catch { } // We only invoke the setter if the conversion didn't throw, or if the newly-entered value is empty. // If the user entered some non-empty value we couldn't parse, we leave the state of the .NET field // unchanged, which for a two-way binding results in the UI reverting to its previous valid state // because the diff will see the current .NET output no longer matches the render tree since we // patched it to reflect the state of the UI. // // This reversion behavior is valuable because alternatives are problematic: // - If we assigned default(T) on failure, the user would lose whatever data they were editing, // for example if they accidentally pressed an alphabetical key while editing a number with // @bind:event="oninput" // - If the diff mechanism didn't revert to the previous good value, the user wouldn't necessarily // know that the data they are submitting is different from what they think they've typed if (converted) { setter(value!); } else if (string.Empty.Equals(e.Value)) { setter(default!); } }; return factory.Create<ChangeEventArgs>(receiver, callback); } private static EventCallback<ChangeEventArgs> CreateBinderCore<T>( this EventCallbackFactory factory, object receiver, Action<T> setter, CultureInfo? culture, string format, BindConverter.BindParserWithFormat<T> converter) { Action<ChangeEventArgs> callback = e => { T? value = default; var converted = false; try { converted = converter(e.Value, culture, format, out value); } catch { } // We only invoke the setter if the conversion didn't throw, or if the newly-entered value is empty. // If the user entered some non-empty value we couldn't parse, we leave the state of the .NET field // unchanged, which for a two-way binding results in the UI reverting to its previous valid state // because the diff will see the current .NET output no longer matches the render tree since we // patched it to reflect the state of the UI. // // This reversion behavior is valuable because alternatives are problematic: // - If we assigned default(T) on failure, the user would lose whatever data they were editing, // for example if they accidentally pressed an alphabetical key while editing a number with // @bind:event="oninput" // - If the diff mechanism didn't revert to the previous good value, the user wouldn't necessarily // know that the data they are submitting is different from what they think they've typed if (converted) { setter(value!); } else if (string.Empty.Equals(e.Value)) { setter(default!); } }; return factory.Create<ChangeEventArgs>(receiver, callback); } } }
/* * Queue.cs - Implementation of the "System.Collections.Queue" class. * * Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Collections { using System; using System.Private; #if !ECMA_COMPAT public #else internal #endif class Queue : ICollection, IEnumerable, ICloneable { // Internal state. private Object[] items; private int add, remove, size; private float growFactor; private int generation; // The default capacity for queues. private const int DefaultCapacity = 32; // Constructors. public Queue() { items = new Object [DefaultCapacity]; add = 0; remove = 0; size = 0; growFactor = 2.0f; generation = 0; } public Queue(int capacity) { if(capacity < 0) { throw new ArgumentOutOfRangeException ("capacity", _("ArgRange_NonNegative")); } items = new Object [capacity]; add = 0; remove = 0; size = 0; growFactor = 2.0f; generation = 0; } public Queue(int capacity, float growFactor) { if(capacity < 0) { throw new ArgumentOutOfRangeException ("capacity", _("ArgRange_NonNegative")); } if(growFactor < 1.0f || growFactor > 10.0f) { throw new ArgumentOutOfRangeException ("growFactor", _("ArgRange_QueueGrowFactor")); } items = new Object [capacity]; add = 0; remove = 0; size = 0; this.growFactor = growFactor; generation = 0; } public Queue(ICollection col) { if(col == null) { throw new ArgumentNullException("col"); } items = new Object [col.Count]; col.CopyTo(items, 0); add = 0; remove = 0; size = items.Length; growFactor = 2.0f; generation = 0; } // Implement the ICollection interface. public virtual void CopyTo(Array array, int index) { if(array == null) { throw new ArgumentNullException("array"); } else if(array.Rank != 1) { throw new ArgumentException(_("Arg_RankMustBe1")); } else if(index < 0) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } else if((array.GetLength(0) - index) < size) { throw new ArgumentException(_("Arg_InvalidArrayRange")); } else if(size > 0) { if((remove + size) <= items.Length) { Array.Copy(items, remove, array, index, size); } else { Array.Copy(items, remove, array, index, items.Length - remove); Array.Copy(items, 0, array, index + items.Length - remove, add); } } } public virtual int Count { get { return size; } } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { return this; } } // Implement the ICloneable interface. public virtual Object Clone() { Queue queue = (Queue)MemberwiseClone(); queue.items = (Object[])items.Clone(); return queue; } // Implement the IEnumerable interface. public virtual IEnumerator GetEnumerator() { return new QueueEnumerator(this); } // Clear the contents of this queue. public virtual void Clear() { Array.Clear(items, 0, items.Length); // clear references of objects add = 0; remove = 0; size = 0; ++generation; } // Determine if this queue contains a specific object. public virtual bool Contains(Object obj) { int index = remove; int capacity = items.Length; int count = size; while(count > 0) { if(items[index] != null && obj != null) { if(obj.Equals(items[index])) { return true; } } else if(items[index] == null && obj == null) { return true; } index = (index + 1) % capacity; --count; } return false; } // Dequeue an item. public virtual Object Dequeue() { if(size > 0) { Object value = items[remove]; items[remove] = null; // set to null to release the handle remove = (remove + 1) % items.Length; --size; ++generation; return value; } else { throw new InvalidOperationException (_("Invalid_EmptyQueue")); } } // Enqueue an item. public virtual void Enqueue(Object obj) { if(size < items.Length) { // The queue is big enough to hold the new item. items[add] = obj; add = (add + 1) % items.Length; ++size; } else { // We need to increase the size of the queue. int newCapacity = (int)(items.Length * growFactor); if(newCapacity <= items.Length) { newCapacity = items.Length + 1; } Object[] newItems = new Object [newCapacity]; if(remove < size) { Array.Copy(items, remove, newItems, 0, size - remove); } if(remove > 0) { Array.Copy(items, 0, newItems, size - remove, remove); } items = newItems; add = size; remove = 0; items[add] = obj; add = (add + 1) % items.Length; ++size; } ++generation; } // Peek at the first item without dequeuing it. public virtual Object Peek() { if(size > 0) { return items[remove]; } else { throw new InvalidOperationException (_("Invalid_EmptyQueue")); } } // Convert the contents of this queue into an array. public virtual Object[] ToArray() { Object[] array = new Object [size]; if(size > 0) { if((remove + size) <= items.Length) { Array.Copy(items, remove, array, 0, size); } else { Array.Copy(items, remove, array, 0, items.Length - remove); Array.Copy(items, 0, array, items.Length - remove, add); } } return array; } // Trim this queue to its actual size. public virtual void TrimToSize() { items = ToArray(); add = items.Length; remove = 0; size = items.Length; } // Convert this queue into a synchronized queue. public static Queue Synchronized(Queue queue) { if(queue == null) { throw new ArgumentNullException("queue"); } else if(queue.IsSynchronized) { return queue; } else { return new SynchronizedQueue(queue); } } // Private class that implements synchronized queues. private class SynchronizedQueue : Queue { // Internal state. private Queue queue; // Constructor. public SynchronizedQueue(Queue queue) { this.queue = queue; } // Implement the ICollection interface. public override void CopyTo(Array array, int index) { lock(SyncRoot) { queue.CopyTo(array, index); } } public override int Count { get { lock(SyncRoot) { return queue.Count; } } } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return queue.SyncRoot; } } // Implement the ICloneable interface. public override Object Clone() { return new SynchronizedQueue((Queue)(queue.Clone())); } // Implement the IEnumerable interface. public override IEnumerator GetEnumerator() { lock(SyncRoot) { return new SynchronizedEnumerator (SyncRoot, queue.GetEnumerator()); } } // Clear the contents of this queue. public override void Clear() { lock(SyncRoot) { queue.Clear(); } } // Determine if this queue contains a specific object. public override bool Contains(Object obj) { lock(SyncRoot) { return queue.Contains(obj); } } // Dequeue an item. public override Object Dequeue() { lock(SyncRoot) { return queue.Dequeue(); } } // Enqueue an item. public override void Enqueue(Object obj) { lock(SyncRoot) { queue.Enqueue(obj); } } // Peek at the first item without dequeuing it. public override Object Peek() { lock(SyncRoot) { return queue.Peek(); } } // Convert the contents of this queue into an array. public override Object[] ToArray() { lock(SyncRoot) { return queue.ToArray(); } } // Trim this queue to its actual size. public override void TrimToSize() { lock(SyncRoot) { queue.TrimToSize(); } } }; // class SynchronizedQueue // Private class for implementing queue enumeration. private class QueueEnumerator : IEnumerator { // Internal state. private Queue queue; private int generation; private int position; // Constructor. public QueueEnumerator(Queue queue) { this.queue = queue; generation = queue.generation; position = -1; } // Implement the IEnumerator interface. public bool MoveNext() { if(generation != queue.generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } ++position; if(position < queue.size) { return true; } position = queue.size; return false; } public void Reset() { if(generation != queue.generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } position = -1; } public Object Current { get { if(generation != queue.generation) { throw new InvalidOperationException (_("Invalid_CollectionModified")); } if(position < 0 || position >= queue.size) { throw new InvalidOperationException (_("Invalid_BadEnumeratorPosition")); } return queue.items [(queue.remove + position) % queue.items.Length]; } } }; // class QueueEnumerator }; // class Queue }; // namespace System.Collections
using System; using System.Diagnostics; using System.IO; using System.Collections; using System.Xml; using System.Xml.Serialization; namespace Microsoft.SPOT.Debugger { public class Pdbx { public class TokenMap { uint StringToUInt32(string s) { s.Trim(); if (s.StartsWith("0x")) s = s.Remove(0, 2); return uint.Parse(s, System.Globalization.NumberStyles.HexNumber); } string UInt32ToString(uint u) { return "0x" + u.ToString("X"); } [XmlIgnore]public uint CLR; [XmlIgnore]public uint TinyCLR; [XmlElement("CLR")] public string CLR_String { get {return UInt32ToString(CLR);} set {CLR = StringToUInt32(value);} } [XmlElement("TinyCLR")] public string TinyCLR_String { get {return UInt32ToString(TinyCLR);} set {TinyCLR = StringToUInt32(value);} } } public class Token : TokenMap { } public class IL : TokenMap { } public class ClassMember { public Token Token; [XmlIgnore]public Class Class; } public class Method : ClassMember { public bool HasByteCode = true; public IL[] ILMap; private bool m_fIsJMC; [XmlIgnore] public bool IsJMC { get { return m_fIsJMC; } set { if (CanSetJMC) m_fIsJMC = value; } } public bool CanSetJMC { get { return this.HasByteCode; } } } public class Field : ClassMember { } public class Class { public Token Token; public Field[] Fields; public Method[] Methods; [XmlIgnore]public Assembly Assembly; } public class Assembly /*Module*/ { public struct VersionStruct { public ushort Major; public ushort Minor; public ushort Build; public ushort Revision; } public string FileName; public VersionStruct Version; public Token Token; public Class[] Classes; [XmlIgnore]public CorDebugAssembly CorDebugAssembly; } public class PdbxFile { public class Resolver { private string[] _assemblyPaths; private string[] _assemblyDirectories; public string[] AssemblyPaths { get { return _assemblyPaths; } set { _assemblyPaths = value; } } public string[] AssemblyDirectories { get {return _assemblyDirectories;} set {_assemblyDirectories = value;} } public PdbxFile Resolve(string name, WireProtocol.Commands.Debugging_Resolve_Assembly.Version version, bool fIsTargetBigEndian) { PdbxFile file = PdbxFile.Open(name, version, _assemblyPaths, _assemblyDirectories, fIsTargetBigEndian); return file; } } public Assembly Assembly; [XmlIgnore]public string PdbxPath; private static PdbxFile TryPdbxFile(string path, WireProtocol.Commands.Debugging_Resolve_Assembly.Version version) { try { path += ".pdbx"; if (File.Exists(path)) { XmlSerializer xmls = new Serialization.PdbxFile.PdbxFileSerializer(); PdbxFile file = (PdbxFile)Utility.XmlDeserialize(path, xmls); //Check version Assembly.VersionStruct version2 = file.Assembly.Version; if (version2.Major == version.iMajorVersion && version2.Minor == version.iMinorVersion) { file.Initialize(path); return file; } } } catch { } return null; } private static PdbxFile OpenHelper(string name, WireProtocol.Commands.Debugging_Resolve_Assembly.Version version, string[] assemblyDirectories, string directorySuffix) { PdbxFile file = null; for (int iDirectory = 0; iDirectory < assemblyDirectories.Length; iDirectory++) { string directory = assemblyDirectories[iDirectory]; if(!string.IsNullOrEmpty(directorySuffix)) { directory = Path.Combine(directory, directorySuffix); } string pathNoExt = Path.Combine(directory, name); if ((file = TryPdbxFile(pathNoExt, version)) != null) break; } return file; } private static PdbxFile Open(string name, WireProtocol.Commands.Debugging_Resolve_Assembly.Version version, string[] assemblyPaths, string[] assemblyDirectories, bool fIsTargetBigEndian) { PdbxFile file = null; if (assemblyPaths != null) { for(int iPath = 0; iPath < assemblyPaths.Length; iPath++) { string path = assemblyPaths[iPath]; string pathNoExt = Path.ChangeExtension(path, null); if (0 == string.Compare(name, Path.GetFileName(pathNoExt), true)) { if ((file = TryPdbxFile(pathNoExt, version)) != null) break; } } } if (file == null && assemblyDirectories != null) { file = OpenHelper(name, version, assemblyDirectories, null); if (file == null) { if (fIsTargetBigEndian) { file = OpenHelper(name, version, assemblyDirectories, @"..\pe\be"); if (file == null) { file = OpenHelper(name, version, assemblyDirectories, @"be"); } } else { file = OpenHelper(name, version, assemblyDirectories, @"..\pe\le"); if (file == null) { file = OpenHelper(name, version, assemblyDirectories, @"le"); } } } } //Try other paths here... return file; } private void Initialize(string path) { this.PdbxPath = path; for(int iClass = 0; iClass < this.Assembly.Classes.Length; iClass++) { Class c = this.Assembly.Classes[iClass]; c.Assembly = this.Assembly; for(int iMethod = 0; iMethod < c.Methods.Length; iMethod++) { Method m = c.Methods[iMethod]; m.Class = c; #if DEBUG for (int iIL = 0; iIL < m.ILMap.Length - 1; iIL++) { Debug.Assert(m.ILMap[iIL].CLR < m.ILMap[iIL + 1].CLR); Debug.Assert(m.ILMap[iIL].TinyCLR < m.ILMap[iIL + 1].TinyCLR); } #endif } foreach (Field f in c.Fields) { f.Class = c; } } } /// Format of the Pdbx file /// ///<Pdbx> /// <dat> /// <filename>NAME</filename> /// </dat> /// <assemblies> /// <assembly> /// <name>NAME</name> /// <version> /// <Major>1</Major> /// <Minor>2</Minor> /// <Build>3</Build> /// <Revision>4</Revision> /// </version> /// <token> /// <CLR>TOKEN</CLR> /// <TinyCLR>TOKEN</TinyCLR> /// </token> /// <classes> /// <class> /// <name>NAME</name> /// <fields> /// <field> /// <token></token> /// </field> /// </fields> /// <methods> /// <method> /// <token></token> /// <ILMap> /// <IL> /// <CLR>IL</CLR> /// <TinyCLR>IL</TinyCLR> /// </IL> /// </ILMap> /// </method> /// </methods> /// </class> /// </classes> /// </assembly> /// </assemblies> ///</Pdbx> /// /// } } }
using System; using System.Net; using System.Net.Sockets; using System.IO; using System.Text; using System.Collections.Generic; namespace Hydna.Net { internal class SocketAdapter : IConnectionAdapter { internal class HandshakeState { internal byte[] data = new byte[1024]; internal int offset = 0; internal string header = ""; } internal class SendState { internal byte[] data = null; internal int offset = 0; } internal class ReceiveState { internal byte[] len = new byte[2]; internal byte[] data = null; internal int length = 0; internal int offset = 0; internal byte first = 0; } const string protocolVersion = "winksock/1"; event ConnectEventHandler OnConnect; event CloseEventHandler OnClose; event FrameEventHandler OnFrame; private Socket _socket; private Queue<SendState> _sendQueue; private bool _sending; private bool _closing; private bool _disposed; private AsyncCallback _sendCallback; private AsyncCallback _receiveCallback; void IDisposable.Dispose() { try { shutdown(null); } catch (Exception) { } } internal SocketAdapter() { _sendQueue = new Queue<SendState>(); _sendCallback = new AsyncCallback(sendHandler); _receiveCallback = new AsyncCallback(receiveHandler); } void IConnectionAdapter.Connect (Uri uri) { AsyncCallback callback; callback = new AsyncCallback(resolvedHandler); Dns.BeginGetHostEntry(uri.Host, callback, uri); } void IConnectionAdapter.Send(Frame frame) { SendState state; if (_closing || _disposed) return; state = new SendState(); state.data = frame.ToBytes(); if (_sending) { _sendQueue.Enqueue(state); return; } processSendState(state); } void IConnectionAdapter.Close() { if (_closing || _disposed) return; _closing = true; _socket.BeginDisconnect(false, new AsyncCallback(disconnectHandler), null); } event ConnectEventHandler IConnectionAdapter.OnConnect { add { OnConnect += value; } remove { OnConnect -= value; } } event CloseEventHandler IConnectionAdapter.OnClose { add { OnClose += value; } remove { OnClose -= value; } } event FrameEventHandler IConnectionAdapter.OnFrame { add { OnFrame += value; } remove { OnFrame -= value; } } void resolvedHandler (IAsyncResult ar) { IPHostEntry entry; if (_closing || _disposed) return; try { entry = Dns.EndGetHostEntry(ar); if (entry.AddressList.Length == 0) { shutdown("Unable to resolve host"); return; } } catch (SocketException ex) { shutdown("Unable to resolve host(" + ex.Message + ")"); return; } IPEndPoint endPoint = new IPEndPoint(entry.AddressList[0], ((Uri)ar.AsyncState).Port); _socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); AsyncCallback callback = new AsyncCallback(connectHandler); _socket.BeginConnect(endPoint, callback, ar.AsyncState); } void connectHandler(IAsyncResult ar) { if (_closing || _disposed) return; try { _socket.EndConnect(ar); } catch (SocketException ex) { shutdown("Faild connect to remote(" + ex.Message + ")"); return; } StringBuilder request = new StringBuilder(); request.Append("GET / HTTP/1.1\r\n"); request.Append("Connection: Upgrade\r\n"); request.Append("Upgrade: " + protocolVersion + "\r\n"); request.Append("Host: " + ((Uri)ar.AsyncState).Host + "\r\n"); request.Append("\r\n"); byte[] data = Encoding.ASCII.GetBytes(request.ToString()); _socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(handshakeSendHandler), null); } void handshakeSendHandler(IAsyncResult ar) { if (_closing || _disposed) return; try { _socket.EndSend(ar); } catch (SocketException ex) { shutdown("Unable to resolve host(" + ex.Message + ")"); return; } HandshakeState state = new HandshakeState(); _socket.BeginReceive(state.data, 0, state.data.Length, SocketFlags.None, new AsyncCallback(handshakeHandler), state); } void handshakeHandler(IAsyncResult ar) { int bytes; if (_closing || _disposed) return; try { bytes = _socket.EndReceive(ar); } catch (SocketException ex) { shutdown("Unable to resolve host(" + ex.Message + ")"); return; } HandshakeState state = (HandshakeState)ar.AsyncState; if (state.offset + bytes > state.data.Length) { // Break on bigger buffers then data buff. shutdown("Unable to connect to host(BAD_HANDSHAKE)"); return; } state.header += Encoding.ASCII.GetString(state.data, state.offset, state.offset + bytes); if (state.header.Contains("\r\n\r\n") == false) { // Consider the response to be uncomplete. state.offset += bytes; _socket.BeginReceive(state.data, state.offset, state.data.Length - state.offset, SocketFlags.None, new AsyncCallback(handshakeHandler), state); return; } if (state.header.Split('\r')[0].Contains("101") == false) { int idx = state.header.IndexOf("\r\n\r\n"); string body = state.header.Substring(idx); if (body.Length > 1) { shutdown(body.TrimStart('\n', '\r', ' ')); } else { shutdown("Bad handshake from server"); } return; } if (OnConnect != null) { OnConnect(); } receiveLength(null); } void sendHandler(IAsyncResult ar) { int bytes; _sending = false; if (_closing || _disposed) return; try { bytes = _socket.EndSend(ar); } catch (SocketException ex) { shutdown(ex.Message); return; } SendState state = (SendState)ar.AsyncState; if (state.offset + bytes < state.data.Length) { state.offset += bytes; _socket.BeginSend(state.data, state.offset, state.data.Length - state.offset, SocketFlags.None, _sendCallback, state); return; } if (_sendQueue.Count > 0) processSendState(_sendQueue.Dequeue()); } void receiveHandler(IAsyncResult ar) { int bytes; if (_closing || _disposed) return; try { bytes = _socket.EndReceive(ar); } catch (SocketException ex) { shutdown(ex.Message); return; } ReceiveState state = (ReceiveState)ar.AsyncState; // Check if we are dealing with packet length if (state.length == 0) { if (bytes == 1) { // Very unlikely, but could happend. Only managed // to receive one byte. receiveLength(state); return; } if (BitConverter.IsLittleEndian) { Array.Reverse(state.len); } state.length = (int)BitConverter.ToUInt16(state.len, 0); state.data = new byte[state.length]; receive(state); return; } state.offset += bytes; if (state.offset != state.length) { receive(state); return; } Frame frame = Frame.Create(state.data); if (OnFrame != null) OnFrame(frame); receiveLength(null); } void disconnectHandler(IAsyncResult ar) { try { _socket.EndDisconnect(ar); } finally { shutdown("Disconnect by user"); } } void shutdown(string reason) { if (_closing || _disposed) return; if (_socket != null) { _socket = null; } _closing = false; _disposed = true; if (OnClose != null) OnClose(reason); } void processSendState(SendState state) { _sending = true; _socket.BeginSend(state.data, 0, state.data.Length, SocketFlags.None, _sendCallback, state); } void receiveLength(ReceiveState state) { int offset = state == null ? 0 : 1; state = state == null ? new ReceiveState() : state; _socket.BeginReceive(state.len, offset, 2 - offset, SocketFlags.None, _receiveCallback, state); } void receive(ReceiveState state) { _socket.BeginReceive(state.data, state.offset, state.length - state.offset, SocketFlags.None, _receiveCallback, state); } } }
#nullable enable using NBitcoin.Crypto; using NBitcoin.DataEncoders; #if !NO_BC using NBitcoin.BouncyCastle.Math; using NBitcoin.BouncyCastle.Math.EC; #endif #if HAS_SPAN using NBitcoin.Secp256k1; #endif using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; namespace NBitcoin { public enum ScriptPubKeyType { /// <summary> /// Derive P2PKH addresses (P2PKH) /// Only use this for legacy code or coins not supporting segwit /// </summary> Legacy, /// <summary> /// Derive Segwit (Bech32) addresses (P2WPKH) /// This will result in the cheapest fees. This is the recommended choice. /// </summary> Segwit, /// <summary> /// Derive P2SH address of a Segwit address (P2WPKH-P2SH) /// Use this when you worry that your users do not support Bech address format. /// </summary> SegwitP2SH, /// <summary> /// Derive the taproot address of this pubkey following BIP86. This public key is used as the internal key, the output key is computed without script path. (The tweak is SHA256(internal_key)) /// </summary> #if !HAS_SPAN [Obsolete("TaprootBIP86 is unavailable in .net framework")] #endif TaprootBIP86 } public class PubKey : IDestination, IComparable<PubKey>, IEquatable<PubKey>, IPubKey { /// <summary> /// Create a new Public key from string /// </summary> public PubKey(string hex) : this(Encoders.Hex.DecodeData(hex)) { } #if HAS_SPAN bool compressed; internal PubKey(Secp256k1.ECPubKey pubkey, bool compressed) { if (pubkey == null) throw new ArgumentNullException(nameof(pubkey)); this._ECKey = pubkey; this.compressed = compressed; } public static bool TryCreatePubKey(byte[] bytes, [MaybeNullWhen(false)] out PubKey pubKey) { if(bytes is null) throw new ArgumentNullException(nameof(bytes)); return TryCreatePubKey(bytes.AsSpan(), out pubKey); } public static bool TryCreatePubKey(ReadOnlySpan<byte> bytes, [MaybeNullWhen(false)] out PubKey pubKey) { if (NBitcoinContext.Instance.TryCreatePubKey(bytes, out var compressed, out var p)) { pubKey = new PubKey(p, compressed); return true; } pubKey = null; return false; } #endif #if !HAS_SPAN public static bool TryCreatePubKey(byte[] bytes, [MaybeNullWhen(false)] out PubKey pubKey) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); try { var eck = new ECKey(bytes, false); pubKey = new PubKey(eck, bytes); return true; } catch { pubKey = null; return false; } } PubKey(ECKey eCKey, byte[] bytes) { _ECKey = eCKey; vch = bytes.ToArray(); } #endif /// <summary> /// Create a new Public key from byte array /// </summary> /// <param name="bytes">byte array</param> public PubKey(byte[] bytes) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); #if HAS_SPAN if (NBitcoinContext.Instance.TryCreatePubKey(bytes, out compressed, out var p)) { _ECKey = p; } else { throw new FormatException("Invalid public key"); } #else this.vch = bytes.ToArray(); try { _ECKey = new ECKey(bytes, false); } catch (Exception ex) { throw new FormatException("Invalid public key", ex); } #endif } #if HAS_SPAN /// <summary> /// Create a new Public key from byte array /// </summary> /// <param name="bytes">byte array</param> public PubKey(ReadOnlySpan<byte> bytes) { if (NBitcoinContext.Instance.TryCreatePubKey(bytes, out compressed, out var p) && p is Secp256k1.ECPubKey) { _ECKey = p; } else { throw new FormatException("Invalid public key"); } } Secp256k1.ECPubKey _ECKey; internal ref readonly Secp256k1.ECPubKey ECKey => ref _ECKey; #else ECKey _ECKey; internal ECKey ECKey { get { if (_ECKey == null) _ECKey = new ECKey(vch, false); return _ECKey; } } #endif public int CompareTo(PubKey other) => BytesComparer.Instance.Compare(this.ToBytes(), other.ToBytes()); public PubKey Compress() { if (IsCompressed) return this; #if HAS_SPAN return new PubKey(this._ECKey, true); #else return ECKey.GetPubKey(true); #endif } public PubKey Decompress() { if (!IsCompressed) return this; #if HAS_SPAN return new PubKey(this._ECKey, false); #else return ECKey.GetPubKey(false); #endif } /// <summary> /// Quick sanity check on public key format. (size + first byte) /// </summary> /// <param name="data">bytes array</param> public static bool SanityCheck(byte[] data) { return SanityCheck(data, 0, data.Length); } public static bool SanityCheck(byte[] data, int offset, int count) { if (data is null) throw new ArgumentNullException(nameof(data)); return ( (count == 33 && (data[offset + 0] == 0x02 || data[offset + 0] == 0x03)) || (count == 65 && (data[offset + 0] == 0x04 || data[offset + 0] == 0x06 || data[offset + 0] == 0x07)) ); } #if HAS_SPAN KeyId? _ID; public KeyId Hash { get { if (_ID is null) { Span<byte> tmp = stackalloc byte[65]; _ECKey.WriteToSpan(compressed, tmp, out int len); tmp = tmp.Slice(0, len); _ID = new KeyId(Hashes.Hash160(tmp)); } return _ID; } } WitKeyId? _WitID; public WitKeyId WitHash { get { if (_WitID is null) { Span<byte> tmp = stackalloc byte[65]; _ECKey.WriteToSpan(compressed, tmp, out int len); tmp = tmp.Slice(0, len); _WitID = new WitKeyId(Hashes.Hash160(tmp)); } return _WitID; } } #else byte[] vch; KeyId? _ID; public KeyId Hash { get { if (_ID == null) { _ID = new KeyId(Hashes.Hash160(vch, 0, vch.Length)); } return _ID; } } WitKeyId? _WitID; public WitKeyId WitHash { get { if (_WitID == null) { _WitID = new WitKeyId(Hashes.Hash160(vch, 0, vch.Length)); } return _WitID; } } #endif public bool IsCompressed { get { #if HAS_SPAN return this.compressed; #else if (this.vch.Length == 65) return false; if (this.vch.Length == 33) return true; throw new NotSupportedException("Invalid public key size"); #endif } } public BitcoinAddress GetAddress(ScriptPubKeyType type, Network network) { switch (type) { case ScriptPubKeyType.Legacy: return this.Hash.GetAddress(network); case ScriptPubKeyType.Segwit: if (!network.Consensus.SupportSegwit) throw new NotSupportedException("This network does not support segwit"); return this.WitHash.GetAddress(network); case ScriptPubKeyType.SegwitP2SH: if (!network.Consensus.SupportSegwit) throw new NotSupportedException("This network does not support segwit"); return this.WitHash.ScriptPubKey.Hash.GetAddress(network); #pragma warning disable CS0618 // Type or member is obsolete case ScriptPubKeyType.TaprootBIP86: #pragma warning restore CS0618 // Type or member is obsolete if (!network.Consensus.SupportTaproot) throw new NotSupportedException("This network does not support taproot"); #if !HAS_SPAN throw new NotSupportedException("This feature of taproot is not supported in .NET Framework"); #else return GetTaprootFullPubKey().GetAddress(network); #endif default: throw new NotSupportedException("Unsupported ScriptPubKeyType"); } } #if HAS_SPAN public TaprootFullPubKey GetTaprootFullPubKey() { return GetTaprootFullPubKey(null); } public TaprootFullPubKey GetTaprootFullPubKey(uint256? merkleRoot) { return TaprootInternalKey.GetTaprootFullPubKey(merkleRoot); } TaprootInternalPubKey? _InternalKey; internal bool Parity => this.ECKey.Q.y.IsOdd; public TaprootInternalPubKey TaprootInternalKey { get { if (_InternalKey is TaprootInternalPubKey) { return _InternalKey; } var xonly = this.ECKey.ToXOnlyPubKey(out _); _InternalKey = new TaprootInternalPubKey(xonly); return _InternalKey; } } #endif HDFingerprint? fp; public HDFingerprint GetHDFingerPrint() { if (fp is HDFingerprint f) return f; f = new HDFingerprint(this.Hash.ToBytes(), 0); fp = f; return f; } public bool Verify(uint256 hash, ECDSASignature sig) { if (sig == null) throw new ArgumentNullException(nameof(sig)); if (hash == null) throw new ArgumentNullException(nameof(hash)); #if HAS_SPAN Span<byte> msg = stackalloc byte[32]; hash.ToBytes(msg); return _ECKey.SigVerify(sig.ToSecpECDSASignature(), msg); #else return ECKey.Verify(hash, sig); #endif } public bool Verify(uint256 hash, byte[] sig) { return Verify(hash, ECDSASignature.FromDER(sig)); } public Script GetScriptPubKey(ScriptPubKeyType type) { return GetDestination(type).ScriptPubKey; } public IAddressableDestination GetDestination(ScriptPubKeyType type) { switch (type) { case ScriptPubKeyType.Legacy: return Hash; case ScriptPubKeyType.Segwit: return WitHash; case ScriptPubKeyType.SegwitP2SH: return WitHash.ScriptPubKey.Hash; #pragma warning disable CS0618 // Type or member is obsolete case ScriptPubKeyType.TaprootBIP86: #pragma warning restore CS0618 // Type or member is obsolete #if HAS_SPAN return GetTaprootFullPubKey(); #else throw new NotSupportedException("ScriptPubKeyType.TaprootBIP86 is not supported by .net framework"); #endif default: throw new NotSupportedException(); } } #if HAS_SPAN public string ToHex() { Span<byte> tmp = stackalloc byte[65]; this._ECKey.WriteToSpan(compressed, tmp, out var l); tmp = tmp.Slice(0, l); return Encoders.Hex.EncodeData(tmp); } #else public string ToHex() { return Encoders.Hex.EncodeData(vch); } #endif public byte[] ToBytes() { #if HAS_SPAN return _ECKey.ToBytes(compressed); #else return vch.ToArray(); #endif } #if HAS_SPAN public void ToBytes(Span<byte> output, out int length) { _ECKey.WriteToSpan(compressed, output, out length); } #endif public byte[] ToBytes(bool @unsafe) { #if HAS_SPAN return ToBytes(); #else if (@unsafe) return vch; else return vch.ToArray(); #endif } public override string ToString() { return ToHex(); } /// <summary> /// Verify message signed using signmessage from bitcoincore /// </summary> /// <param name="message">The message</param> /// <param name="signature">The signature</param> /// <returns>True if signatures is valid</returns> public bool VerifyMessage(string message, string signature) { return VerifyMessage(Encoding.UTF8.GetBytes(message), signature); } /// <summary> /// Verify message signed using signmessage from bitcoincore /// </summary> /// <param name="message">The message</param> /// <param name="signature">The signature</param> /// <returns>True if signatures is valid</returns> public bool VerifyMessage(byte[] messageBytes, string signature) { return VerifyMessage(messageBytes, DecodeSigString(signature)); } /// <summary> /// Verify message signed using signmessage from bitcoincore /// </summary> /// <param name="message">The message</param> /// <param name="signature">The signature</param> /// <returns>True if signatures is valid</returns> public bool VerifyMessage(byte[] message, ECDSASignature signature) { #if HAS_SPAN var messageToSign = Utils.FormatMessageForSigning(message); var hash = Hashes.DoubleSHA256(messageToSign); Span<byte> msg = stackalloc byte[32]; hash.ToBytes(msg); return _ECKey.SigVerify(signature.ToSecpECDSASignature(), msg); #else var messageToSign = Utils.FormatMessageForSigning(message); var hash = Hashes.DoubleSHA256(messageToSign); return ECKey.Verify(hash, signature); #endif } #if HAS_SPAN /// <summary> /// Decode signature from bitcoincore verify/signing rpc methods /// </summary> /// <param name="signature"></param> /// <returns></returns> private static ECDSASignature DecodeSigString(string signature) { var signatureEncoded = Encoders.Base64.DecodeData(signature); return DecodeSig(signatureEncoded); } private static ECDSASignature DecodeSig(byte[] signatureEncoded) { if (Secp256k1.SecpECDSASignature.TryCreateFromCompact(signatureEncoded.AsSpan().Slice(1), out var sig) && sig is Secp256k1.SecpECDSASignature) { return new ECDSASignature(sig); } return new ECDSASignature(Secp256k1.Scalar.Zero, Secp256k1.Scalar.Zero); } #else /// <summary> /// Decode signature from bitcoincore verify/signing rpc methods /// </summary> /// <param name="signature"></param> /// <returns></returns> private static ECDSASignature DecodeSigString(string signature) { var signatureEncoded = Encoders.Base64.DecodeData(signature); return DecodeSig(signatureEncoded); } private static ECDSASignature DecodeSig(byte[] signatureEncoded) { BigInteger r = new BigInteger(1, signatureEncoded.SafeSubarray(1, 32)); BigInteger s = new BigInteger(1, signatureEncoded.SafeSubarray(33, 32)); #pragma warning disable 618 var sig = new ECDSASignature(r, s); #pragma warning restore 618 return sig; } #endif //Thanks bitcoinj source code //http://bitcoinj.googlecode.com/git-history/keychain/core/src/main/java/com/google/bitcoin/core/Utils.java public static PubKey RecoverFromMessage(string messageText, string signatureText) { return RecoverFromMessage(Encoding.UTF8.GetBytes(messageText), signatureText); } public static PubKey RecoverFromMessage(byte[] messageBytes, string signatureText) { var signatureEncoded = Encoders.Base64.DecodeData(signatureText); var message = Utils.FormatMessageForSigning(messageBytes); var hash = Hashes.DoubleSHA256(message); return RecoverCompact(hash, signatureEncoded); } public static PubKey RecoverCompact(uint256 hash, byte[] signatureEncoded) { #if HAS_SPAN if (signatureEncoded.Length != 65) throw new ArgumentException(paramName: nameof(signatureEncoded), message: "Signature truncated, expected 65"); Span<byte> msg = stackalloc byte[32]; hash.ToBytes(msg); var s = signatureEncoded.AsSpan(); int recid = (s[0] - 27) & 3; bool fComp = ((s[0] - 27) & 4) != 0; if (Secp256k1.SecpRecoverableECDSASignature.TryCreateFromCompact(s.Slice(1), recid, out var sig) && Secp256k1.ECPubKey.TryRecover(NBitcoinContext.Instance, sig, msg, out var pubkey)) { return new PubKey(pubkey, fComp); } throw new InvalidOperationException("Impossible to recover the public key"); #else if (signatureEncoded.Length < 65) throw new ArgumentException("Signature truncated, expected 65 bytes and got " + signatureEncoded.Length); int header = signatureEncoded[0]; // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y if (header < 27 || header > 34) throw new ArgumentException("Header byte out of range: " + header); var sig = DecodeSig(signatureEncoded); bool compressed = false; if (header >= 31) { compressed = true; header -= 4; } int recId = header - 27; ECKey key = ECKey.RecoverFromSignature(recId, sig, hash, compressed); return key.GetPubKey(compressed); #endif } public PubKey Derivate(byte[] cc, uint nChild, out byte[] ccChild) { if (!IsCompressed) throw new InvalidOperationException("The pubkey must be compressed"); if ((nChild >> 31) != 0) throw new InvalidOperationException("A public key can't derivate an hardened child"); #if HAS_SPAN Span<byte> vout = stackalloc byte[64]; vout.Clear(); Span<byte> pubkey = stackalloc byte[33]; this.ToBytes(pubkey, out _); Hashes.BIP32Hash(cc, nChild, pubkey[0], pubkey.Slice(1), vout); ccChild = new byte[32]; ; vout.Slice(32, 32).CopyTo(ccChild); return new PubKey(this.ECKey.AddTweak(vout.Slice(0, 32)), true); #else byte[] l = new byte[32]; byte[] r = new byte[32]; var pubKey = ToBytes(); byte[] lr = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.Skip(1).ToArray()); Array.Copy(lr, l, 32); Array.Copy(lr, 32, r, 0, 32); ccChild = r; BigInteger N = ECKey.CURVE.N; BigInteger parse256LL = new BigInteger(1, l); if (parse256LL.CompareTo(N) >= 0) throw new InvalidOperationException("You won a prize ! this should happen very rarely. Take a screenshot, and roll the dice again."); var q = ECKey.CURVE.G.Multiply(parse256LL).Add(ECKey.GetPublicKeyParameters().Q); if (q.IsInfinity) throw new InvalidOperationException("You won the big prize ! this would happen only 1 in 2^127. Take a screenshot, and roll the dice again."); q = q.Normalize(); var p = new NBitcoin.BouncyCastle.Math.EC.FpPoint(ECKey.CURVE.Curve, q.XCoord, q.YCoord, true); return new PubKey(p.GetEncoded()); #endif } public override bool Equals(object obj) { if (obj is PubKey pk) return Equals(pk); return false; } #if HAS_SPAN public bool Equals(PubKey pk) => this == pk; public static bool operator ==(PubKey? a, PubKey? b) { if (a is PubKey aa && b is PubKey bb) { return aa.ECKey == bb.ECKey && aa.compressed == bb.compressed; } return a is null && b is null; } #else public bool Equals(PubKey? pk) => pk is PubKey && Utils.ArrayEqual(vch, pk.vch); public static bool operator ==(PubKey? a, PubKey? b) { if (a?.vch is byte[] avch && b?.vch is byte[] bvch) { return Utils.ArrayEqual(avch, bvch); } return a is null && b is null; } #endif public static bool operator !=(PubKey? a, PubKey? b) { return !(a == b); } int? hashcode; public override int GetHashCode() { if (hashcode is int h) return h; #if HAS_SPAN unchecked { h = this._ECKey.GetHashCode(); h = h * 23 + (compressed ? 0 : 1); hashcode = h; return h; } #else h = ToHex().GetHashCode(); hashcode = h; return h; #endif } #region IDestination Members Script? _ScriptPubKey; public Script ScriptPubKey { get { if (_ScriptPubKey is null) { _ScriptPubKey = PayToPubkeyTemplate.Instance.GenerateScriptPubKey(this); } return _ScriptPubKey; } } /// <summary> /// Exchange shared secret through ECDH /// </summary> /// <param name="key">Private key</param> /// <returns>Shared pubkey</returns> public PubKey GetSharedPubkey(Key key) { #if HAS_SPAN if (key == null) throw new ArgumentNullException(nameof(key)); return new PubKey(ECKey.GetSharedPubkey(key._ECKey), true); #else var pub = _ECKey.GetPublicKeyParameters(); var privKey = key._ECKey.PrivateKey; if (!pub.Parameters.Equals(privKey.Parameters)) throw new InvalidOperationException("ECDH public key has wrong domain parameters"); ECPoint q = pub.Q.Multiply(privKey.D).Normalize(); if (q.IsInfinity) throw new InvalidOperationException("Infinity is not a valid agreement value for ECDH"); var pubkey = ECKey.Secp256k1.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()); pubkey = pubkey.Normalize(); return new ECKey(pubkey.GetEncoded(true), false).GetPubKey(true); #endif } public string Encrypt(string message) { if (message is null) throw new ArgumentNullException(nameof(message)); var bytes = Encoding.UTF8.GetBytes(message); return Encoders.Base64.EncodeData(Encrypt(bytes)); } public byte[] Encrypt(byte[] message) { if (message is null) throw new ArgumentNullException(nameof(message)); var ephemeral = new Key(); var sharedKey = Hashes.SHA512(GetSharedPubkey(ephemeral).ToBytes()); var iv = sharedKey.SafeSubarray(0, 16); var encryptionKey = sharedKey.SafeSubarray(16, 16); var hashingKey = sharedKey.SafeSubarray(32); var aes = new AesBuilder().SetKey(encryptionKey).SetIv(iv).IsUsedForEncryption(true).Build(); var cipherText = aes.Process(message, 0, message.Length); var ephemeralPubkeyBytes = ephemeral.PubKey.ToBytes(); var encrypted = Encoders.ASCII.DecodeData("BIE1").Concat(ephemeralPubkeyBytes, cipherText); var hashMAC = Hashes.HMACSHA256(hashingKey, encrypted); return encrypted.Concat(hashMAC); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace AlgorithmDemo { public partial class FlowControlerForm : Form { delegate void dSelectConfiguratoinObject(object o); bool isDropDown = true; System.Threading.Thread workerThread; enum ControlMode { Manual, Auto }; ControlMode controlMode = ControlMode.Manual; int lastTickCount = Environment.TickCount; int frameTime = 300; public FlowControlerForm() { InitializeComponent(); this.Activated += delegate { this.Opacity = 1; }; this.Deactivate += delegate { this.Opacity = 0.6; if (isDropDown) { DeDropDown(); } }; } private void FlowControler_Load(object sender, EventArgs e) { DemoRateTrackBar.Value = (int)(1000.0 / frameTime); if (isDropDown) { DeDropDown(); } this.FormClosed += delegate { if (workerThread != null) { try { if ((workerThread.ThreadState & System.Threading.ThreadState.Suspended) == System.Threading.ThreadState.Suspended) { workerThread.Resume(); } if ((workerThread.ThreadState & System.Threading.ThreadState.Suspended) != System.Threading.ThreadState.Suspended) { workerThread.Abort(); } } catch (System.Threading.ThreadStateException) { } } }; } public void SelectConfiguratoinObject(object o) { if (this.InvokeRequired) { this.BeginInvoke(new dSelectConfiguratoinObject(SelectConfiguratoinObject), new object[] { o }); return; } propertyGrid.SelectedObject = o; } private void CForm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } } private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { //update(); } delegate void dShow(); public void SuspendAndRecordWorkerThread() { this.BeginInvoke(new dShow(Show), new object[]{}); if (controlMode == ControlMode.Manual) { EnableFlowBotton(); workerThread = System.Threading.Thread.CurrentThread; System.Threading.Thread.CurrentThread.Suspend(); } else if (controlMode == ControlMode.Auto) { //if (lastTimeMillisecond == default) //{ // lastTimeMillisecond = System.DateTime.Now.Millisecond; // System.Threading.Thread.CurrentThread.Join(frameTime); //} //else { int elapsed = unchecked(Environment.TickCount - lastTickCount); int sleepTime = frameTime - lastTickCount / 1500; if (sleepTime > 0) { System.Threading.Thread.CurrentThread.Join(sleepTime); } lastTickCount = DateTime.Now.Millisecond; } } } delegate void dTemp(); private void EnableFlowBotton() { if (this.InvokeRequired) { this.BeginInvoke(new dTemp(EnableFlowBotton)); return; } AutoStepBotton.Enabled = true; BreakAllBotton.Enabled = true; NextStepBotton.Enabled = true; this.Focus(); } private void NextStepBotton_Click(object sender, EventArgs e) { if (workerThread != null) { AutoStepBotton.Enabled = false; BreakAllBotton.Enabled = false; NextStepBotton.Enabled = false; if (this.ParentForm != null) { this.Parent.Focus(); } workerThread.Resume(); } } private void AutoStepBotton_Click(object sender, EventArgs e) { if (controlMode == ControlMode.Manual) { controlMode = ControlMode.Auto; AutoStepBotton.Text = "||"; NextStepBotton.Enabled = false; workerThread.Resume(); } else if (controlMode == ControlMode.Auto) { controlMode = ControlMode.Manual; AutoStepBotton.Text = ">>"; AutoStepBotton.Enabled = true; BreakAllBotton.Enabled = true; NextStepBotton.Enabled = true; } } delegate void dReset(); public void Reset() { if (this.InvokeRequired) { this.BeginInvoke(new dReset(Reset), new object[] { }); return; } controlMode = ControlMode.Manual; this.SelectConfiguratoinObject(null); AutoStepBotton.Text = ">>"; AutoStepBotton.Enabled = false; BreakAllBotton.Enabled = false; NextStepBotton.Enabled = false; } private void BreakAllBotton_Click(object sender, EventArgs e) { if ((workerThread.ThreadState & System.Threading.ThreadState.Suspended) == System.Threading.ThreadState.Suspended) { workerThread.Resume(); } workerThread.Abort(); Reset(); } protected override void OnClosing(System.ComponentModel.CancelEventArgs cea) { //cea.Cancel = true; //this.Hide(); } private void propertyGrid_Click(object sender, EventArgs e) { } private void DropDownBotton_Click(object sender, EventArgs e) { if (isDropDown) { DeDropDown(); } else { DropDown(); } } private void DropDown() { this.Height += 121; isDropDown = true; } private void DeDropDown() { this.Height -= 121; isDropDown = false; } private void DemoRateTrackBar_Scroll(object sender, EventArgs e) { int time = (int)(1000.0 / DemoRateTrackBar.Value); System.Threading.Interlocked.Exchange(ref frameTime, time); } } }
namespace GImpactTestDemo { static class BunnyMesh { public static float[] Vertices = { -0.334392f, 0.133007f, 0.062259f, -0.350189f, 0.150354f, -0.147769f, -0.234201f, 0.343811f, -0.174307f, -0.200259f, 0.285207f, 0.093749f, 0.003520f, 0.475208f, -0.159365f, 0.001856f, 0.419203f, 0.098582f, -0.252802f, 0.093666f, 0.237538f, -0.162901f, 0.237984f, 0.206905f, 0.000865f, 0.318141f, 0.235370f, -0.414624f, 0.164083f, -0.278254f, -0.262213f, 0.357334f, -0.293246f, 0.004628f, 0.482694f, -0.338626f, -0.402162f, 0.133528f, -0.443247f, -0.243781f, 0.324275f, -0.436763f, 0.005293f, 0.437592f, -0.458332f, -0.339884f, -0.041150f, -0.668211f, -0.248382f, 0.255825f, -0.627493f, 0.006261f, 0.376103f, -0.631506f, -0.216201f, -0.126776f, -0.886936f, -0.171075f, 0.011544f, -0.881386f, -0.181074f, 0.098223f, -0.814779f, -0.119891f, 0.218786f, -0.760153f, -0.078895f, 0.276780f, -0.739281f, 0.006801f, 0.310959f, -0.735661f, -0.168842f, 0.102387f, -0.920381f, -0.104072f, 0.177278f, -0.952530f, -0.129704f, 0.211848f, -0.836678f, -0.099875f, 0.310931f, -0.799381f, 0.007237f, 0.361687f, -0.794439f, -0.077913f, 0.258753f, -0.921640f, 0.007957f, 0.282241f, -0.931680f, -0.252222f, -0.550401f, -0.557810f, -0.267633f, -0.603419f, -0.655209f, -0.446838f, -0.118517f, -0.466159f, -0.459488f, -0.093017f, -0.311341f, -0.370645f, -0.100108f, -0.159454f, -0.371984f, -0.091991f, -0.011044f, -0.328945f, -0.098269f, 0.088659f, -0.282452f, -0.018862f, 0.311501f, -0.352403f, -0.131341f, 0.144902f, -0.364126f, -0.200299f, 0.202388f, -0.283965f, -0.231869f, 0.023668f, -0.298943f, -0.155218f, 0.369716f, -0.293787f, -0.121856f, 0.419097f, -0.290163f, -0.290797f, 0.107824f, -0.264165f, -0.272849f, 0.036347f, -0.228567f, -0.372573f, 0.290309f, -0.190431f, -0.286997f, 0.421917f, -0.191039f, -0.240973f, 0.507118f, -0.287272f, -0.276431f, -0.065444f, -0.295675f, -0.280818f, -0.174200f, -0.399537f, -0.313131f, -0.376167f, -0.392666f, -0.488581f, -0.427494f, -0.331669f, -0.570185f, -0.466054f, -0.282290f, -0.618140f, -0.589220f, -0.374238f, -0.594882f, -0.323298f, -0.381071f, -0.629723f, -0.350777f, -0.382112f, -0.624060f, -0.221577f, -0.272701f, -0.566522f, 0.259157f, -0.256702f, -0.663406f, 0.286079f, -0.280948f, -0.428359f, 0.055790f, -0.184974f, -0.508894f, 0.326265f, -0.279971f, -0.526918f, 0.395319f, -0.282599f, -0.663393f, 0.412411f, -0.188329f, -0.475093f, 0.417954f, -0.263384f, -0.663396f, 0.466604f, -0.209063f, -0.663393f, 0.509344f, -0.002044f, -0.319624f, 0.553078f, -0.001266f, -0.371260f, 0.413296f, -0.219753f, -0.339762f, -0.040921f, -0.256986f, -0.282511f, -0.006349f, -0.271706f, -0.260881f, 0.001764f, -0.091191f, -0.419184f, -0.045912f, -0.114944f, -0.429752f, -0.124739f, -0.113970f, -0.382987f, -0.188540f, -0.243012f, -0.464942f, -0.242850f, -0.314815f, -0.505402f, -0.324768f, 0.002774f, -0.437526f, -0.262766f, -0.072625f, -0.417748f, -0.221440f, -0.160112f, -0.476932f, -0.293450f, 0.003859f, -0.453425f, -0.443916f, -0.120363f, -0.581567f, -0.438689f, -0.091499f, -0.584191f, -0.294511f, -0.116469f, -0.599861f, -0.188308f, -0.208032f, -0.513640f, -0.134649f, -0.235749f, -0.610017f, -0.040939f, -0.344916f, -0.622487f, -0.085380f, -0.336401f, -0.531864f, -0.212298f, 0.001961f, -0.459550f, -0.135547f, -0.058296f, -0.430536f, -0.043440f, 0.001378f, -0.449511f, -0.037762f, -0.130135f, -0.510222f, 0.079144f, 0.000142f, -0.477549f, 0.157064f, -0.114284f, -0.453206f, 0.304397f, -0.000592f, -0.443558f, 0.285401f, -0.056215f, -0.663402f, 0.326073f, -0.026248f, -0.568010f, 0.273318f, -0.049261f, -0.531064f, 0.389854f, -0.127096f, -0.663398f, 0.479316f, -0.058384f, -0.663401f, 0.372891f, -0.303961f, 0.054199f, 0.625921f, -0.268594f, 0.193403f, 0.502766f, -0.277159f, 0.126123f, 0.443289f, -0.287605f, -0.005722f, 0.531844f, -0.231396f, -0.121289f, 0.587387f, -0.253475f, -0.081797f, 0.756541f, -0.195164f, -0.137969f, 0.728011f, -0.167673f, -0.156573f, 0.609388f, -0.145917f, -0.169029f, 0.697600f, -0.077776f, -0.214247f, 0.622586f, -0.076873f, -0.214971f, 0.696301f, -0.002341f, -0.233135f, 0.622859f, -0.002730f, -0.213526f, 0.691267f, -0.003136f, -0.192628f, 0.762731f, -0.056136f, -0.201222f, 0.763806f, -0.114589f, -0.166192f, 0.770723f, -0.155145f, -0.129632f, 0.791738f, -0.183611f, -0.058705f, 0.847012f, -0.165562f, 0.001980f, 0.833386f, -0.220084f, 0.019914f, 0.768935f, -0.255730f, 0.090306f, 0.670782f, -0.255594f, 0.113833f, 0.663389f, -0.226380f, 0.212655f, 0.617740f, -0.003367f, -0.195342f, 0.799680f, -0.029743f, -0.210508f, 0.827180f, -0.003818f, -0.194783f, 0.873636f, -0.004116f, -0.157907f, 0.931268f, -0.031280f, -0.184555f, 0.889476f, -0.059885f, -0.184448f, 0.841330f, -0.135333f, -0.164332f, 0.878200f, -0.085574f, -0.170948f, 0.925547f, -0.163833f, -0.094170f, 0.897114f, -0.138444f, -0.104250f, 0.945975f, -0.083497f, -0.084934f, 0.979607f, -0.004433f, -0.146642f, 0.985872f, -0.150715f, 0.032650f, 0.884111f, -0.135892f, -0.035520f, 0.945455f, -0.070612f, 0.036849f, 0.975733f, -0.004458f, -0.042526f, 1.015670f, -0.004249f, 0.046042f, 1.003240f, -0.086969f, 0.133224f, 0.947633f, -0.003873f, 0.161605f, 0.970499f, -0.125544f, 0.140012f, 0.917678f, -0.125651f, 0.250246f, 0.857602f, -0.003127f, 0.284070f, 0.878870f, -0.159174f, 0.125726f, 0.888878f, -0.183807f, 0.196970f, 0.844480f, -0.159890f, 0.291736f, 0.732480f, -0.199495f, 0.207230f, 0.779864f, -0.206182f, 0.164608f, 0.693257f, -0.186315f, 0.160689f, 0.817193f, -0.192827f, 0.166706f, 0.782271f, -0.175112f, 0.110008f, 0.860621f, -0.161022f, 0.057420f, 0.855111f, -0.172319f, 0.036155f, 0.816189f, -0.190318f, 0.064083f, 0.760605f, -0.195072f, 0.129179f, 0.731104f, -0.203126f, 0.410287f, 0.680536f, -0.216677f, 0.309274f, 0.642272f, -0.241515f, 0.311485f, 0.587832f, -0.002209f, 0.366663f, 0.749413f, -0.088230f, 0.396265f, 0.678635f, -0.170147f, 0.109517f, 0.840784f, -0.160521f, 0.067766f, 0.830650f, -0.181546f, 0.139805f, 0.812146f, -0.180495f, 0.148568f, 0.776087f, -0.180255f, 0.129125f, 0.744192f, -0.186298f, 0.078308f, 0.769352f, -0.167622f, 0.060539f, 0.806675f, -0.189876f, 0.102760f, 0.802582f, -0.108340f, 0.455446f, 0.657174f, -0.241585f, 0.527592f, 0.669296f, -0.265676f, 0.513366f, 0.634594f, -0.203073f, 0.478550f, 0.581526f, -0.266772f, 0.642330f, 0.602061f, -0.216961f, 0.564846f, 0.535435f, -0.202210f, 0.525495f, 0.475944f, -0.193888f, 0.467925f, 0.520606f, -0.265837f, 0.757267f, 0.500933f, -0.240306f, 0.653440f, 0.463215f, -0.309239f, 0.776868f, 0.304726f, -0.271009f, 0.683094f, 0.382018f, -0.312111f, 0.671099f, 0.286687f, -0.268791f, 0.624342f, 0.377231f, -0.302457f, 0.533996f, 0.360289f, -0.263656f, 0.529310f, 0.412564f, -0.282311f, 0.415167f, 0.447666f, -0.239201f, 0.442096f, 0.495604f, -0.220043f, 0.569026f, 0.445877f, -0.001263f, 0.395631f, 0.602029f, -0.057345f, 0.442535f, 0.572224f, -0.088927f, 0.506333f, 0.529106f, -0.125738f, 0.535076f, 0.612913f, -0.126251f, 0.577170f, 0.483159f, -0.149594f, 0.611520f, 0.557731f, -0.163188f, 0.660791f, 0.491080f, -0.172482f, 0.663387f, 0.415416f, -0.160464f, 0.591710f, 0.370659f, -0.156445f, 0.536396f, 0.378302f, -0.136496f, 0.444358f, 0.425226f, -0.095564f, 0.373768f, 0.473659f, -0.104146f, 0.315912f, 0.498104f, -0.000496f, 0.384194f, 0.473817f, -0.000183f, 0.297770f, 0.401486f, -0.129042f, 0.270145f, 0.434495f, 0.000100f, 0.272963f, 0.349138f, -0.113060f, 0.236984f, 0.385554f, 0.007260f, 0.016311f, -0.883396f, 0.007865f, 0.122104f, -0.956137f, -0.032842f, 0.115282f, -0.953252f, -0.089115f, 0.108449f, -0.950317f, -0.047440f, 0.014729f, -0.882756f, -0.104458f, 0.013137f, -0.882070f, -0.086439f, -0.584866f, -0.608343f, -0.115026f, -0.662605f, -0.436732f, -0.071683f, -0.665372f, -0.606385f, -0.257884f, -0.665381f, -0.658052f, -0.272542f, -0.665381f, -0.592063f, -0.371322f, -0.665382f, -0.353620f, -0.372362f, -0.665381f, -0.224420f, -0.335166f, -0.665380f, -0.078623f, -0.225999f, -0.665375f, -0.038981f, -0.106719f, -0.665374f, -0.186351f, -0.081749f, -0.665372f, -0.292554f, 0.006943f, -0.091505f, -0.858354f, 0.006117f, -0.280985f, -0.769967f, 0.004495f, -0.502360f, -0.559799f, -0.198638f, -0.302135f, -0.845816f, -0.237395f, -0.542544f, -0.587188f, -0.270001f, -0.279489f, -0.669861f, -0.134547f, -0.119852f, -0.959004f, -0.052088f, -0.122463f, -0.944549f, -0.124463f, -0.293508f, -0.899566f, -0.047616f, -0.289643f, -0.879292f, -0.168595f, -0.529132f, -0.654931f, -0.099793f, -0.515719f, -0.645873f, -0.186168f, -0.605282f, -0.724690f, -0.112970f, -0.583097f, -0.707469f, -0.108152f, -0.665375f, -0.700408f, -0.183019f, -0.665378f, -0.717630f, -0.349529f, -0.334459f, -0.511985f, -0.141182f, -0.437705f, -0.798194f, -0.212670f, -0.448725f, -0.737447f, -0.261111f, -0.414945f, -0.613835f, -0.077364f, -0.431480f, -0.778113f, 0.005174f, -0.425277f, -0.651592f, 0.089236f, -0.431732f, -0.777093f, 0.271006f, -0.415749f, -0.610577f, 0.223981f, -0.449384f, -0.734774f, 0.153275f, -0.438150f, -0.796391f, 0.358414f, -0.335529f, -0.507649f, 0.193434f, -0.665946f, -0.715325f, 0.118363f, -0.665717f, -0.699021f, 0.123515f, -0.583454f, -0.706020f, 0.196851f, -0.605860f, -0.722345f, 0.109788f, -0.516035f, -0.644590f, 0.178656f, -0.529656f, -0.652804f, 0.061157f, -0.289807f, -0.878626f, 0.138234f, -0.293905f, -0.897958f, 0.066933f, -0.122643f, -0.943820f, 0.149571f, -0.120281f, -0.957264f, 0.280989f, -0.280321f, -0.666487f, 0.246581f, -0.543275f, -0.584224f, 0.211720f, -0.302754f, -0.843303f, 0.086966f, -0.665627f, -0.291520f, 0.110634f, -0.665702f, -0.185021f, 0.228099f, -0.666061f, -0.036201f, 0.337743f, -0.666396f, -0.074503f, 0.376722f, -0.666513f, -0.219833f, 0.377265f, -0.666513f, -0.349036f, 0.281411f, -0.666217f, -0.588670f, 0.267564f, -0.666174f, -0.654834f, 0.080745f, -0.665602f, -0.605452f, 0.122016f, -0.662963f, -0.435280f, 0.095767f, -0.585141f, -0.607228f, 0.118944f, 0.012799f, -0.880702f, 0.061944f, 0.014564f, -0.882086f, 0.104725f, 0.108156f, -0.949130f, 0.048513f, 0.115159f, -0.952753f, 0.112696f, 0.236643f, 0.386937f, 0.128177f, 0.269757f, 0.436071f, 0.102643f, 0.315600f, 0.499370f, 0.094535f, 0.373481f, 0.474824f, 0.136270f, 0.443946f, 0.426895f, 0.157071f, 0.535923f, 0.380222f, 0.161350f, 0.591224f, 0.372630f, 0.173035f, 0.662865f, 0.417531f, 0.162808f, 0.660299f, 0.493077f, 0.148250f, 0.611070f, 0.559555f, 0.125719f, 0.576790f, 0.484702f, 0.123489f, 0.534699f, 0.614440f, 0.087621f, 0.506066f, 0.530188f, 0.055321f, 0.442365f, 0.572915f, 0.219936f, 0.568361f, 0.448571f, 0.238099f, 0.441375f, 0.498528f, 0.281711f, 0.414315f, 0.451121f, 0.263833f, 0.528513f, 0.415794f, 0.303284f, 0.533081f, 0.363998f, 0.269687f, 0.623528f, 0.380528f, 0.314255f, 0.670153f, 0.290524f, 0.272023f, 0.682273f, 0.385343f, 0.311480f, 0.775931f, 0.308527f, 0.240239f, 0.652714f, 0.466159f, 0.265619f, 0.756464f, 0.504187f, 0.192562f, 0.467341f, 0.522972f, 0.201605f, 0.524885f, 0.478417f, 0.215743f, 0.564193f, 0.538084f, 0.264969f, 0.641527f, 0.605317f, 0.201031f, 0.477940f, 0.584002f, 0.263086f, 0.512567f, 0.637832f, 0.238615f, 0.526867f, 0.672237f, 0.105309f, 0.455123f, 0.658482f, 0.183993f, 0.102195f, 0.804872f, 0.161563f, 0.060042f, 0.808692f, 0.180748f, 0.077754f, 0.771600f, 0.175168f, 0.128588f, 0.746368f, 0.175075f, 0.148030f, 0.778264f, 0.175658f, 0.139265f, 0.814333f, 0.154191f, 0.067291f, 0.832578f, 0.163818f, 0.109013f, 0.842830f, 0.084760f, 0.396004f, 0.679695f, 0.238888f, 0.310760f, 0.590775f, 0.213380f, 0.308625f, 0.644905f, 0.199666f, 0.409678f, 0.683003f, 0.190143f, 0.128597f, 0.733463f, 0.184833f, 0.063516f, 0.762902f, 0.166070f, 0.035644f, 0.818261f, 0.154361f, 0.056943f, 0.857042f, 0.168542f, 0.109489f, 0.862725f, 0.187387f, 0.166131f, 0.784599f, 0.180428f, 0.160135f, 0.819438f, 0.201823f, 0.163991f, 0.695756f, 0.194206f, 0.206635f, 0.782275f, 0.155438f, 0.291260f, 0.734412f, 0.177696f, 0.196424f, 0.846693f, 0.152305f, 0.125256f, 0.890786f, 0.119546f, 0.249876f, 0.859104f, 0.118369f, 0.139643f, 0.919173f, 0.079410f, 0.132973f, 0.948652f, 0.062419f, 0.036648f, 0.976547f, 0.127847f, -0.035919f, 0.947070f, 0.143624f, 0.032206f, 0.885913f, 0.074888f, -0.085173f, 0.980577f, 0.130184f, -0.104656f, 0.947620f, 0.156201f, -0.094653f, 0.899074f, 0.077366f, -0.171194f, 0.926545f, 0.127722f, -0.164729f, 0.879810f, 0.052670f, -0.184618f, 0.842019f, 0.023477f, -0.184638f, 0.889811f, 0.022626f, -0.210587f, 0.827500f, 0.223089f, 0.211976f, 0.620493f, 0.251444f, 0.113067f, 0.666494f, 0.251419f, 0.089540f, 0.673887f, 0.214360f, 0.019258f, 0.771595f, 0.158999f, 0.001490f, 0.835374f, 0.176696f, -0.059249f, 0.849218f, 0.148696f, -0.130091f, 0.793599f, 0.108290f, -0.166528f, 0.772088f, 0.049820f, -0.201382f, 0.764454f, 0.071341f, -0.215195f, 0.697209f, 0.073148f, -0.214475f, 0.623510f, 0.140502f, -0.169461f, 0.699354f, 0.163374f, -0.157073f, 0.611416f, 0.189466f, -0.138550f, 0.730366f, 0.247593f, -0.082554f, 0.759610f, 0.227468f, -0.121982f, 0.590197f, 0.284702f, -0.006586f, 0.535347f, 0.275741f, 0.125287f, 0.446676f, 0.266650f, 0.192594f, 0.506044f, 0.300086f, 0.053287f, 0.629620f, 0.055450f, -0.663935f, 0.375065f, 0.122854f, -0.664138f, 0.482323f, 0.046520f, -0.531571f, 0.391918f, 0.024824f, -0.568450f, 0.275106f, 0.053855f, -0.663931f, 0.328224f, 0.112829f, -0.453549f, 0.305788f, 0.131265f, -0.510617f, 0.080746f, 0.061174f, -0.430716f, -0.042710f, 0.341019f, -0.532887f, -0.208150f, 0.347705f, -0.623533f, -0.081139f, 0.238040f, -0.610732f, -0.038037f, 0.211764f, -0.514274f, -0.132078f, 0.120605f, -0.600219f, -0.186856f, 0.096985f, -0.584476f, -0.293357f, 0.127621f, -0.581941f, -0.437170f, 0.165902f, -0.477425f, -0.291453f, 0.077720f, -0.417975f, -0.220519f, 0.320892f, -0.506363f, -0.320874f, 0.248214f, -0.465684f, -0.239842f, 0.118764f, -0.383338f, -0.187114f, 0.118816f, -0.430106f, -0.123307f, 0.094131f, -0.419464f, -0.044777f, 0.274526f, -0.261706f, 0.005110f, 0.259842f, -0.283292f, -0.003185f, 0.222861f, -0.340431f, -0.038210f, 0.204445f, -0.664380f, 0.513353f, 0.259286f, -0.664547f, 0.471281f, 0.185402f, -0.476020f, 0.421718f, 0.279163f, -0.664604f, 0.417328f, 0.277157f, -0.528122f, 0.400208f, 0.183069f, -0.509812f, 0.329995f, 0.282599f, -0.429210f, 0.059242f, 0.254816f, -0.664541f, 0.290687f, 0.271436f, -0.567707f, 0.263966f, 0.386561f, -0.625221f, -0.216870f, 0.387086f, -0.630883f, -0.346073f, 0.380021f, -0.596021f, -0.318679f, 0.291269f, -0.619007f, -0.585707f, 0.339280f, -0.571198f, -0.461946f, 0.400045f, -0.489778f, -0.422640f, 0.406817f, -0.314349f, -0.371230f, 0.300588f, -0.281718f, -0.170549f, 0.290866f, -0.277304f, -0.061905f, 0.187735f, -0.241545f, 0.509437f, 0.188032f, -0.287569f, 0.424234f, 0.227520f, -0.373262f, 0.293102f, 0.266526f, -0.273650f, 0.039597f, 0.291592f, -0.291676f, 0.111386f, 0.291914f, -0.122741f, 0.422683f, 0.297574f, -0.156119f, 0.373368f, 0.286603f, -0.232731f, 0.027162f, 0.364663f, -0.201399f, 0.206850f, 0.353855f, -0.132408f, 0.149228f, 0.282208f, -0.019715f, 0.314960f, 0.331187f, -0.099266f, 0.092701f, 0.375463f, -0.093120f, -0.006467f, 0.375917f, -0.101236f, -0.154882f, 0.466635f, -0.094416f, -0.305669f, 0.455805f, -0.119881f, -0.460632f, 0.277465f, -0.604242f, -0.651871f, 0.261022f, -0.551176f, -0.554667f, 0.093627f, 0.258494f, -0.920589f, 0.114248f, 0.310608f, -0.798070f, 0.144232f, 0.211434f, -0.835001f, 0.119916f, 0.176940f, -0.951159f, 0.184061f, 0.101854f, -0.918220f, 0.092431f, 0.276521f, -0.738231f, 0.133504f, 0.218403f, -0.758602f, 0.194987f, 0.097655f, -0.812476f, 0.185542f, 0.011005f, -0.879202f, 0.230315f, -0.127450f, -0.884202f, 0.260471f, 0.255056f, -0.624378f, 0.351567f, -0.042194f, -0.663976f, 0.253742f, 0.323524f, -0.433716f, 0.411612f, 0.132299f, -0.438264f, 0.270513f, 0.356530f, -0.289984f, 0.422146f, 0.162819f, -0.273130f, 0.164724f, 0.237490f, 0.208912f, 0.253806f, 0.092900f, 0.240640f, 0.203608f, 0.284597f, 0.096223f, 0.241006f, 0.343093f, -0.171396f, 0.356076f, 0.149288f, -0.143443f, 0.337656f, 0.131992f, 0.066374f }; public static int[] Indices = { 126,134,133, 342,138,134, 133,134,138, 126,342,134, 312,316,317, 169,163,162, 312,317,319, 312,319,318, 169,162,164, 169,168,163, 312,314,315, 169,164,165, 169,167,168, 312,315,316, 312,313,314, 169,165,166, 169,166,167, 312,318,313, 308,304,305, 308,305,306, 179,181,188, 177,173,175, 177,175,176, 302,293,300, 322,294,304, 188,176,175, 188,175,179, 158,177,187, 305,293,302, 305,302,306, 322,304,308, 188,181,183, 158,173,177, 293,298,300, 304,294,296, 304,296,305, 185,176,188, 185,188,183, 187,177,176, 187,176,185, 305,296,298, 305,298,293, 436,432, 28, 436, 28, 23, 434,278,431, 30,208,209, 30,209, 29, 19, 20, 24, 208,207,211, 208,211,209, 19,210,212, 433,434,431, 433,431,432, 433,432,436, 436,437,433, 277,275,276, 277,276,278, 209,210, 25, 21, 26, 24, 21, 24, 20, 25, 26, 27, 25, 27, 29, 435,439,277, 439,275,277, 432,431, 30, 432, 30, 28, 433,437,438, 433,438,435, 434,277,278, 24, 25,210, 24, 26, 25, 29, 27, 28, 29, 28, 30, 19, 24,210, 208, 30,431, 208,431,278, 435,434,433, 435,277,434, 25, 29,209, 27, 22, 23, 27, 23, 28, 26, 22, 27, 26, 21, 22, 212,210,209, 212,209,211, 207,208,278, 207,278,276, 439,435,438, 12, 9, 10, 12, 10, 13, 2, 3, 5, 2, 5, 4, 16, 13, 14, 16, 14, 17, 22, 21, 16, 13, 10, 11, 13, 11, 14, 1, 0, 3, 1, 3, 2, 15, 12, 16, 19, 18, 15, 19, 15, 16, 19, 16, 20, 9, 1, 2, 9, 2, 10, 3, 7, 8, 3, 8, 5, 16, 17, 23, 16, 23, 22, 21, 20, 16, 10, 2, 4, 10, 4, 11, 0, 6, 7, 0, 7, 3, 12, 13, 16, 451,446,445, 451,445,450, 442,440,439, 442,439,438, 442,438,441, 421,420,422, 412,411,426, 412,426,425, 408,405,407, 413, 67, 68, 413, 68,414, 391,390,412, 80,384,386, 404,406,378, 390,391,377, 390,377, 88, 400,415,375, 398,396,395, 398,395,371, 398,371,370, 112,359,358, 112,358,113, 351,352,369, 125,349,348, 345,343,342, 342,340,339, 341,335,337, 328,341,327, 331,323,333, 331,322,323, 327,318,319, 327,319,328, 315,314,324, 302,300,301, 302,301,303, 320,311,292, 285,284,289, 310,307,288, 310,288,290, 321,350,281, 321,281,282, 423,448,367, 272,273,384, 272,384,274, 264,265,382, 264,382,383, 440,442,261, 440,261,263, 252,253,254, 252,254,251, 262,256,249, 262,249,248, 228,243,242, 228, 31,243, 213,215,238, 213,238,237, 19,212,230, 224,225,233, 224,233,231, 217,218, 56, 217, 56, 54, 217,216,239, 217,239,238, 217,238,215, 218,217,215, 218,215,214, 6,102,206, 186,199,200, 197,182,180, 170,171,157, 201,200,189, 170,190,191, 170,191,192, 175,174,178, 175,178,179, 168,167,155, 122,149,158, 122,158,159, 135,153,154, 135,154,118, 143,140,141, 143,141,144, 132,133,136, 130,126,133, 124,125,127, 122,101,100, 122,100,121, 110,108,107, 110,107,109, 98, 99, 97, 98, 97, 64, 98, 64, 66, 87, 55, 57, 83, 82, 79, 83, 79, 84, 78, 74, 50, 49, 71, 41, 49, 41, 37, 49, 37, 36, 58, 44, 60, 60, 59, 58, 51, 34, 33, 39, 40, 42, 39, 42, 38, 243,240, 33, 243, 33,229, 39, 38, 6, 44, 46, 40, 55, 56, 57, 64, 62, 65, 64, 65, 66, 41, 71, 45, 75, 50, 51, 81, 79, 82, 77, 88, 73, 93, 92, 94, 68, 47, 46, 96, 97, 99, 96, 99, 95, 110,109,111, 111,112,110, 114,113,123, 114,123,124, 132,131,129, 133,137,136, 135,142,145, 145,152,135, 149,147,157, 157,158,149, 164,150,151, 153,163,168, 153,168,154, 185,183,182, 185,182,184, 161,189,190, 200,199,191, 200,191,190, 180,178,195, 180,195,196, 102,101,204, 102,204,206, 43, 48,104, 43,104,103, 216,217, 54, 216, 54, 32, 207,224,231, 230,212,211, 230,211,231, 227,232,241, 227,241,242, 235,234,241, 235,241,244, 430,248,247, 272,274,253, 272,253,252, 439,260,275, 225,224,259, 225,259,257, 269,270,407, 269,407,405, 270,269,273, 270,273,272, 273,269,268, 273,268,267, 273,267,266, 273,266,265, 273,265,264, 448,279,367, 281,350,368, 285,286,301, 290,323,310, 290,311,323, 282,281,189, 292,311,290, 292,290,291, 307,306,302, 307,302,303, 316,315,324, 316,324,329, 331,351,350, 330,334,335, 330,335,328, 341,337,338, 344,355,354, 346,345,348, 346,348,347, 364,369,352, 364,352,353, 365,363,361, 365,361,362, 376,401,402, 373,372,397, 373,397,400, 376, 92,377, 381,378,387, 381,387,385, 386, 77, 80, 390,389,412, 416,417,401, 403,417,415, 408,429,430, 419,423,418, 427,428,444, 427,444,446, 437,436,441, 450,445, 11, 450, 11, 4, 447,449, 5, 447, 5, 8, 441,438,437, 425,426,451, 425,451,452, 417,421,415, 408,407,429, 399,403,400, 399,400,397, 394,393,416, 389,411,412, 386,383,385, 408,387,378, 408,378,406, 377,391,376, 94,375,415, 372,373,374, 372,374,370, 359,111,360, 359,112,111, 113,358,349, 113,349,123, 346,343,345, 343,340,342, 338,336,144, 338,144,141, 327,341,354, 327,354,326, 331,350,321, 331,321,322, 314,313,326, 314,326,325, 300,298,299, 300,299,301, 288,287,289, 189,292,282, 287,288,303, 284,285,297, 368,280,281, 448,447,279, 274,226,255, 267,268,404, 267,404,379, 429,262,430, 439,440,260, 257,258,249, 257,249,246, 430,262,248, 234,228,242, 234,242,241, 237,238,239, 237,239,236, 15, 18,227, 15,227,229, 222,223, 82, 222, 82, 83, 214,215,213, 214,213, 81, 38,102, 6, 122,159,200, 122,200,201, 174,171,192, 174,192,194, 197,193,198, 190,170,161, 181,179,178, 181,178,180, 166,156,155, 163,153,152, 163,152,162, 120,156,149, 120,149,121, 152,153,135, 140,143,142, 135,131,132, 135,132,136, 130,129,128, 130,128,127, 100,105,119, 100,119,120, 106,104,107, 106,107,108, 91, 95, 59, 93, 94, 68, 91, 89, 92, 76, 53, 55, 76, 55, 87, 81, 78, 79, 74, 73, 49, 69, 60, 45, 58, 62, 64, 58, 64, 61, 53, 31, 32, 32, 54, 53, 42, 43, 38, 35, 36, 0, 35, 0, 1, 34, 35, 1, 34, 1, 9, 44, 40, 41, 44, 41, 45, 33,240, 51, 63, 62, 58, 63, 58, 59, 45, 71, 70, 76, 75, 51, 76, 51, 52, 86, 85, 84, 86, 84, 87, 89, 72, 73, 89, 73, 88, 91, 92, 96, 91, 96, 95, 72, 91, 60, 72, 60, 69, 104,106,105, 119,105,117, 119,117,118, 124,127,128, 117,116,129, 117,129,131, 118,117,131, 135,140,142, 146,150,152, 146,152,145, 149,122,121, 166,165,151, 166,151,156, 158,172,173, 161,160,189, 199,198,193, 199,193,191, 204,201,202, 178,174,194, 200,159,186, 109, 48, 67, 48,107,104, 216, 32,236, 216,236,239, 223,214, 81, 223, 81, 82, 33, 12, 15, 32,228,234, 32,234,236, 240, 31, 52, 256,255,246, 256,246,249, 258,263,248, 258,248,249, 275,260,259, 275,259,276, 207,276,259, 270,271,429, 270,429,407, 413,418,366, 413,366,365, 368,367,279, 368,279,280, 303,301,286, 303,286,287, 283,282,292, 283,292,291, 320,292,189, 298,296,297, 298,297,299, 318,327,326, 318,326,313, 329,330,317, 336,333,320, 326,354,353, 334,332,333, 334,333,336, 342,339,139, 342,139,138, 345,342,126, 347,357,356, 369,368,351, 363,356,357, 363,357,361, 366,367,368, 366,368,369, 375,373,400, 92, 90,377, 409,387,408, 386,385,387, 386,387,388, 412,394,391, 396,398,399, 408,406,405, 415,421,419, 415,419,414, 425,452,448, 425,448,424, 444,441,443, 448,452,449, 448,449,447, 446,444,443, 446,443,445, 250,247,261, 250,261,428, 421,422,423, 421,423,419, 427,410,250, 417,403,401, 403,402,401, 420,392,412, 420,412,425, 420,425,424, 386,411,389, 383,382,381, 383,381,385, 378,379,404, 372,371,395, 372,395,397, 371,372,370, 361,359,360, 361,360,362, 368,350,351, 349,347,348, 356,355,344, 356,344,346, 344,341,340, 344,340,343, 338,337,336, 328,335,341, 324,352,351, 324,351,331, 320,144,336, 314,325,324, 322,308,309, 310,309,307, 287,286,289, 203,280,279, 203,279,205, 297,295,283, 297,283,284, 447,205,279, 274,384, 80, 274, 80,226, 266,267,379, 266,379,380, 225,257,246, 225,246,245, 256,254,253, 256,253,255, 430,247,250, 226,235,244, 226,244,245, 232,233,244, 232,244,241, 230, 18, 19, 32, 31,228, 219,220, 86, 219, 86, 57, 226,213,235, 206, 7, 6, 122,201,101, 201,204,101, 180,196,197, 170,192,171, 200,190,189, 194,193,195, 183,181,180, 183,180,182, 155,154,168, 149,156,151, 149,151,148, 155,156,120, 145,142,143, 145,143,146, 136,137,140, 133,132,130, 128,129,116, 100,120,121, 110,112,113, 110,113,114, 66, 65, 63, 66, 63, 99, 66, 99, 98, 96, 46, 61, 89, 88, 90, 86, 87, 57, 80, 78, 81, 72, 69, 49, 67, 48, 47, 67, 47, 68, 56, 55, 53, 50, 49, 36, 50, 36, 35, 40, 39, 41, 242,243,229, 242,229,227, 6, 37, 39, 42, 47, 48, 42, 48, 43, 61, 46, 44, 45, 70, 69, 69, 70, 71, 69, 71, 49, 74, 78, 77, 83, 84, 85, 73, 74, 77, 93, 96, 92, 68, 46, 93, 95, 99, 63, 95, 63, 59, 115,108,110, 115,110,114, 125,126,127, 129,130,132, 137,133,138, 137,138,139, 148,146,143, 148,143,147, 119,118,154, 161,147,143, 165,164,151, 158,157,171, 158,171,172, 159,158,187, 159,187,186, 194,192,191, 194,191,193, 189,202,201, 182,197,184, 205, 8, 7, 48,109,107, 218,219, 57, 218, 57, 56, 207,231,211, 232,230,231, 232,231,233, 53, 52, 31, 388,411,386, 409,430,250, 262,429,254, 262,254,256, 442,444,428, 273,264,383, 273,383,384, 429,271,251, 429,251,254, 413,365,362, 67,413,360, 282,283,295, 285,301,299, 202,281,280, 284,283,291, 284,291,289, 320,189,160, 308,306,307, 307,309,308, 319,317,330, 319,330,328, 353,352,324, 332,331,333, 340,341,338, 354,341,344, 349,358,357, 349,357,347, 364,355,356, 364,356,363, 364,365,366, 364,366,369, 374,376,402, 375, 92,373, 77,389,390, 382,380,381, 389, 77,386, 393,394,412, 393,412,392, 401,394,416, 415,400,403, 411,410,427, 411,427,426, 422,420,424, 247,248,263, 247,263,261, 445,443, 14, 445, 14, 11, 449,450, 4, 449, 4, 5, 443,441, 17, 443, 17, 14, 436, 23, 17, 436, 17,441, 424,448,422, 448,423,422, 414,419,418, 414,418,413, 406,404,405, 399,397,395, 399,395,396, 420,416,392, 388,410,411, 386,384,383, 390, 88, 77, 375, 94, 92, 415,414, 68, 415, 68, 94, 370,374,402, 370,402,398, 361,357,358, 361,358,359, 125,348,126, 346,344,343, 340,338,339, 337,335,334, 337,334,336, 325,353,324, 324,331,332, 324,332,329, 323,322,309, 323,309,310, 294,295,297, 294,297,296, 289,286,285, 202,280,203, 288,307,303, 282,295,321, 67,360,111, 418,423,367, 418,367,366, 272,252,251, 272,251,271, 272,271,270, 255,253,274, 265,266,380, 265,380,382, 442,428,261, 440,263,258, 440,258,260, 409,250,410, 255,226,245, 255,245,246, 31,240,243, 236,234,235, 236,235,237, 233,225,245, 233,245,244, 220,221, 85, 220, 85, 86, 81,213,226, 81,226, 80, 7,206,205, 186,184,198, 186,198,199, 204,203,205, 204,205,206, 195,193,196, 171,174,172, 173,174,175, 173,172,174, 155,167,166, 160,161,143, 160,143,144, 119,154,155, 148,151,150, 148,150,146, 140,137,139, 140,139,141, 127,126,130, 114,124,128, 114,128,115, 117,105,106, 117,106,116, 104,105,100, 104,100,103, 59, 60, 91, 97, 96, 61, 97, 61, 64, 91, 72, 89, 87, 84, 79, 87, 79, 76, 78, 80, 77, 49, 50, 74, 60, 44, 45, 61, 44, 58, 51, 50, 35, 51, 35, 34, 39, 37, 41, 33, 34, 9, 33, 9, 12, 0, 36, 37, 0, 37, 6, 40, 46, 47, 40, 47, 42, 53, 54, 56, 65, 62, 63, 72, 49, 73, 79, 78, 75, 79, 75, 76, 52, 53, 76, 92, 89, 90, 96, 93, 46, 102,103,100, 102,100,101, 116,106,108, 116,108,115, 123,125,124, 116,115,128, 118,131,135, 140,135,136, 148,147,149, 120,119,155, 164,162,152, 164,152,150, 157,147,161, 157,161,170, 186,187,185, 186,185,184, 193,197,196, 202,203,204, 194,195,178, 198,184,197, 67,111,109, 38, 43,103, 38,103,102, 214,223,222, 214,222,221, 214,221,220, 214,220,219, 214,219,218, 213,237,235, 221,222, 83, 221, 83, 85, 15,229, 33, 227, 18,230, 227,230,232, 52, 51,240, 75, 78, 50, 408,430,409, 260,258,257, 260,257,259, 224,207,259, 268,269,405, 268,405,404, 413,362,360, 447, 8,205, 299,297,285, 189,281,202, 290,288,289, 290,289,291, 322,321,295, 322,295,294, 333,323,311, 333,311,320, 317,316,329, 320,160,144, 353,325,326, 329,332,334, 329,334,330, 339,338,141, 339,141,139, 348,345,126, 347,356,346, 123,349,125, 364,353,354, 364,354,355, 365,364,363, 376,391,394, 376,394,401, 92,376,374, 92,374,373, 377, 90, 88, 380,379,378, 380,378,381, 388,387,409, 388,409,410, 416,393,392, 399,398,402, 399,402,403, 250,428,427, 421,417,416, 421,416,420, 426,427,446, 426,446,451, 444,442,441, 452,451,450, 452,450,449 }; } }
/* * Copyright (c) 2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections.Generic; #if VISUAL_STUDIO using ReaderWriterLockImpl = System.Threading.ReaderWriterLockSlim; #else using ReaderWriterLockImpl = OpenMetaverse.ReaderWriterLockSlim; #endif namespace OpenMetaverse { public class DoubleDictionary<TKey1, TKey2, TValue> { Dictionary<TKey1, TValue> Dictionary1; Dictionary<TKey2, TValue> Dictionary2; ReaderWriterLockImpl rwLock = new ReaderWriterLockImpl(); public DoubleDictionary() { Dictionary1 = new Dictionary<TKey1,TValue>(); Dictionary2 = new Dictionary<TKey2,TValue>(); } public DoubleDictionary(int capacity) { Dictionary1 = new Dictionary<TKey1, TValue>(capacity); Dictionary2 = new Dictionary<TKey2, TValue>(capacity); } public void Add(TKey1 key1, TKey2 key2, TValue value) { rwLock.EnterWriteLock(); try { if (Dictionary1.ContainsKey(key1)) { if (!Dictionary2.ContainsKey(key2)) throw new ArgumentException("key1 exists in the dictionary but not key2"); } else if (Dictionary2.ContainsKey(key2)) { if (!Dictionary1.ContainsKey(key1)) throw new ArgumentException("key2 exists in the dictionary but not key1"); } Dictionary1[key1] = value; Dictionary2[key2] = value; } finally { rwLock.ExitWriteLock(); } } public bool Remove(TKey1 key1, TKey2 key2) { bool success; rwLock.EnterWriteLock(); try { Dictionary1.Remove(key1); success = Dictionary2.Remove(key2); } finally { rwLock.ExitWriteLock(); } return success; } public bool Remove(TKey1 key1) { bool found = false; rwLock.EnterWriteLock(); try { // This is an O(n) operation! TValue value; if (Dictionary1.TryGetValue(key1, out value)) { foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2) { if (kvp.Value.Equals(value)) { Dictionary1.Remove(key1); Dictionary2.Remove(kvp.Key); found = true; break; } } } } finally { rwLock.ExitWriteLock(); } return found; } public bool Remove(TKey2 key2) { bool found = false; rwLock.EnterWriteLock(); try { // This is an O(n) operation! TValue value; if (Dictionary2.TryGetValue(key2, out value)) { foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1) { if (kvp.Value.Equals(value)) { Dictionary2.Remove(key2); Dictionary1.Remove(kvp.Key); found = true; break; } } } } finally { rwLock.ExitWriteLock(); } return found; } public void Clear() { rwLock.EnterWriteLock(); try { Dictionary1.Clear(); Dictionary2.Clear(); } finally { rwLock.ExitWriteLock(); } } public int Count { get { return Dictionary1.Count; } } public bool ContainsKey(TKey1 key) { return Dictionary1.ContainsKey(key); } public bool ContainsKey(TKey2 key) { return Dictionary2.ContainsKey(key); } public bool TryGetValue(TKey1 key, out TValue value) { bool success; rwLock.EnterReadLock(); try { success = Dictionary1.TryGetValue(key, out value); } finally { rwLock.ExitReadLock(); } return success; } public bool TryGetValue(TKey2 key, out TValue value) { bool success; rwLock.EnterReadLock(); try { success = Dictionary2.TryGetValue(key, out value); } finally { rwLock.ExitReadLock(); } return success; } public void ForEach(Action<TValue> action) { rwLock.EnterReadLock(); try { foreach (TValue value in Dictionary1.Values) action(value); } finally { rwLock.ExitReadLock(); } } public void ForEach(Action<KeyValuePair<TKey1, TValue>> action) { rwLock.EnterReadLock(); try { foreach (KeyValuePair<TKey1, TValue> entry in Dictionary1) action(entry); } finally { rwLock.ExitReadLock(); } } public void ForEach(Action<KeyValuePair<TKey2, TValue>> action) { rwLock.EnterReadLock(); try { foreach (KeyValuePair<TKey2, TValue> entry in Dictionary2) action(entry); } finally { rwLock.ExitReadLock(); } } public TValue FindValue(Predicate<TValue> predicate) { rwLock.EnterReadLock(); try { foreach (TValue value in Dictionary1.Values) { if (predicate(value)) return value; } } finally { rwLock.ExitReadLock(); } return default(TValue); } public IList<TValue> FindAll(Predicate<TValue> predicate) { IList<TValue> list = new List<TValue>(); rwLock.EnterReadLock(); try { foreach (TValue value in Dictionary1.Values) { if (predicate(value)) list.Add(value); } } finally { rwLock.ExitReadLock(); } return list; } public int RemoveAll(Predicate<TValue> predicate) { IList<TKey1> list = new List<TKey1>(); rwLock.EnterUpgradeableReadLock(); try { foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1) { if (predicate(kvp.Value)) list.Add(kvp.Key); } IList<TKey2> list2 = new List<TKey2>(list.Count); foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2) { if (predicate(kvp.Value)) list2.Add(kvp.Key); } rwLock.EnterWriteLock(); try { for (int i = 0; i < list.Count; i++) Dictionary1.Remove(list[i]); for (int i = 0; i < list2.Count; i++) Dictionary2.Remove(list2[i]); } finally { rwLock.ExitWriteLock(); } } finally { rwLock.ExitUpgradeableReadLock(); } return list.Count; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Last Years GL Financial Trans Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class GLFPREVDataSet : EduHubDataSet<GLFPREV> { /// <inheritdoc /> public override string Name { get { return "GLFPREV"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal GLFPREVDataSet(EduHubContext Context) : base(Context) { Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_FEE_CODE = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.FEE_CODE)); Index_GLPROGRAM = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.GLPROGRAM)); Index_GST_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.GST_TYPE)); Index_INITIATIVE = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.INITIATIVE)); Index_SUBPROGRAM = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.SUBPROGRAM)); Index_TID = new Lazy<Dictionary<int, GLFPREV>>(() => this.ToDictionary(i => i.TID)); Index_TRREF = new Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>>(() => this.ToGroupedNullDictionary(i => i.TRREF)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="GLFPREV" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="GLFPREV" /> fields for each CSV column header</returns> internal override Action<GLFPREV, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<GLFPREV, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = v; break; case "TRBATCH": mapper[i] = (e, v) => e.TRBATCH = v == null ? (int?)null : int.Parse(v); break; case "TRPERD": mapper[i] = (e, v) => e.TRPERD = v == null ? (int?)null : int.Parse(v); break; case "TRTYPE": mapper[i] = (e, v) => e.TRTYPE = v; break; case "TRQTY": mapper[i] = (e, v) => e.TRQTY = v == null ? (int?)null : int.Parse(v); break; case "TRDATE": mapper[i] = (e, v) => e.TRDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "TRREF": mapper[i] = (e, v) => e.TRREF = v; break; case "TRAMT": mapper[i] = (e, v) => e.TRAMT = v == null ? (decimal?)null : decimal.Parse(v); break; case "TRDET": mapper[i] = (e, v) => e.TRDET = v; break; case "TRXLEDGER": mapper[i] = (e, v) => e.TRXLEDGER = v; break; case "TRXCODE": mapper[i] = (e, v) => e.TRXCODE = v; break; case "TRXTRTYPE": mapper[i] = (e, v) => e.TRXTRTYPE = v; break; case "TRSHORT": mapper[i] = (e, v) => e.TRSHORT = v; break; case "TRBANK": mapper[i] = (e, v) => e.TRBANK = v; break; case "RECONCILE": mapper[i] = (e, v) => e.RECONCILE = v; break; case "RECONCILE_FLAGGED": mapper[i] = (e, v) => e.RECONCILE_FLAGGED = v; break; case "RECONCILE_DATE": mapper[i] = (e, v) => e.RECONCILE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "RECONCILE_USER": mapper[i] = (e, v) => e.RECONCILE_USER = v; break; case "RECONCILE_STATEMENT": mapper[i] = (e, v) => e.RECONCILE_STATEMENT = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "PRINT_CHEQUE": mapper[i] = (e, v) => e.PRINT_CHEQUE = v; break; case "CHEQUE_NO": mapper[i] = (e, v) => e.CHEQUE_NO = v; break; case "PAYEE": mapper[i] = (e, v) => e.PAYEE = v; break; case "ADDRESS01": mapper[i] = (e, v) => e.ADDRESS01 = v; break; case "ADDRESS02": mapper[i] = (e, v) => e.ADDRESS02 = v; break; case "CHQ_TID": mapper[i] = (e, v) => e.CHQ_TID = v == null ? (int?)null : int.Parse(v); break; case "GST_BOX": mapper[i] = (e, v) => e.GST_BOX = v; break; case "GST_PERD": mapper[i] = (e, v) => e.GST_PERD = v == null ? (int?)null : int.Parse(v); break; case "GST_AMOUNT": mapper[i] = (e, v) => e.GST_AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "TRNETT": mapper[i] = (e, v) => e.TRNETT = v == null ? (decimal?)null : decimal.Parse(v); break; case "TRGROSS": mapper[i] = (e, v) => e.TRGROSS = v == null ? (decimal?)null : decimal.Parse(v); break; case "GST_RATE": mapper[i] = (e, v) => e.GST_RATE = v == null ? (double?)null : double.Parse(v); break; case "GST_TYPE": mapper[i] = (e, v) => e.GST_TYPE = v; break; case "GST_RECLAIM": mapper[i] = (e, v) => e.GST_RECLAIM = v; break; case "GST_SALE_PURCH": mapper[i] = (e, v) => e.GST_SALE_PURCH = v; break; case "SOURCE_TID": mapper[i] = (e, v) => e.SOURCE_TID = v == null ? (int?)null : int.Parse(v); break; case "WITHHOLD_AMOUNT": mapper[i] = (e, v) => e.WITHHOLD_AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "WITHHOLD_TYPE": mapper[i] = (e, v) => e.WITHHOLD_TYPE = v; break; case "WITHHOLD_RATE": mapper[i] = (e, v) => e.WITHHOLD_RATE = v == null ? (double?)null : double.Parse(v); break; case "EOY_KEPT": mapper[i] = (e, v) => e.EOY_KEPT = v; break; case "DRAWER": mapper[i] = (e, v) => e.DRAWER = v; break; case "BSB": mapper[i] = (e, v) => e.BSB = v; break; case "BANK": mapper[i] = (e, v) => e.BANK = v; break; case "BRANCH": mapper[i] = (e, v) => e.BRANCH = v; break; case "ACCOUNT_NUMBER": mapper[i] = (e, v) => e.ACCOUNT_NUMBER = v == null ? (int?)null : int.Parse(v); break; case "RTYPE": mapper[i] = (e, v) => e.RTYPE = v; break; case "LINE_NO": mapper[i] = (e, v) => e.LINE_NO = v == null ? (int?)null : int.Parse(v); break; case "FLAG": mapper[i] = (e, v) => e.FLAG = v == null ? (int?)null : int.Parse(v); break; case "DEBIT_TOTAL": mapper[i] = (e, v) => e.DEBIT_TOTAL = v == null ? (decimal?)null : decimal.Parse(v); break; case "CREDIT_TOTAL": mapper[i] = (e, v) => e.CREDIT_TOTAL = v == null ? (decimal?)null : decimal.Parse(v); break; case "SUBPROGRAM": mapper[i] = (e, v) => e.SUBPROGRAM = v; break; case "GLPROGRAM": mapper[i] = (e, v) => e.GLPROGRAM = v; break; case "INITIATIVE": mapper[i] = (e, v) => e.INITIATIVE = v; break; case "DEBIT": mapper[i] = (e, v) => e.DEBIT = v == null ? (decimal?)null : decimal.Parse(v); break; case "CREDIT": mapper[i] = (e, v) => e.CREDIT = v == null ? (decimal?)null : decimal.Parse(v); break; case "CANCELLED": mapper[i] = (e, v) => e.CANCELLED = v; break; case "FEE_CODE": mapper[i] = (e, v) => e.FEE_CODE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="GLFPREV" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="GLFPREV" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="GLFPREV" /> entities</param> /// <returns>A merged <see cref="IEnumerable{GLFPREV}"/> of entities</returns> internal override IEnumerable<GLFPREV> ApplyDeltaEntities(IEnumerable<GLFPREV> Entities, List<GLFPREV> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<GLFPREV>>> Index_CODE; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_FEE_CODE; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_GLPROGRAM; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_GST_TYPE; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_INITIATIVE; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_SUBPROGRAM; private Lazy<Dictionary<int, GLFPREV>> Index_TID; private Lazy<NullDictionary<string, IReadOnlyList<GLFPREV>>> Index_TRREF; #endregion #region Index Methods /// <summary> /// Find GLFPREV by CODE field /// </summary> /// <param name="CODE">CODE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByCODE(string CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find GLFPREV by CODE field /// </summary> /// <param name="CODE">CODE value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(string CODE, out IReadOnlyList<GLFPREV> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find GLFPREV by CODE field /// </summary> /// <param name="CODE">CODE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByCODE(string CODE) { IReadOnlyList<GLFPREV> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by FEE_CODE field /// </summary> /// <param name="FEE_CODE">FEE_CODE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByFEE_CODE(string FEE_CODE) { return Index_FEE_CODE.Value[FEE_CODE]; } /// <summary> /// Attempt to find GLFPREV by FEE_CODE field /// </summary> /// <param name="FEE_CODE">FEE_CODE value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByFEE_CODE(string FEE_CODE, out IReadOnlyList<GLFPREV> Value) { return Index_FEE_CODE.Value.TryGetValue(FEE_CODE, out Value); } /// <summary> /// Attempt to find GLFPREV by FEE_CODE field /// </summary> /// <param name="FEE_CODE">FEE_CODE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByFEE_CODE(string FEE_CODE) { IReadOnlyList<GLFPREV> value; if (Index_FEE_CODE.Value.TryGetValue(FEE_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by GLPROGRAM field /// </summary> /// <param name="GLPROGRAM">GLPROGRAM value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByGLPROGRAM(string GLPROGRAM) { return Index_GLPROGRAM.Value[GLPROGRAM]; } /// <summary> /// Attempt to find GLFPREV by GLPROGRAM field /// </summary> /// <param name="GLPROGRAM">GLPROGRAM value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGLPROGRAM(string GLPROGRAM, out IReadOnlyList<GLFPREV> Value) { return Index_GLPROGRAM.Value.TryGetValue(GLPROGRAM, out Value); } /// <summary> /// Attempt to find GLFPREV by GLPROGRAM field /// </summary> /// <param name="GLPROGRAM">GLPROGRAM value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByGLPROGRAM(string GLPROGRAM) { IReadOnlyList<GLFPREV> value; if (Index_GLPROGRAM.Value.TryGetValue(GLPROGRAM, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByGST_TYPE(string GST_TYPE) { return Index_GST_TYPE.Value[GST_TYPE]; } /// <summary> /// Attempt to find GLFPREV by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGST_TYPE(string GST_TYPE, out IReadOnlyList<GLFPREV> Value) { return Index_GST_TYPE.Value.TryGetValue(GST_TYPE, out Value); } /// <summary> /// Attempt to find GLFPREV by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByGST_TYPE(string GST_TYPE) { IReadOnlyList<GLFPREV> value; if (Index_GST_TYPE.Value.TryGetValue(GST_TYPE, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByINITIATIVE(string INITIATIVE) { return Index_INITIATIVE.Value[INITIATIVE]; } /// <summary> /// Attempt to find GLFPREV by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByINITIATIVE(string INITIATIVE, out IReadOnlyList<GLFPREV> Value) { return Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out Value); } /// <summary> /// Attempt to find GLFPREV by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByINITIATIVE(string INITIATIVE) { IReadOnlyList<GLFPREV> value; if (Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindBySUBPROGRAM(string SUBPROGRAM) { return Index_SUBPROGRAM.Value[SUBPROGRAM]; } /// <summary> /// Attempt to find GLFPREV by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySUBPROGRAM(string SUBPROGRAM, out IReadOnlyList<GLFPREV> Value) { return Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out Value); } /// <summary> /// Attempt to find GLFPREV by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindBySUBPROGRAM(string SUBPROGRAM) { IReadOnlyList<GLFPREV> value; if (Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by TID field /// </summary> /// <param name="TID">TID value used to find GLFPREV</param> /// <returns>Related GLFPREV entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public GLFPREV FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find GLFPREV by TID field /// </summary> /// <param name="TID">TID value used to find GLFPREV</param> /// <param name="Value">Related GLFPREV entity</param> /// <returns>True if the related GLFPREV entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out GLFPREV Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find GLFPREV by TID field /// </summary> /// <param name="TID">TID value used to find GLFPREV</param> /// <returns>Related GLFPREV entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public GLFPREV TryFindByTID(int TID) { GLFPREV value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } /// <summary> /// Find GLFPREV by TRREF field /// </summary> /// <param name="TRREF">TRREF value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> FindByTRREF(string TRREF) { return Index_TRREF.Value[TRREF]; } /// <summary> /// Attempt to find GLFPREV by TRREF field /// </summary> /// <param name="TRREF">TRREF value used to find GLFPREV</param> /// <param name="Value">List of related GLFPREV entities</param> /// <returns>True if the list of related GLFPREV entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTRREF(string TRREF, out IReadOnlyList<GLFPREV> Value) { return Index_TRREF.Value.TryGetValue(TRREF, out Value); } /// <summary> /// Attempt to find GLFPREV by TRREF field /// </summary> /// <param name="TRREF">TRREF value used to find GLFPREV</param> /// <returns>List of related GLFPREV entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<GLFPREV> TryFindByTRREF(string TRREF) { IReadOnlyList<GLFPREV> value; if (Index_TRREF.Value.TryGetValue(TRREF, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a GLFPREV table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[GLFPREV]( [TID] int NOT NULL, [CODE] varchar(10) NOT NULL, [TRBATCH] int NULL, [TRPERD] int NULL, [TRTYPE] varchar(1) NULL, [TRQTY] int NULL, [TRDATE] datetime NULL, [TRREF] varchar(10) NULL, [TRAMT] money NULL, [TRDET] varchar(30) NULL, [TRXLEDGER] varchar(2) NULL, [TRXCODE] varchar(10) NULL, [TRXTRTYPE] varchar(1) NULL, [TRSHORT] varchar(10) NULL, [TRBANK] varchar(10) NULL, [RECONCILE] varchar(1) NULL, [RECONCILE_FLAGGED] varchar(1) NULL, [RECONCILE_DATE] datetime NULL, [RECONCILE_USER] varchar(128) NULL, [RECONCILE_STATEMENT] datetime NULL, [PRINT_CHEQUE] varchar(1) NULL, [CHEQUE_NO] varchar(10) NULL, [PAYEE] varchar(30) NULL, [ADDRESS01] varchar(30) NULL, [ADDRESS02] varchar(30) NULL, [CHQ_TID] int NULL, [GST_BOX] varchar(3) NULL, [GST_PERD] int NULL, [GST_AMOUNT] money NULL, [TRNETT] money NULL, [TRGROSS] money NULL, [GST_RATE] float NULL, [GST_TYPE] varchar(4) NULL, [GST_RECLAIM] varchar(1) NULL, [GST_SALE_PURCH] varchar(2) NULL, [SOURCE_TID] int NULL, [WITHHOLD_AMOUNT] money NULL, [WITHHOLD_TYPE] varchar(4) NULL, [WITHHOLD_RATE] float NULL, [EOY_KEPT] varchar(1) NULL, [DRAWER] varchar(20) NULL, [BSB] varchar(6) NULL, [BANK] varchar(20) NULL, [BRANCH] varchar(20) NULL, [ACCOUNT_NUMBER] int NULL, [RTYPE] varchar(2) NULL, [LINE_NO] int NULL, [FLAG] int NULL, [DEBIT_TOTAL] money NULL, [CREDIT_TOTAL] money NULL, [SUBPROGRAM] varchar(4) NULL, [GLPROGRAM] varchar(3) NULL, [INITIATIVE] varchar(3) NULL, [DEBIT] money NULL, [CREDIT] money NULL, [CANCELLED] varchar(3) NULL, [FEE_CODE] varchar(10) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [GLFPREV_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [GLFPREV_Index_CODE] ON [dbo].[GLFPREV] ( [CODE] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_FEE_CODE] ON [dbo].[GLFPREV] ( [FEE_CODE] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_GLPROGRAM] ON [dbo].[GLFPREV] ( [GLPROGRAM] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_GST_TYPE] ON [dbo].[GLFPREV] ( [GST_TYPE] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_INITIATIVE] ON [dbo].[GLFPREV] ( [INITIATIVE] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_SUBPROGRAM] ON [dbo].[GLFPREV] ( [SUBPROGRAM] ASC ); CREATE NONCLUSTERED INDEX [GLFPREV_Index_TRREF] ON [dbo].[GLFPREV] ( [TRREF] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_FEE_CODE') ALTER INDEX [GLFPREV_Index_FEE_CODE] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_GLPROGRAM') ALTER INDEX [GLFPREV_Index_GLPROGRAM] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_GST_TYPE') ALTER INDEX [GLFPREV_Index_GST_TYPE] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_INITIATIVE') ALTER INDEX [GLFPREV_Index_INITIATIVE] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_SUBPROGRAM') ALTER INDEX [GLFPREV_Index_SUBPROGRAM] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_TID') ALTER INDEX [GLFPREV_Index_TID] ON [dbo].[GLFPREV] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_TRREF') ALTER INDEX [GLFPREV_Index_TRREF] ON [dbo].[GLFPREV] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_FEE_CODE') ALTER INDEX [GLFPREV_Index_FEE_CODE] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_GLPROGRAM') ALTER INDEX [GLFPREV_Index_GLPROGRAM] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_GST_TYPE') ALTER INDEX [GLFPREV_Index_GST_TYPE] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_INITIATIVE') ALTER INDEX [GLFPREV_Index_INITIATIVE] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_SUBPROGRAM') ALTER INDEX [GLFPREV_Index_SUBPROGRAM] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_TID') ALTER INDEX [GLFPREV_Index_TID] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFPREV]') AND name = N'GLFPREV_Index_TRREF') ALTER INDEX [GLFPREV_Index_TRREF] ON [dbo].[GLFPREV] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="GLFPREV"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="GLFPREV"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<GLFPREV> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[GLFPREV] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the GLFPREV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the GLFPREV data set</returns> public override EduHubDataSetDataReader<GLFPREV> GetDataSetDataReader() { return new GLFPREVDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the GLFPREV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the GLFPREV data set</returns> public override EduHubDataSetDataReader<GLFPREV> GetDataSetDataReader(List<GLFPREV> Entities) { return new GLFPREVDataReader(new EduHubDataSetLoadedReader<GLFPREV>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class GLFPREVDataReader : EduHubDataSetDataReader<GLFPREV> { public GLFPREVDataReader(IEduHubDataSetReader<GLFPREV> Reader) : base (Reader) { } public override int FieldCount { get { return 60; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // TRBATCH return Current.TRBATCH; case 3: // TRPERD return Current.TRPERD; case 4: // TRTYPE return Current.TRTYPE; case 5: // TRQTY return Current.TRQTY; case 6: // TRDATE return Current.TRDATE; case 7: // TRREF return Current.TRREF; case 8: // TRAMT return Current.TRAMT; case 9: // TRDET return Current.TRDET; case 10: // TRXLEDGER return Current.TRXLEDGER; case 11: // TRXCODE return Current.TRXCODE; case 12: // TRXTRTYPE return Current.TRXTRTYPE; case 13: // TRSHORT return Current.TRSHORT; case 14: // TRBANK return Current.TRBANK; case 15: // RECONCILE return Current.RECONCILE; case 16: // RECONCILE_FLAGGED return Current.RECONCILE_FLAGGED; case 17: // RECONCILE_DATE return Current.RECONCILE_DATE; case 18: // RECONCILE_USER return Current.RECONCILE_USER; case 19: // RECONCILE_STATEMENT return Current.RECONCILE_STATEMENT; case 20: // PRINT_CHEQUE return Current.PRINT_CHEQUE; case 21: // CHEQUE_NO return Current.CHEQUE_NO; case 22: // PAYEE return Current.PAYEE; case 23: // ADDRESS01 return Current.ADDRESS01; case 24: // ADDRESS02 return Current.ADDRESS02; case 25: // CHQ_TID return Current.CHQ_TID; case 26: // GST_BOX return Current.GST_BOX; case 27: // GST_PERD return Current.GST_PERD; case 28: // GST_AMOUNT return Current.GST_AMOUNT; case 29: // TRNETT return Current.TRNETT; case 30: // TRGROSS return Current.TRGROSS; case 31: // GST_RATE return Current.GST_RATE; case 32: // GST_TYPE return Current.GST_TYPE; case 33: // GST_RECLAIM return Current.GST_RECLAIM; case 34: // GST_SALE_PURCH return Current.GST_SALE_PURCH; case 35: // SOURCE_TID return Current.SOURCE_TID; case 36: // WITHHOLD_AMOUNT return Current.WITHHOLD_AMOUNT; case 37: // WITHHOLD_TYPE return Current.WITHHOLD_TYPE; case 38: // WITHHOLD_RATE return Current.WITHHOLD_RATE; case 39: // EOY_KEPT return Current.EOY_KEPT; case 40: // DRAWER return Current.DRAWER; case 41: // BSB return Current.BSB; case 42: // BANK return Current.BANK; case 43: // BRANCH return Current.BRANCH; case 44: // ACCOUNT_NUMBER return Current.ACCOUNT_NUMBER; case 45: // RTYPE return Current.RTYPE; case 46: // LINE_NO return Current.LINE_NO; case 47: // FLAG return Current.FLAG; case 48: // DEBIT_TOTAL return Current.DEBIT_TOTAL; case 49: // CREDIT_TOTAL return Current.CREDIT_TOTAL; case 50: // SUBPROGRAM return Current.SUBPROGRAM; case 51: // GLPROGRAM return Current.GLPROGRAM; case 52: // INITIATIVE return Current.INITIATIVE; case 53: // DEBIT return Current.DEBIT; case 54: // CREDIT return Current.CREDIT; case 55: // CANCELLED return Current.CANCELLED; case 56: // FEE_CODE return Current.FEE_CODE; case 57: // LW_DATE return Current.LW_DATE; case 58: // LW_TIME return Current.LW_TIME; case 59: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // TRBATCH return Current.TRBATCH == null; case 3: // TRPERD return Current.TRPERD == null; case 4: // TRTYPE return Current.TRTYPE == null; case 5: // TRQTY return Current.TRQTY == null; case 6: // TRDATE return Current.TRDATE == null; case 7: // TRREF return Current.TRREF == null; case 8: // TRAMT return Current.TRAMT == null; case 9: // TRDET return Current.TRDET == null; case 10: // TRXLEDGER return Current.TRXLEDGER == null; case 11: // TRXCODE return Current.TRXCODE == null; case 12: // TRXTRTYPE return Current.TRXTRTYPE == null; case 13: // TRSHORT return Current.TRSHORT == null; case 14: // TRBANK return Current.TRBANK == null; case 15: // RECONCILE return Current.RECONCILE == null; case 16: // RECONCILE_FLAGGED return Current.RECONCILE_FLAGGED == null; case 17: // RECONCILE_DATE return Current.RECONCILE_DATE == null; case 18: // RECONCILE_USER return Current.RECONCILE_USER == null; case 19: // RECONCILE_STATEMENT return Current.RECONCILE_STATEMENT == null; case 20: // PRINT_CHEQUE return Current.PRINT_CHEQUE == null; case 21: // CHEQUE_NO return Current.CHEQUE_NO == null; case 22: // PAYEE return Current.PAYEE == null; case 23: // ADDRESS01 return Current.ADDRESS01 == null; case 24: // ADDRESS02 return Current.ADDRESS02 == null; case 25: // CHQ_TID return Current.CHQ_TID == null; case 26: // GST_BOX return Current.GST_BOX == null; case 27: // GST_PERD return Current.GST_PERD == null; case 28: // GST_AMOUNT return Current.GST_AMOUNT == null; case 29: // TRNETT return Current.TRNETT == null; case 30: // TRGROSS return Current.TRGROSS == null; case 31: // GST_RATE return Current.GST_RATE == null; case 32: // GST_TYPE return Current.GST_TYPE == null; case 33: // GST_RECLAIM return Current.GST_RECLAIM == null; case 34: // GST_SALE_PURCH return Current.GST_SALE_PURCH == null; case 35: // SOURCE_TID return Current.SOURCE_TID == null; case 36: // WITHHOLD_AMOUNT return Current.WITHHOLD_AMOUNT == null; case 37: // WITHHOLD_TYPE return Current.WITHHOLD_TYPE == null; case 38: // WITHHOLD_RATE return Current.WITHHOLD_RATE == null; case 39: // EOY_KEPT return Current.EOY_KEPT == null; case 40: // DRAWER return Current.DRAWER == null; case 41: // BSB return Current.BSB == null; case 42: // BANK return Current.BANK == null; case 43: // BRANCH return Current.BRANCH == null; case 44: // ACCOUNT_NUMBER return Current.ACCOUNT_NUMBER == null; case 45: // RTYPE return Current.RTYPE == null; case 46: // LINE_NO return Current.LINE_NO == null; case 47: // FLAG return Current.FLAG == null; case 48: // DEBIT_TOTAL return Current.DEBIT_TOTAL == null; case 49: // CREDIT_TOTAL return Current.CREDIT_TOTAL == null; case 50: // SUBPROGRAM return Current.SUBPROGRAM == null; case 51: // GLPROGRAM return Current.GLPROGRAM == null; case 52: // INITIATIVE return Current.INITIATIVE == null; case 53: // DEBIT return Current.DEBIT == null; case 54: // CREDIT return Current.CREDIT == null; case 55: // CANCELLED return Current.CANCELLED == null; case 56: // FEE_CODE return Current.FEE_CODE == null; case 57: // LW_DATE return Current.LW_DATE == null; case 58: // LW_TIME return Current.LW_TIME == null; case 59: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // TRBATCH return "TRBATCH"; case 3: // TRPERD return "TRPERD"; case 4: // TRTYPE return "TRTYPE"; case 5: // TRQTY return "TRQTY"; case 6: // TRDATE return "TRDATE"; case 7: // TRREF return "TRREF"; case 8: // TRAMT return "TRAMT"; case 9: // TRDET return "TRDET"; case 10: // TRXLEDGER return "TRXLEDGER"; case 11: // TRXCODE return "TRXCODE"; case 12: // TRXTRTYPE return "TRXTRTYPE"; case 13: // TRSHORT return "TRSHORT"; case 14: // TRBANK return "TRBANK"; case 15: // RECONCILE return "RECONCILE"; case 16: // RECONCILE_FLAGGED return "RECONCILE_FLAGGED"; case 17: // RECONCILE_DATE return "RECONCILE_DATE"; case 18: // RECONCILE_USER return "RECONCILE_USER"; case 19: // RECONCILE_STATEMENT return "RECONCILE_STATEMENT"; case 20: // PRINT_CHEQUE return "PRINT_CHEQUE"; case 21: // CHEQUE_NO return "CHEQUE_NO"; case 22: // PAYEE return "PAYEE"; case 23: // ADDRESS01 return "ADDRESS01"; case 24: // ADDRESS02 return "ADDRESS02"; case 25: // CHQ_TID return "CHQ_TID"; case 26: // GST_BOX return "GST_BOX"; case 27: // GST_PERD return "GST_PERD"; case 28: // GST_AMOUNT return "GST_AMOUNT"; case 29: // TRNETT return "TRNETT"; case 30: // TRGROSS return "TRGROSS"; case 31: // GST_RATE return "GST_RATE"; case 32: // GST_TYPE return "GST_TYPE"; case 33: // GST_RECLAIM return "GST_RECLAIM"; case 34: // GST_SALE_PURCH return "GST_SALE_PURCH"; case 35: // SOURCE_TID return "SOURCE_TID"; case 36: // WITHHOLD_AMOUNT return "WITHHOLD_AMOUNT"; case 37: // WITHHOLD_TYPE return "WITHHOLD_TYPE"; case 38: // WITHHOLD_RATE return "WITHHOLD_RATE"; case 39: // EOY_KEPT return "EOY_KEPT"; case 40: // DRAWER return "DRAWER"; case 41: // BSB return "BSB"; case 42: // BANK return "BANK"; case 43: // BRANCH return "BRANCH"; case 44: // ACCOUNT_NUMBER return "ACCOUNT_NUMBER"; case 45: // RTYPE return "RTYPE"; case 46: // LINE_NO return "LINE_NO"; case 47: // FLAG return "FLAG"; case 48: // DEBIT_TOTAL return "DEBIT_TOTAL"; case 49: // CREDIT_TOTAL return "CREDIT_TOTAL"; case 50: // SUBPROGRAM return "SUBPROGRAM"; case 51: // GLPROGRAM return "GLPROGRAM"; case 52: // INITIATIVE return "INITIATIVE"; case 53: // DEBIT return "DEBIT"; case 54: // CREDIT return "CREDIT"; case 55: // CANCELLED return "CANCELLED"; case 56: // FEE_CODE return "FEE_CODE"; case 57: // LW_DATE return "LW_DATE"; case 58: // LW_TIME return "LW_TIME"; case 59: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "TRBATCH": return 2; case "TRPERD": return 3; case "TRTYPE": return 4; case "TRQTY": return 5; case "TRDATE": return 6; case "TRREF": return 7; case "TRAMT": return 8; case "TRDET": return 9; case "TRXLEDGER": return 10; case "TRXCODE": return 11; case "TRXTRTYPE": return 12; case "TRSHORT": return 13; case "TRBANK": return 14; case "RECONCILE": return 15; case "RECONCILE_FLAGGED": return 16; case "RECONCILE_DATE": return 17; case "RECONCILE_USER": return 18; case "RECONCILE_STATEMENT": return 19; case "PRINT_CHEQUE": return 20; case "CHEQUE_NO": return 21; case "PAYEE": return 22; case "ADDRESS01": return 23; case "ADDRESS02": return 24; case "CHQ_TID": return 25; case "GST_BOX": return 26; case "GST_PERD": return 27; case "GST_AMOUNT": return 28; case "TRNETT": return 29; case "TRGROSS": return 30; case "GST_RATE": return 31; case "GST_TYPE": return 32; case "GST_RECLAIM": return 33; case "GST_SALE_PURCH": return 34; case "SOURCE_TID": return 35; case "WITHHOLD_AMOUNT": return 36; case "WITHHOLD_TYPE": return 37; case "WITHHOLD_RATE": return 38; case "EOY_KEPT": return 39; case "DRAWER": return 40; case "BSB": return 41; case "BANK": return 42; case "BRANCH": return 43; case "ACCOUNT_NUMBER": return 44; case "RTYPE": return 45; case "LINE_NO": return 46; case "FLAG": return 47; case "DEBIT_TOTAL": return 48; case "CREDIT_TOTAL": return 49; case "SUBPROGRAM": return 50; case "GLPROGRAM": return 51; case "INITIATIVE": return 52; case "DEBIT": return 53; case "CREDIT": return 54; case "CANCELLED": return 55; case "FEE_CODE": return 56; case "LW_DATE": return 57; case "LW_TIME": return 58; case "LW_USER": return 59; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
//css_dbg /t:winexe; //css_ref FileDialogs.dll; //css_reference csscriptlibrary.dll; using System; using System.Collections; using System.ComponentModel; using System.Data; using System.IO; using System.Xml; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using Microsoft.Win32; using System.Text; using System.Reflection; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using csscript; namespace CSSScript { public class SearchDirs : Form { private System.ComponentModel.IContainer components = null; private ListBox listBox1; private Button ok; private Button apply; private Button cancel; private Panel panel1; private LinkLabel edit; private LinkLabel remove; private LinkLabel add; private Button downBtn; private Button upBtn; private bool modified = false; public SearchDirs() { InitializeComponent(); upBtn.Text = downBtn.Text = ""; upBtn.Image = imgUp; downBtn.Image = imgDown; } protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.listBox1 = new System.Windows.Forms.ListBox(); this.ok = new System.Windows.Forms.Button(); this.apply = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.downBtn = new System.Windows.Forms.Button(); this.upBtn = new System.Windows.Forms.Button(); this.edit = new System.Windows.Forms.LinkLabel(); this.remove = new System.Windows.Forms.LinkLabel(); this.add = new System.Windows.Forms.LinkLabel(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // listBox1 // this.listBox1.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.listBox1.Location = new System.Drawing.Point(2, 0); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(607, 225); this.listBox1.TabIndex = 0; this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged); // // ok // this.ok.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.ok.DialogResult = System.Windows.Forms.DialogResult.OK; this.ok.Enabled = false; this.ok.Location = new System.Drawing.Point(190, 281); this.ok.Name = "ok"; this.ok.Size = new System.Drawing.Size(75, 23); this.ok.TabIndex = 1; this.ok.Text = "Ok"; this.ok.Click += new System.EventHandler(this.ok_Click); // // apply // this.apply.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.apply.Enabled = false; this.apply.Location = new System.Drawing.Point(271, 281); this.apply.Name = "apply"; this.apply.Size = new System.Drawing.Size(75, 23); this.apply.TabIndex = 1; this.apply.Text = "Apply"; this.apply.Click += new System.EventHandler(this.apply_Click); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancel.Location = new System.Drawing.Point(352, 281); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size(75, 23); this.cancel.TabIndex = 1; this.cancel.Text = "Cancel"; this.cancel.Click += new System.EventHandler(this.cancel_Click); // // panel1 // this.panel1.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.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.downBtn); this.panel1.Controls.Add(this.upBtn); this.panel1.Controls.Add(this.edit); this.panel1.Controls.Add(this.remove); this.panel1.Controls.Add(this.add); this.panel1.Controls.Add(this.listBox1); this.panel1.Location = new System.Drawing.Point(2, 1); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(613, 260); this.panel1.TabIndex = 2; // // downBtn // this.downBtn.Location = new System.Drawing.Point(167, 230); this.downBtn.Name = "downBtn"; this.downBtn.Size = new System.Drawing.Size(28, 25); this.downBtn.TabIndex = 3; this.downBtn.Text = "Down"; this.downBtn.Click += new System.EventHandler(this.downBtn_Click); // // upBtn // this.upBtn.Location = new System.Drawing.Point(136, 230); this.upBtn.Name = "upBtn"; this.upBtn.Size = new System.Drawing.Size(28, 25); this.upBtn.TabIndex = 3; this.upBtn.Text = "Up"; this.upBtn.Click += new System.EventHandler(this.upBtn_Click); // // edit // this.edit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.edit.Enabled = false; this.edit.Location = new System.Drawing.Point(39, 232); this.edit.Name = "edit"; this.edit.Size = new System.Drawing.Size(25, 13); this.edit.TabIndex = 2; this.edit.TabStop = true; this.edit.Text = "Edit"; this.edit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.edit_LinkClicked); // // remove // this.remove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.remove.Enabled = false; this.remove.Location = new System.Drawing.Point(70, 232); this.remove.Name = "remove"; this.remove.Size = new System.Drawing.Size(47, 13); this.remove.TabIndex = 2; this.remove.TabStop = true; this.remove.Text = "Remove"; this.remove.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.remove_LinkClicked); // // add // this.add.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.add.Location = new System.Drawing.Point(9, 232); this.add.Name = "add"; this.add.Size = new System.Drawing.Size(26, 13); this.add.TabIndex = 2; this.add.TabStop = true; this.add.Text = "Add"; this.add.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.add_LinkClicked); // // SearchDirs // this.AcceptButton = this.ok; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.cancel; this.ClientSize = new System.Drawing.Size(616, 316); this.Controls.Add(this.panel1); this.Controls.Add(this.cancel); this.Controls.Add(this.apply); this.Controls.Add(this.ok); this.MaximizeBox = false; this.Name = "SearchDirs"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CS-Script SearchDirs"; this.Load += new System.EventHandler(this.SearchDirs_Load); this.Closing += new System.ComponentModel.CancelEventHandler(this.ConfigForm_Closing); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } static public string ConfigFile { get { if (Environment.GetEnvironmentVariable("CSSCRIPT_DIR") == null) throw new ApplicationException("CS-Script is not installed"); return Environment.ExpandEnvironmentVariables("%CSSCRIPT_DIR%\\css_config.xml"); } } [STAThread] static public void Main(string[] args) { if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")) Console.WriteLine( "Usage: cscscript SearchDirs [/add path]\n" + "This script displays list of the CS-Script search directories for script file and assembly probing.\n\n" + "</add> - command switch to add new search directory\n" + "<path> - search directory\n" + " Example: cscscript SearchDirs /add c:\\Temp\n"); else try { if (args.Length > 1 && args[0] == "/add") { Settings settings = Settings.Load(ConfigFile); if (!settings.SearchDirs.Trim().EndsWith(";")) settings.SearchDirs += ";" + args[1] + ";"; else settings.SearchDirs += args[1] + ";"; settings.Save(ConfigFile); } else Application.Run(new SearchDirs()); } catch (Exception ex) { MessageBox.Show(ex.Message, "CS-Script"); } } private void ConfigForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (modified) { DialogResult response = MessageBox.Show("The SearchDirs have been modified.\n Do you want to save them?", "CS-Script", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (response == DialogResult.Yes) apply_Click(sender, e); else if (response == DialogResult.Cancel) e.Cancel = true; } } static Image DullImage(Image img) { Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(newBitmap)) { //g.DrawImage(image, 0.0f, 0.0f); //draw original image ImageAttributes imageAttributes = new ImageAttributes(); int width = img.Width; int height = img.Height; float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // red scaling factor of 1 new float[] {0, 1, 0, 0, 0}, // green scaling factor of 1 new float[] {0, 0, 1, 0, 0}, // blue scaling factor of 1 new float[] {0, 0, 0, 1, 0}, // alpha scaling factor of 1 new float[] {.05f, .05f, .05f, 0, 1}}; // three translations of 0.2 ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage( img, new Rectangle(0, 0, width, height), // destination rectangle 0, 0, // upper-left corner of source rectangle width, // width of source rectangle height, // height of source rectangle GraphicsUnit.Pixel, imageAttributes); } return newBitmap; } static Image CreateUpImage() { Image img = new Bitmap(25, 25); using (Graphics g = Graphics.FromImage(img)) { LinearGradientBrush lgb = new LinearGradientBrush( new Point(0, 0), new Point(25, 0), Color.YellowGreen, Color.DarkGreen); int xOffset = -3; int yOffset = -1; g.FillPolygon(lgb, new Point[] { new Point(15+xOffset,5+yOffset), new Point(25+xOffset,15+yOffset), new Point(18+xOffset,15+yOffset), new Point(18+xOffset,20+yOffset), new Point(12+xOffset,20+yOffset), new Point(12+xOffset,15+yOffset), new Point(5+xOffset,15+yOffset) }); } return img; } static Image CreateDownImage() { Image img = new Bitmap(CreateUpImage()); img.RotateFlip(RotateFlipType.Rotate180FlipX); return img; } Image imgUp = CreateUpImage(); Image imgDown = CreateDownImage(); Image imgUpDisabled = DullImage(CreateUpImage()); Image imgDownDisabled = DullImage(CreateDownImage()); private void SearchDirs_Load(object sender, EventArgs e) { try { Settings settings = Settings.Load(ConfigFile); foreach (string dir in settings.SearchDirs.Split(';')) if (dir.Trim() != "") listBox1.Items.Add(dir.Trim()); add.Enabled = true; ok.Enabled = apply.Enabled = modified; listBox1_SelectedIndexChanged(null, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { upBtn.Enabled = downBtn.Enabled = edit.Enabled = remove.Enabled = (listBox1.SelectedIndex != -1); upBtn.Image = upBtn.Enabled ? imgUp : imgUpDisabled; downBtn.Image = downBtn.Enabled ? imgDown : imgDownDisabled; } private void edit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { using (EditDirForm dlg = new EditDirForm(listBox1.SelectedItem.ToString())) { if (dlg.ShowDialog() == DialogResult.OK) { listBox1.Items[listBox1.SelectedIndex] = dlg.Dir; modified = true; ok.Enabled = apply.Enabled = modified; } } } private void add_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { using (EditDirForm dlg = new EditDirForm("")) { if (dlg.ShowDialog() == DialogResult.OK) { listBox1.Items.Add(dlg.Dir); modified = true; ok.Enabled = apply.Enabled = modified; listBox1.SelectedIndex = listBox1.Items.Count - 1; } } } private void remove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { int index = listBox1.SelectedIndex; listBox1.Items.RemoveAt(listBox1.SelectedIndex); modified = true; ok.Enabled = apply.Enabled = modified; if (index < listBox1.Items.Count) listBox1.SelectedIndex = index; else listBox1.SelectedIndex = listBox1.Items.Count - 1; } private void apply_Click(object sender, EventArgs e) { try { Settings settings = Settings.Load(ConfigFile); settings.SearchDirs = ""; foreach (string dir in listBox1.Items) settings.SearchDirs += dir + ";"; settings.Save(ConfigFile); modified = false; apply.Enabled = modified; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ok_Click(object sender, EventArgs e) { apply_Click(sender, e); Close(); } private void cancel_Click(object sender, EventArgs e) { Close(); } private void downBtn_Click(object sender, EventArgs e) { int index = listBox1.SelectedIndex; if (index == listBox1.Items.Count - 1 || listBox1.SelectedItem == null) return; string dir = listBox1.SelectedItem.ToString(); listBox1.Items.RemoveAt(index); listBox1.Items.Insert(index + 1, dir); listBox1.SelectedIndex = index + 1; modified = true; ok.Enabled = apply.Enabled = modified; } private void upBtn_Click(object sender, EventArgs e) { int index = listBox1.SelectedIndex; if (index == 0 || listBox1.SelectedItem == null) return; string dir = listBox1.SelectedItem.ToString(); listBox1.Items.RemoveAt(index); listBox1.Items.Insert(index - 1, dir); listBox1.SelectedIndex = index - 1; modified = true; ok.Enabled = apply.Enabled = modified; } } public class SelectFolderDialog { static public string SelectFolder(string initialDirectory) { using (OpenFileDialog dlg = new OpenFileDialog()) { if (initialDirectory != null && initialDirectory != "") dlg.InitialDirectory = initialDirectory; //else // dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); dlg.Title = "Please choose a folder"; dlg.CheckFileExists = false; dlg.FileName = "[Folder]"; dlg.Filter = "Folders|no.files"; if (dlg.ShowDialog() == DialogResult.OK) return Path.GetDirectoryName(dlg.FileName); else return ""; } } } public class EditDirForm : Form { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ok = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.browse = new System.Windows.Forms.Button(); this.SuspendLayout(); // // ok // this.ok.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.ok.Location = new System.Drawing.Point(178, 40); this.ok.Name = "ok"; this.ok.Size = new System.Drawing.Size(75, 23); this.ok.TabIndex = 0; this.ok.Text = "Ok"; this.ok.Click += new System.EventHandler(this.ok_Click); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancel.Location = new System.Drawing.Point(259, 40); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size(75, 23); this.cancel.TabIndex = 1; this.cancel.Text = "Cancel"; this.cancel.Click += new System.EventHandler(this.ok_Cancel); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(12, 11); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(480, 20); this.textBox1.TabIndex = 0; // // browse // this.browse.Anchor = System.Windows.Forms.AnchorStyles.Right; this.browse.Location = new System.Drawing.Point(495, 9); this.browse.Name = "browse"; this.browse.Size = new System.Drawing.Size(26, 23); this.browse.TabIndex = 0; this.browse.Text = "..."; this.browse.Click += new System.EventHandler(this.browse_Click); // // EditDirForm // this.AcceptButton = this.ok; this.CancelButton = this.cancel; this.ClientSize = new System.Drawing.Size(530, 72); this.Controls.Add(this.textBox1); this.Controls.Add(this.browse); this.Controls.Add(this.cancel); this.Controls.Add(this.ok); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.MaximumSize = new System.Drawing.Size(3710, 106); this.MinimumSize = new System.Drawing.Size(371, 106); this.Name = "EditDirForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Directory"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button ok; private System.Windows.Forms.Button cancel; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button browse; public string Dir { get { return textBox1.Text; } } public EditDirForm(string dir) { InitializeComponent(); textBox1.Text = dir; } static internal bool IsVistaOrHigher() { return Environment.OSVersion.Version.Major >= 6; } private void browse_Click(object sender, EventArgs e) { //FileDialogs do not work well on Vista bool useClassicFolderBrowser = IsVistaOrHigher(); if (useClassicFolderBrowser) { using (FolderBrowserDialog browse = new FolderBrowserDialog()) { browse.Description = "Select CS-Script search directorty to add."; browse.SelectedPath = textBox1.Text; if (browse.ShowDialog() == DialogResult.OK) textBox1.Text = browse.SelectedPath; } } else { using (FileDialogs.SelectFolderDialog dialog = new FileDialogs.SelectFolderDialog()) { if (DialogResult.OK == dialog.ShowDialog()) { if (dialog.SelectedPath != "") textBox1.Text = dialog.SelectedPath; } } } } private void ok_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; Close(); } private void ok_Cancel(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; Close(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; using Xunit; namespace System.Text.Primitives.Tests { public class IntegerTests { const int NumberOfRandomSamples = 1000; static readonly TextEncoder[] Encoders = new TextEncoder[] { TextEncoder.Utf8, TextEncoder.Utf16, }; static readonly TextFormat[] Formats = new TextFormat[] { new TextFormat('N', 0), new TextFormat('N', 1), new TextFormat('N', 10), new TextFormat('N', 30), new TextFormat('N', 255), new TextFormat('D', 0), new TextFormat('D', 1), new TextFormat('D', 10), new TextFormat('D', 30), new TextFormat('D', 255), new TextFormat('x', 0), new TextFormat('x', 1), new TextFormat('x', 10), new TextFormat('x', 30), new TextFormat('x', 255), new TextFormat('X', 0), new TextFormat('X', 1), new TextFormat('X', 10), new TextFormat('X', 30), new TextFormat('X', 255), }; [Fact] public void SpecificIntegerTests() { foreach (var encoder in Encoders) { foreach (var format in Formats) { Validate<ulong>(0, format, encoder); Validate<ulong>(1, format, encoder); Validate<ulong>(999999999999, format, encoder); Validate<ulong>(1000000000000, format, encoder); Validate<ulong>(ulong.MaxValue, format, encoder); Validate<uint>(0, format, encoder); Validate<uint>(1, format, encoder); Validate<uint>(999999999, format, encoder); Validate<uint>(1000000000, format, encoder); Validate<uint>(uint.MaxValue, format, encoder); Validate<ushort>(0, format, encoder); Validate<ushort>(1, format, encoder); Validate<ushort>(9999, format, encoder); Validate<ushort>(10000, format, encoder); Validate<ushort>(ushort.MaxValue, format, encoder); Validate<byte>(0, format, encoder); Validate<byte>(1, format, encoder); Validate<byte>(99, format, encoder); Validate<byte>(100, format, encoder); Validate<byte>(byte.MaxValue, format, encoder); Validate<long>(long.MinValue, format, encoder); Validate<long>(-1000000000000, format, encoder); Validate<long>(-999999999999, format, encoder); Validate<long>(-1, format, encoder); Validate<long>(0, format, encoder); Validate<long>(1, format, encoder); Validate<long>(999999999999, format, encoder); Validate<long>(1000000000000, format, encoder); Validate<long>(long.MaxValue, format, encoder); Validate<int>(int.MinValue, format, encoder); Validate<int>(-1000000000, format, encoder); Validate<int>(-999999999, format, encoder); Validate<int>(-1, format, encoder); Validate<int>(0, format, encoder); Validate<int>(1, format, encoder); Validate<int>(999999999, format, encoder); Validate<int>(1000000000, format, encoder); Validate<int>(int.MaxValue, format, encoder); Validate<short>(short.MinValue, format, encoder); Validate<short>(-10000, format, encoder); Validate<short>(-9999, format, encoder); Validate<short>(-1, format, encoder); Validate<short>(0, format, encoder); Validate<short>(1, format, encoder); Validate<short>(9999, format, encoder); Validate<short>(10000, format, encoder); Validate<short>(short.MaxValue, format, encoder); Validate<sbyte>(sbyte.MaxValue, format, encoder); Validate<sbyte>(-100, format, encoder); Validate<sbyte>(-99, format, encoder); Validate<sbyte>(-1, format, encoder); Validate<sbyte>(0, format, encoder); Validate<sbyte>(1, format, encoder); Validate<sbyte>(99, format, encoder); Validate<sbyte>(100, format, encoder); Validate<sbyte>(sbyte.MaxValue, format, encoder); } } } [Fact] public void RandomIntegerTests() { for (var i = 0; i < NumberOfRandomSamples; i++) { foreach (var encoder in Encoders) { foreach (var format in Formats) { ValidateRandom<ulong>(format, encoder); ValidateRandom<uint>(format, encoder); ValidateRandom<ushort>(format, encoder); ValidateRandom<byte>(format, encoder); ValidateRandom<long>(format, encoder); ValidateRandom<int>(format, encoder); ValidateRandom<short>(format, encoder); ValidateRandom<sbyte>(format, encoder); } } } } static void ValidateRandom<T>(TextFormat format, TextEncoder encoder) { Validate<T>(GetRandom<T>(), format, encoder); } static void Validate<T>(long value, TextFormat format, TextEncoder encoder) { Validate<T>(unchecked((ulong)value), format, encoder); } static void Validate<T>(ulong value, TextFormat format, TextEncoder encoder) { var formatString = format.Precision == 255 ? $"{format.Symbol}" : $"{format.Symbol}{format.Precision}"; var span = new Span<byte>(new byte[128]); string expected; int written; if (typeof(T) == typeof(ulong)) { expected = value.ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat(value, span, out written, format, encoder)); } else if (typeof(T) == typeof(uint)) { expected = ((uint)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((uint)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(ushort)) { expected = ((ushort)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((ushort)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(byte)) { expected = ((byte)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((byte)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(long)) { expected = ((long)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((long)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(int)) { expected = ((int)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((int)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(short)) { expected = ((short)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((short)value, span, out written, format, encoder)); } else if (typeof(T) == typeof(sbyte)) { expected = ((sbyte)value).ToString(formatString, CultureInfo.InvariantCulture); Assert.True(PrimitiveFormatter.TryFormat((sbyte)value, span, out written, format, encoder)); } else throw new NotSupportedException(); string actual = TestHelper.SpanToString(span.Slice(0, written), encoder); Assert.Equal(expected, actual); } static readonly Random Rnd = new Random(234922); static ulong GetRandom<T>() { int size = Unsafe.SizeOf<T>(); byte[] data = new byte[size]; Rnd.NextBytes(data); if (typeof(T) == typeof(ulong)) return BitConverter.ToUInt64(data, 0); else if (typeof(T) == typeof(uint)) return BitConverter.ToUInt32(data, 0); else if (typeof(T) == typeof(ushort)) return BitConverter.ToUInt16(data, 0); else if (typeof(T) == typeof(long)) return (ulong)BitConverter.ToInt64(data, 0); else if (typeof(T) == typeof(int)) return (ulong)BitConverter.ToInt32(data, 0); else if (typeof(T) == typeof(short)) return (ulong)BitConverter.ToInt16(data, 0); else if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) return data[0]; else throw new NotSupportedException(); } } }
//------------------------------------------------------------------------------ // <copyright file="MSG.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Security; using MS.Internal.WindowsBase; namespace System.Windows.Interop { /// <summary> /// This class is the managed version of the Win32 MSG datatype. /// </summary> /// <remarks> /// For Avalon/[....] interop to work, [....] needs to be able to modify MSG structs as they are /// processed, so they are passed by ref (it's also a perf gain) /// /// - but in the Partial Trust scenario, this would be a security vulnerability; allowing partially trusted code /// to intercept and arbitrarily change MSG contents could potentially create a spoofing opportunity. /// /// - so rather than try to secure all posible current and future extensibility points against untrusted code /// getting write access to a MSG struct during message processing, we decided the simpler, more performant, and /// more secure, both now and going forward, solution was to secure write access to the MSG struct directly /// at the source. /// /// - get access is unrestricted and should in-line nicely for zero perf cost /// /// - set access is restricted via a call to SecurityHelper.DemandUnrestrictedUIPermission, which is optimized /// to a no-op in the Full Trust scenario, and will throw a security exception in the Partial Trust scenario /// /// - NOTE: This breaks Avalon/[....] interop in the Partial Trust scenario, but that's not a supported /// scenario anyway. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased")] [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [StructLayout(LayoutKind.Sequential)] [Serializable] public struct MSG { /// <SecurityNote> /// Critical: Setting critical data /// </SecurityNote> [SecurityCritical] [FriendAccessAllowed] // Built into Base, used by Core or Framework. internal MSG(IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, int time, int pt_x, int pt_y) { _hwnd = hwnd; _message = message; _wParam = wParam; _lParam = lParam; _time = time; _pt_x = pt_x; _pt_y = pt_y; } // // Public Properties: // /// <summary> /// The handle of the window to which the message was sent. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr hwnd { [SecurityCritical] get { return _hwnd; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _hwnd = value; } } /// <summary> /// The Value of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> public int message { [SecurityCritical] get { return _message; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _message = value; } } /// <summary> /// The wParam of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr wParam { [SecurityCritical] get { return _wParam; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _wParam = value; } } /// <summary> /// The lParam of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr lParam { [SecurityCritical] get { return _lParam; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _lParam = value; } } /// <summary> /// The time the window message was sent. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> public int time { [SecurityCritical] get { return _time; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _time = value; } } // In the original Win32, pt was a by-Value POINT structure /// <summary> /// The X coordinate of the message POINT struct. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUpperCased")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] public int pt_x { [SecurityCritical] get { return _pt_x; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _pt_x = value; } } /// <summary> /// The Y coordinate of the message POINT struct. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code as that may be exploited for spoofing purposes /// PublicOK: This data is safe for Partial Trust code to read (getter), There is a demand on the setter to block Partial Trust code /// </SecurityNote> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUpperCased")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")] public int pt_y { [SecurityCritical] get { return _pt_y; } [SecurityCritical] set { SecurityHelper.DemandUnrestrictedUIPermission(); _pt_y = value; } } // // Internal data: // - do not alter the number, order or size of ANY of this members! // - they must agree EXACTLY with the native Win32 MSG structure /// <summary> /// The handle of the window to which the message was sent. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private IntPtr _hwnd; /// <summary> /// The Value of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private int _message; /// <summary> /// The wParam of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private IntPtr _wParam; /// <summary> /// The lParam of the window message. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private IntPtr _lParam; /// <summary> /// The time the window message was sent. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private int _time; /// <summary> /// The X coordinate of the message POINT struct. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private int _pt_x; /// <summary> /// The Y coordinate of the message POINT struct. /// </summary> /// <SecurityNote> /// Critical: This data can not be modified by Partial Trust code for spoofing purposes /// </SecurityNote> [SecurityCritical] private int _pt_y; } }
using System; using System.ComponentModel; using System.Windows.Forms; using Microsoft.Win32; using UltraSFV.Core; namespace UltraSFV { public partial class WorkingDialog : Form { private UltraSFV _parent; private DateTime StartDate; private TimeSpan ts; private string _Status = "working"; #region Constructor public WorkingDialog(UltraSFV parent) { InitializeComponent(); _parent = parent; } #endregion #region Form Events private void WorkingDialog_Load(object sender, EventArgs e) { this.TopMost = Properties.Settings.Default.AlwaysOnTop; StartDate = DateTime.Now; timer1.Start(); backgroundWorker1.RunWorkerAsync(); SetButtonStatus(); UpdateStatsLabels(); } private void WorkingDialog_FormClosing(object sender, FormClosingEventArgs e) { if (_Status == "working") { e.Cancel = true; } } private void WorkingDialog_FormClosed(object sender, FormClosedEventArgs e) { UpdateStatisticsInRegistry(); Properties.Settings.Default.Save(); if (timer1.Enabled) timer1.Stop(); if (timer2.Enabled) timer2.Stop(); if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); } #endregion #region Button Click Events private void buttonPause_Click(object sender, EventArgs e) { if (_Status == "working") { _Status = "paused"; backgroundWorker1.CancelAsync(); this.Text = "UltraSFV - Pausing..."; buttonPause.Enabled = false; buttonStop.Enabled = false; } else if (_Status == "paused") { _Status = "working"; backgroundWorker1.RunWorkerAsync(); this.Text = "UltraSFV - Processing"; buttonPause.Text = "Pause"; buttonStop.Text = "Stop"; StartDate = DateTime.Now.Subtract(ts); timer1.Start(); timer2.Start(); } } private void buttonStop_Click(object sender, EventArgs e) { if (_Status == "working") { _Status = "stopped"; backgroundWorker1.CancelAsync(); this.Text = "UltraSFV - Stopping..."; buttonStop.Enabled = false; buttonPause.Enabled = false; } else if (_Status == "paused") { if (!String.IsNullOrEmpty(Program.CoreWorkQueue.OutputFile)) { MessageBox.Show("The CRC processing has been stopped. No file saved.", "No File Saved", MessageBoxButtons.OK, MessageBoxIcon.Warning); } this.Close(); } } private void buttonClose_Click(object sender, EventArgs e) { this.Close(); } #endregion #region Background Worker private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bw = sender as BackgroundWorker; Program.CoreWorkQueue.Start(bw); if (bw.CancellationPending) { e.Cancel = true; } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { //SetButtonStatus(); labelFileName.Text = Program.CoreWorkQueue.CurrentFileName; progressBar1.Value = Program.CoreWorkQueue.PercentageComplete; labelTotalPercentage.Text = String.Format("{0}%", Program.CoreWorkQueue.PercentageComplete); progressBar2.Value = e.ProgressPercentage; labelFilePercentage.Text = String.Format("{0}%", e.ProgressPercentage); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { timer1_Tick(null, null); timer1.Stop(); timer2_Tick(null, null); timer2.Stop(); labelFileName.Text = Program.CoreWorkQueue.CurrentFileName; progressBar1.Value = Program.CoreWorkQueue.PercentageComplete; labelTotalPercentage.Text = String.Format("{0}%", Program.CoreWorkQueue.PercentageComplete); progressBar2.Value = 100; labelFilePercentage.Text = "100%"; _parent.LoadResults(); if (!String.IsNullOrEmpty(Program.CoreWorkQueue.OutputFile) && e.Cancelled && _Status == "stopped") { MessageBox.Show("The CRC processing has been stopped. No file saved.", "No File Saved", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (!String.IsNullOrEmpty(Program.CoreWorkQueue.OutputFile) && !e.Cancelled) { HashFile file = Program.CoreWorkQueue.SaveResultsToFile(); if (file != null) { _parent.CurrentHashFile = file; if (Properties.Settings.Default.AlertWhenFileCreated) MessageBox.Show("File Created!\n\n" + Program.CoreWorkQueue.OutputFile, "Done", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("There was an error attempting to save the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (_Status == "working") _Status = "finished"; SetButtonStatus(); } #endregion #region Timers private void timer1_Tick(object sender, EventArgs e) { ts = DateTime.Now.Subtract(StartDate); string sTime = ts.Hours.ToString("00") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00"); labelTime.Text = sTime; } private void timer2_Tick(object sender, EventArgs e) { //UpdateStatsLabels(); ts = DateTime.Now.Subtract(StartDate); if (Program.CoreWorkQueue.BytesProcessed > 0) labelPerformance.Text = StringUtilities.GetFileSizeAsString((long)(Program.CoreWorkQueue.BytesProcessed / ts.TotalSeconds)) + "/s"; _parent.LoadResults(); } #endregion #region Helper Methods private void SetButtonStatus() { if (_Status == "working") { if (Program.CoreWorkQueue.RemainingRecords <= 1) { buttonPause.Enabled = false; buttonStop.Enabled = false; } else { buttonPause.Enabled = true; buttonStop.Enabled = true; } } else if (_Status == "paused") { this.Text = "UltraSFV - Paused"; buttonPause.Text = "Resume"; buttonStop.Text = "Cancel"; buttonPause.Enabled = true; buttonStop.Enabled = true; } else if (_Status == "stopped") { this.Text = "UltraSFV - Stopped"; this.Close(); buttonPause.Visible = false; buttonStop.Visible = false; } else if (_Status == "finished") { this.Text = "UltraSFV - Finished"; this.Close(); buttonPause.Visible = false; buttonStop.Visible = false; } } private void UpdateStatsLabels() { labelTotal.Text = Program.CoreWorkQueue.TotalRecords.ToString(); labelChecked.Text = Program.CoreWorkQueue.CompletedRecords.ToString(); labelRemain.Text = Program.CoreWorkQueue.RemainingRecords.ToString(); } private void UpdateStatisticsInRegistry() { RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\UltraSFV\\Statistics", true); key.SetValue("TotalProcessed", ((int)key.GetValue("TotalProcessed", 0) + Program.CoreWorkQueue.CompletedRecords)); key.SetValue("TotalGood", ((int)key.GetValue("TotalGood", 0) + Program.CoreWorkQueue.GoodRecords)); key.SetValue("TotalBad", ((int)key.GetValue("TotalBad", 0) + Program.CoreWorkQueue.BadRecords)); key.SetValue("TotalSkipped", ((int)key.GetValue("TotalSkipped", 0) + Program.CoreWorkQueue.SkippedRecords)); key.SetValue("TotalMissing", ((int)key.GetValue("TotalMissing", 0) + Program.CoreWorkQueue.MissingFiles)); key.SetValue("TotalLocked", ((int)key.GetValue("TotalLocked", 0) + Program.CoreWorkQueue.HashesGenerated)); long val; if (long.TryParse(key.GetValue("TotalBytes", 0).ToString(), out val)) { val = val + Program.CoreWorkQueue.BytesProcessed; } else { val = Program.CoreWorkQueue.BytesProcessed; } key.SetValue("TotalBytes", val); if (long.TryParse(key.GetValue("TotalTime", 0).ToString(), out val)) { val = val + ts.Ticks; } else { val = ts.Ticks; } key.SetValue("TotalTime", val); key.Close(); } #endregion } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- namespace MatterHackers.Agg { public interface IGradient { int calculate(int x, int y, int d); }; public interface IColorFunction { int size(); RGBA_Bytes this[int v] { get; } }; //==========================================================span_gradient public class span_gradient : ISpanGenerator { public const int gradient_subpixel_shift = 4; //-----gradient_subpixel_shift public const int gradient_subpixel_scale = 1 << gradient_subpixel_shift; //-----gradient_subpixel_scale public const int gradient_subpixel_mask = gradient_subpixel_scale - 1; //-----gradient_subpixel_mask public const int subpixelShift = 8; public const int downscale_shift = subpixelShift - gradient_subpixel_shift; private ISpanInterpolator m_interpolator; private IGradient m_gradient_function; private IColorFunction m_color_function; private int m_d1; private int m_d2; //-------------------------------------------------------------------- public span_gradient() { } //-------------------------------------------------------------------- public span_gradient(ISpanInterpolator inter, IGradient gradient_function, IColorFunction color_function, double d1, double d2) { m_interpolator = inter; m_gradient_function = gradient_function; m_color_function = color_function; m_d1 = (agg_basics.iround(d1 * gradient_subpixel_scale)); m_d2 = (agg_basics.iround(d2 * gradient_subpixel_scale)); } //-------------------------------------------------------------------- public ISpanInterpolator interpolator() { return m_interpolator; } public IGradient gradient_function() { return m_gradient_function; } public IColorFunction color_function() { return m_color_function; } public double d1() { return (double)(m_d1) / gradient_subpixel_scale; } public double d2() { return (double)(m_d2) / gradient_subpixel_scale; } //-------------------------------------------------------------------- public void interpolator(ISpanInterpolator i) { m_interpolator = i; } public void gradient_function(IGradient gf) { m_gradient_function = gf; } public void color_function(IColorFunction cf) { m_color_function = cf; } public void d1(double v) { m_d1 = agg_basics.iround(v * gradient_subpixel_scale); } public void d2(double v) { m_d2 = agg_basics.iround(v * gradient_subpixel_scale); } //-------------------------------------------------------------------- public void prepare() { } //-------------------------------------------------------------------- public void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { int dd = m_d2 - m_d1; if (dd < 1) dd = 1; m_interpolator.begin(x + 0.5, y + 0.5, len); do { m_interpolator.coordinates(out x, out y); int d = m_gradient_function.calculate(x >> downscale_shift, y >> downscale_shift, m_d2); d = ((d - m_d1) * (int)m_color_function.size()) / dd; if (d < 0) d = 0; if (d >= (int)m_color_function.size()) { d = m_color_function.size() - 1; } span[spanIndex++] = m_color_function[d]; m_interpolator.Next(); } while (--len != 0); } }; //=====================================================gradient_linear_color public struct gradient_linear_color : IColorFunction { private RGBA_Bytes m_c1; private RGBA_Bytes m_c2; private int m_size; public gradient_linear_color(RGBA_Bytes c1, RGBA_Bytes c2) : this(c1, c2, 256) { } public gradient_linear_color(RGBA_Bytes c1, RGBA_Bytes c2, int size) { m_c1 = c1; m_c2 = c2; m_size = size; } public int size() { return m_size; } public RGBA_Bytes this[int v] { get { return m_c1.gradient(m_c2, (double)(v) / (double)(m_size - 1)); } } public void colors(RGBA_Bytes c1, RGBA_Bytes c2) { colors(c1, c2, 256); } public void colors(RGBA_Bytes c1, RGBA_Bytes c2, int size) { m_c1 = c1; m_c2 = c2; m_size = size; } }; //==========================================================gradient_circle public class gradient_circle : IGradient { // Actually the same as radial. Just for compatibility public int calculate(int x, int y, int d) { return (int)(agg_math.fast_sqrt((int)(x * x + y * y))); } }; //==========================================================gradient_radial public class gradient_radial : IGradient { public int calculate(int x, int y, int d) { return (int)(System.Math.Sqrt(x * x + y * y)); //return (int)(agg_math.fast_sqrt((int)(x * x + y * y))); } } //========================================================gradient_radial_d public class gradient_radial_d : IGradient { public int calculate(int x, int y, int d) { return (int)agg_basics.uround(System.Math.Sqrt((double)(x) * (double)(x) + (double)(y) * (double)(y))); } }; //====================================================gradient_radial_focus public class gradient_radial_focus : IGradient { private int m_r; private int m_fx; private int m_fy; private double m_r2; private double m_fx2; private double m_fy2; private double m_mul; //--------------------------------------------------------------------- public gradient_radial_focus() { m_r = (100 * span_gradient.gradient_subpixel_scale); m_fx = (0); m_fy = (0); update_values(); } //--------------------------------------------------------------------- public gradient_radial_focus(double r, double fx, double fy) { m_r = (agg_basics.iround(r * span_gradient.gradient_subpixel_scale)); m_fx = (agg_basics.iround(fx * span_gradient.gradient_subpixel_scale)); m_fy = (agg_basics.iround(fy * span_gradient.gradient_subpixel_scale)); update_values(); } //--------------------------------------------------------------------- public void init(double r, double fx, double fy) { m_r = agg_basics.iround(r * span_gradient.gradient_subpixel_scale); m_fx = agg_basics.iround(fx * span_gradient.gradient_subpixel_scale); m_fy = agg_basics.iround(fy * span_gradient.gradient_subpixel_scale); update_values(); } //--------------------------------------------------------------------- public double radius() { return (double)(m_r) / span_gradient.gradient_subpixel_scale; } public double focus_x() { return (double)(m_fx) / span_gradient.gradient_subpixel_scale; } public double focus_y() { return (double)(m_fy) / span_gradient.gradient_subpixel_scale; } //--------------------------------------------------------------------- public int calculate(int x, int y, int d) { double dx = x - m_fx; double dy = y - m_fy; double d2 = dx * m_fy - dy * m_fx; double d3 = m_r2 * (dx * dx + dy * dy) - d2 * d2; return agg_basics.iround((dx * m_fx + dy * m_fy + System.Math.Sqrt(System.Math.Abs(d3))) * m_mul); } //--------------------------------------------------------------------- private void update_values() { // Calculate the invariant values. In case the focal center // lies exactly on the gradient circle the divisor degenerates // into zero. In this case we just move the focal center by // one subpixel unit possibly in the direction to the origin (0,0) // and calculate the values again. //------------------------- m_r2 = (double)(m_r) * (double)(m_r); m_fx2 = (double)(m_fx) * (double)(m_fx); m_fy2 = (double)(m_fy) * (double)(m_fy); double d = (m_r2 - (m_fx2 + m_fy2)); if (d == 0) { if (m_fx != 0) { if (m_fx < 0) ++m_fx; else --m_fx; } if (m_fy != 0) { if (m_fy < 0) ++m_fy; else --m_fy; } m_fx2 = (double)(m_fx) * (double)(m_fx); m_fy2 = (double)(m_fy) * (double)(m_fy); d = (m_r2 - (m_fx2 + m_fy2)); } m_mul = m_r / d; } }; //==============================================================gradient_x public class gradient_x : IGradient { public int calculate(int x, int y, int d) { return x; } }; //==============================================================gradient_y public class gradient_y : IGradient { public int calculate(int x, int y, int d) { return y; } }; //========================================================gradient_diamond public class gradient_diamond : IGradient { public int calculate(int x, int y, int d) { int ax = System.Math.Abs(x); int ay = System.Math.Abs(y); return ax > ay ? ax : ay; } }; //=============================================================gradient_xy public class gradient_xy : IGradient { public int calculate(int x, int y, int d) { return System.Math.Abs(x) * System.Math.Abs(y) / d; } }; //========================================================gradient_sqrt_xy public class gradient_sqrt_xy : IGradient { public int calculate(int x, int y, int d) { //return (int)System.Math.Sqrt((int)(System.Math.Abs(x) * System.Math.Abs(y))); return (int)agg_math.fast_sqrt((int)(System.Math.Abs(x) * System.Math.Abs(y))); } }; //==========================================================gradient_conic public class gradient_conic : IGradient { public int calculate(int x, int y, int d) { return (int)agg_basics.uround(System.Math.Abs(System.Math.Atan2((double)(y), (double)(x))) * (double)(d) / System.Math.PI); } }; //=================================================gradient_repeat_adaptor public class gradient_repeat_adaptor : IGradient { private IGradient m_gradient; public gradient_repeat_adaptor(IGradient gradient) { m_gradient = gradient; } public int calculate(int x, int y, int d) { int ret = m_gradient.calculate(x, y, d) % d; if (ret < 0) ret += d; return ret; } }; //================================================gradient_reflect_adaptor public class gradient_reflect_adaptor : IGradient { private IGradient m_gradient; public gradient_reflect_adaptor(IGradient gradient) { m_gradient = gradient; } public int calculate(int x, int y, int d) { int d2 = d << 1; int ret = m_gradient.calculate(x, y, d) % d2; if (ret < 0) ret += d2; if (ret >= d) ret = d2 - ret; return ret; } }; public class gradient_clamp_adaptor : IGradient { private IGradient m_gradient; public gradient_clamp_adaptor(IGradient gradient) { m_gradient = gradient; } public int calculate(int x, int y, int d) { int ret = m_gradient.calculate(x, y, d); if (ret < 0) ret = 0; if (ret > d) ret = d; return ret; } }; }
// 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.Globalization; using System.Reflection; using System.Runtime.InteropServices; namespace System.Security.Cryptography { public class CryptoConfig { private const string AssemblyName_Cng = "System.Security.Cryptography.Cng"; private const string AssemblyName_Csp = "System.Security.Cryptography.Csp"; private const string AssemblyName_Pkcs = "System.Security.Cryptography.Pkcs"; private const string AssemblyName_X509Certificates = "System.Security.Cryptography.X509Certificates"; private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; private const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6"; private const string OID_RSA_MD5 = "1.2.840.113549.2.5"; private const string OID_RSA_RC2CBC = "1.2.840.113549.3.2"; private const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7"; private const string OID_OIWSEC_desCBC = "1.3.14.3.2.7"; private const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26"; private const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1"; private const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2"; private const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3"; private const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1"; private const string ECDsaIdentifier = "ECDsa"; private static volatile Dictionary<string, string> s_defaultOidHT = null; private static volatile Dictionary<string, object> s_defaultNameHT = null; private static volatile Dictionary<string, Type> appNameHT = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); private static volatile Dictionary<string, string> appOidHT = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static readonly char[] SepArray = { '.' }; // valid ASN.1 separators // CoreFx does not support AllowOnlyFipsAlgorithms public static bool AllowOnlyFipsAlgorithms => false; // Private object for locking instead of locking on a public type for SQL reliability work. private static object s_InternalSyncObject = new object(); private static Dictionary<string, string> DefaultOidHT { get { if (s_defaultOidHT != null) { return s_defaultOidHT; } Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); ht.Add("SHA", OID_OIWSEC_SHA1); ht.Add("SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Cng", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Managed", OID_OIWSEC_SHA1); ht.Add("SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Cng", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Managed", OID_OIWSEC_SHA256); ht.Add("SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Cng", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Managed", OID_OIWSEC_SHA384); ht.Add("SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Cng", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Managed", OID_OIWSEC_SHA512); ht.Add("RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160Managed", OID_OIWSEC_RIPEMD160); ht.Add("MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5Managed", OID_RSA_MD5); ht.Add("TripleDESKeyWrap", OID_RSA_SMIMEalgCMS3DESwrap); ht.Add("RC2", OID_RSA_RC2CBC); ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", OID_RSA_RC2CBC); ht.Add("DES", OID_OIWSEC_desCBC); ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", OID_OIWSEC_desCBC); ht.Add("TripleDES", OID_RSA_DES_EDE3_CBC); ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", OID_RSA_DES_EDE3_CBC); s_defaultOidHT = ht; return s_defaultOidHT; } } private static Dictionary<string, object> DefaultNameHT { get { if (s_defaultNameHT != null) { return s_defaultNameHT; } Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5); Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1); Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256); Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384); Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512); Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged); Type AesManagedType = typeof(System.Security.Cryptography.AesManaged); Type SHA256DefaultType = typeof(System.Security.Cryptography.SHA256Managed); Type SHA384DefaultType = typeof(System.Security.Cryptography.SHA384Managed); Type SHA512DefaultType = typeof(System.Security.Cryptography.SHA512Managed); string SHA1CryptoServiceProviderType = "System.Security.Cryptography.SHA1CryptoServiceProvider, " + AssemblyName_Csp; string MD5CryptoServiceProviderType = "System.Security.Cryptography.MD5CryptoServiceProvider," + AssemblyName_Csp; string RSACryptoServiceProviderType = "System.Security.Cryptography.RSACryptoServiceProvider, " + AssemblyName_Csp; string DSACryptoServiceProviderType = "System.Security.Cryptography.DSACryptoServiceProvider, " + AssemblyName_Csp; string DESCryptoServiceProviderType = "System.Security.Cryptography.DESCryptoServiceProvider, " + AssemblyName_Csp; string TripleDESCryptoServiceProviderType = "System.Security.Cryptography.TripleDESCryptoServiceProvider, " + AssemblyName_Csp; string RC2CryptoServiceProviderType = "System.Security.Cryptography.RC2CryptoServiceProvider, " + AssemblyName_Csp; string RNGCryptoServiceProviderType = "System.Security.Cryptography.RNGCryptoServiceProvider, " + AssemblyName_Csp; string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyName_Csp; string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyName_Cng; // Random number generator ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType); ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType); // Hash functions ht.Add("SHA", SHA1CryptoServiceProviderType); ht.Add("SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType); ht.Add("MD5", MD5CryptoServiceProviderType); ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType); ht.Add("SHA256", SHA256DefaultType); ht.Add("SHA-256", SHA256DefaultType); ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType); ht.Add("SHA384", SHA384DefaultType); ht.Add("SHA-384", SHA384DefaultType); ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType); ht.Add("SHA512", SHA512DefaultType); ht.Add("SHA-512", SHA512DefaultType); ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType); // Keyed Hash Algorithms ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type); ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type); ht.Add("HMACMD5", HMACMD5Type); ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type); ht.Add("HMACSHA1", HMACSHA1Type); ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type); ht.Add("HMACSHA256", HMACSHA256Type); ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type); ht.Add("HMACSHA384", HMACSHA384Type); ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type); ht.Add("HMACSHA512", HMACSHA512Type); ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type); // Asymmetric algorithms ht.Add("RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType); ht.Add("DSA", DSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType); // Windows will register the public ECDsaCng type. Non-Windows gets a special handler. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ht.Add(ECDsaIdentifier, ECDsaCngType); } ht.Add("ECDsaCng", ECDsaCngType); ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType); // Symmetric algorithms ht.Add("DES", DESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType); ht.Add("3DES", TripleDESCryptoServiceProviderType); ht.Add("TripleDES", TripleDESCryptoServiceProviderType); ht.Add("Triple DES", TripleDESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType); ht.Add("RC2", RC2CryptoServiceProviderType); ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType); ht.Add("Rijndael", RijndaelManagedType); ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType); // Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType); ht.Add("AES", AesCryptoServiceProviderType); ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("AesManaged", AesManagedType); ht.Add("System.Security.Cryptography.AesManaged", AesManagedType); // Xml Dsig/ Enc Hash algorithms ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType); // Add the other hash algorithms introduced with XML Encryption ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType); ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType); // Xml Encryption symmetric keys ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType); // Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/ ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type); // Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type); // X509 Extensions (custom decoders) // Basic Constraints OID value ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); // Subject Key Identifier OID value ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyName_X509Certificates); // Key Usage OID value ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyName_X509Certificates); // Enhanced Key Usage OID value ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyName_X509Certificates); // X509Chain class can be overridden to use a different chain engine. ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyName_X509Certificates); // PKCS9 attributes ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyName_Pkcs); s_defaultNameHT = ht; return s_defaultNameHT; // Types in Desktop but currently unsupported in CoreFx: // Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160); // Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES); // Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription); // Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription); // Type RSAPKCS1SHA256SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA256SignatureDescription); // Type RSAPKCS1SHA384SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA384SignatureDescription); // Type RSAPKCS1SHA512SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA512SignatureDescription); // string RIPEMD160ManagedType = "System.Security.Cryptography.RIPEMD160Managed" + AssemblyName_Encoding; // string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyName_Cng; // string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyName_Cng; // string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyName_Cng; // string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyName_Cng; // string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyName_Cng; // string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyName_Cng; // string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyName_Csp; // string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyName_Csp; // string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyName_Csp; // string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity; } } public static void AddAlgorithm(Type algorithm, params string[] names) { if (algorithm == null) throw new ArgumentNullException(nameof(algorithm)); if (!algorithm.IsVisible) throw new ArgumentException(SR.Cryptography_AlgorithmTypesMustBeVisible, nameof(algorithm)); if (names == null) throw new ArgumentNullException(nameof(names)); string[] algorithmNames = new string[names.Length]; Array.Copy(names, 0, algorithmNames, 0, algorithmNames.Length); // Pre-check the algorithm names for validity so that we don't add a few of the names and then // throw an exception if we find an invalid name partway through the list. foreach (string name in algorithmNames) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); } } // Everything looks valid, so we're safe to take the table lock and add the name mappings. lock (s_InternalSyncObject) { foreach (string name in algorithmNames) { appNameHT[name] = algorithm; } } } public static object CreateFromName(string name, params object[] args) { if (name == null) throw new ArgumentNullException(nameof(name)); Type retvalType = null; // Check to see if we have an application defined mapping lock (s_InternalSyncObject) { if (!appNameHT.TryGetValue(name, out retvalType)) { retvalType = null; } } // We allow the default table to Types and Strings // Types get used for types in .Algorithms assembly. // strings get used for delay-loaded stuff in other assemblies such as .Csp. object retvalObj; if (retvalType == null && DefaultNameHT.TryGetValue(name, out retvalObj)) { if (retvalObj is Type) { retvalType = (Type)retvalObj; } else if (retvalObj is string) { retvalType = Type.GetType((string)retvalObj, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } else { Debug.Fail("Unsupported Dictionary value:" + retvalObj.ToString()); } } // Special case asking for "ECDsa" since the default map from .NET Framework uses // a Windows-only type. if (retvalType == null && (args == null || args.Length == 1) && name == ECDsaIdentifier) { return ECDsa.Create(); } // Maybe they gave us a classname. if (retvalType == null) { retvalType = Type.GetType(name, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } // Still null? Then we didn't find it. if (retvalType == null) { return null; } // Locate all constructors. MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault); if (cons == null) { return null; } if (args == null) { args = Array.Empty<object>(); } List<MethodBase> candidates = new List<MethodBase>(); for (int i = 0; i < cons.Length; i++) { MethodBase con = cons[i]; if (con.GetParameters().Length == args.Length) { candidates.Add(con); } } if (candidates.Count == 0) { return null; } cons = candidates.ToArray(); // Bind to matching ctor. object state; ConstructorInfo rci = Type.DefaultBinder.BindToMethod( ConstructorDefault, cons, ref args, null, null, null, out state) as ConstructorInfo; // Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand). if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) { return null; } // Ctor invoke and allocation. object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null); // Reset any parameter re-ordering performed by the binder. if (state != null) { Type.DefaultBinder.ReorderArgumentArray(ref args, state); } return retval; } public static object CreateFromName(string name) { return CreateFromName(name, null); } public static void AddOID(string oid, params string[] names) { if (oid == null) throw new ArgumentNullException(nameof(oid)); if (names == null) throw new ArgumentNullException(nameof(names)); string[] oidNames = new string[names.Length]; Array.Copy(names, 0, oidNames, 0, oidNames.Length); // Pre-check the input names for validity, so that we don't add a few of the names and throw an // exception if an invalid name is found further down the array. foreach (string name in oidNames) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); } } // Everything is valid, so we're good to lock the hash table and add the application mappings lock (s_InternalSyncObject) { foreach (string name in oidNames) { appOidHT[name] = oid; } } } public static string MapNameToOID(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); string oidName; // Check to see if we have an application defined mapping lock (s_InternalSyncObject) { if (!appOidHT.TryGetValue(name, out oidName)) { oidName = null; } } if (string.IsNullOrEmpty(oidName) && !DefaultOidHT.TryGetValue(name, out oidName)) { try { Oid oid = Oid.FromFriendlyName(name, OidGroup.All); oidName = oid.Value; } catch (CryptographicException) { } } return oidName; } public static byte[] EncodeOID(string str) { if (str == null) throw new ArgumentNullException(nameof(str)); string[] oidString = str.Split(SepArray); uint[] oidNums = new uint[oidString.Length]; for (int i = 0; i < oidString.Length; i++) { oidNums[i] = unchecked((uint)int.Parse(oidString[i], CultureInfo.InvariantCulture)); } // Handle the first two oidNums special if (oidNums.Length < 2) throw new CryptographicUnexpectedOperationException(SR.Cryptography_InvalidOID); uint firstTwoOidNums = unchecked((oidNums[0] * 40) + oidNums[1]); // Determine length of output array int encodedOidNumsLength = 2; // Reserve first two bytes for later EncodeSingleOidNum(firstTwoOidNums, null, ref encodedOidNumsLength); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], null, ref encodedOidNumsLength); } // Allocate the array to receive encoded oidNums byte[] encodedOidNums = new byte[encodedOidNumsLength]; int encodedOidNumsIndex = 2; // Encode each segment EncodeSingleOidNum(firstTwoOidNums, encodedOidNums, ref encodedOidNumsIndex); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], encodedOidNums, ref encodedOidNumsIndex); } Debug.Assert(encodedOidNumsIndex == encodedOidNumsLength); // Final return value is 06 <length> encodedOidNums[] if (encodedOidNumsIndex - 2 > 0x7f) throw new CryptographicUnexpectedOperationException(SR.Cryptography_Config_EncodedOIDError); encodedOidNums[0] = (byte)0x06; encodedOidNums[1] = (byte)(encodedOidNumsIndex - 2); return encodedOidNums; } private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index) { // Write directly to destination starting at index, and update index based on how many bytes written. // If destination is null, just return updated index. if (unchecked((int)value) < 0x80) { if (destination != null) { destination[index++] = unchecked((byte)value); } else { index += 1; } } else if (value < 0x4000) { if (destination != null) { destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } else { index += 2; } } else if (value < 0x200000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 3; } } else if (value < 0x10000000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 4; } } else { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 28) | 0x80); destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 5; } } } } }
/* * 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; using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Avatar.Friends { /* This module handles adding/removing friends, and the the presence notification process for login/logoff of friends. The presence notification works as follows: - After the user initially connects to a region (so we now have a UDP connection to work with), this module fetches the friends of user (those are cached), their on-/offline status, and info about the region they are in from the MessageServer. - (*) It then informs the user about the on-/offline status of her friends. - It then informs all online friends currently on this region-server about user's new online status (this will save some network traffic, as local messages don't have to be transferred inter-region, and it will be all that has to be done in Standalone Mode). - For the rest of the online friends (those not on this region-server), this module uses the provided region-information to map users to regions, and sends one notification to every region containing the friends to inform on that server. - The region-server will handle that in the following way: - If it finds the friend, it informs her about the user being online. - If it doesn't find the friend (maybe she TPed away in the meantime), it stores that information. - After it processed all friends, it returns the list of friends it couldn't find. - If this list isn't empty, the FriendsModule re-requests information about those online friends that have been missed and starts at (*) again until all friends have been found, or until it tried 3 times (to prevent endless loops due to some uncaught error). NOTE: Online/Offline notifications don't need to be sent on region change. We implement two XMLRpc handlers here, handling all the inter-region things we have to handle: - On-/Offline-Notifications (bulk) - Terminate Friendship messages (single) */ public class FriendsModule : IRegionModule, IFriendsModule { private class Transaction { public UUID agentID; public string agentName; public uint count; public Transaction(UUID agentID, string agentName) { this.agentID = agentID; this.agentName = agentName; this.count = 1; } } private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate); private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>(); private Dictionary<UUID, UUID> m_pendingCallingcardRequests = new Dictionary<UUID,UUID>(); private Scene m_initialScene; // saves a lookup if we don't have a specific scene private Dictionary<ulong, Scene> m_scenes = new Dictionary<ulong,Scene>(); private IMessageTransferModule m_TransferModule = null; private IGridService m_gridServices = null; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { lock (m_scenes) { if (m_scenes.Count == 0) { MainServer.Instance.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk); MainServer.Instance.AddXmlRPCHandler("terminate_friend", processTerminateFriend); m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max m_initialScene = scene; } if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle)) m_scenes[scene.RegionInfo.RegionHandle] = scene; } scene.RegisterModuleInterface<IFriendsModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientClosed; } public void PostInitialise() { if (m_scenes.Count > 0) { m_TransferModule = m_initialScene.RequestModuleInterface<IMessageTransferModule>(); m_gridServices = m_initialScene.GridService; } if (m_TransferModule == null) m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work"); } public void Close() { } public string Name { get { return "FriendsModule"; } } public bool IsSharedModule { get { return true; } } #endregion #region IInterregionFriendsComms public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online) { List<UUID> tpdAway = new List<UUID>(); // destRegionHandle is a region on another server uint x = 0, y = 0; Utils.LongToUInts(destRegionHandle, out x, out y); GridRegion info = m_gridServices.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID, (int)x, (int)y); if (info != null) { string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; Hashtable reqParams = new Hashtable(); reqParams["agentID"] = agentId.ToString(); reqParams["agentOnline"] = online; int count = 0; foreach (UUID uuid in friends) { reqParams["friendID_" + count++] = uuid.ToString(); } reqParams["friendCount"] = count; IList parameters = new ArrayList(); parameters.Add(reqParams); try { XmlRpcRequest request = new XmlRpcRequest("presence_update_bulk", parameters); XmlRpcResponse response = request.Send(httpServer, 5000); Hashtable respData = (Hashtable)response.Value; count = (int)respData["friendCount"]; for (int i = 0; i < count; ++i) { UUID uuid; if (UUID.TryParse((string)respData["friendID_" + i], out uuid)) tpdAway.Add(uuid); } } catch (WebException e) { // Ignore connect failures, simulators come and go // if (!e.Message.Contains("ConnectFailure")) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); } } catch (Exception e) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); } } else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}???", destRegionHandle); return tpdAway; } public bool TriggerTerminateFriend(ulong destRegionHandle, UUID agentID, UUID exFriendID) { // destRegionHandle is a region on another server uint x = 0, y = 0; Utils.LongToUInts(destRegionHandle, out x, out y); GridRegion info = m_gridServices.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID, (int)x, (int)y); if (info == null) { m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}", destRegionHandle); return false; // region not found??? } string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; Hashtable reqParams = new Hashtable(); reqParams["agentID"] = agentID.ToString(); reqParams["friendID"] = exFriendID.ToString(); IList parameters = new ArrayList(); parameters.Add(reqParams); try { XmlRpcRequest request = new XmlRpcRequest("terminate_friend", parameters); XmlRpcResponse response = request.Send(httpServer, 5000); Hashtable respData = (Hashtable)response.Value; return (bool)respData["success"]; } catch (Exception e) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); return false; } } #endregion #region Incoming XMLRPC messages /// <summary> /// Receive presence information changes about clients in other regions. /// </summary> /// <param name="req"></param> /// <returns></returns> public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)req.Params[0]; List<UUID> friendsNotHere = new List<UUID>(); // this is called with the expectation that all the friends in the request are on this region-server. // But as some time passed since we checked (on the other region-server, via the MessagingServer), // some of the friends might have teleported away. // Actually, even now, between this line and the sending below, some people could TP away. So, // we'll have to lock the m_rootAgents list for the duration to prevent/delay that. lock (m_rootAgents) { List<ScenePresence> friendsHere = new List<ScenePresence>(); try { UUID agentID = new UUID((string)requestData["agentID"]); bool agentOnline = (bool)requestData["agentOnline"]; int count = (int)requestData["friendCount"]; for (int i = 0; i < count; ++i) { UUID uuid; if (UUID.TryParse((string)requestData["friendID_" + i], out uuid)) { if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid)); else friendsNotHere.Add(uuid); } } // now send, as long as they are still here... UUID[] agentUUID = new UUID[] { agentID }; if (agentOnline) { foreach (ScenePresence agent in friendsHere) { agent.ControllingClient.SendAgentOnline(agentUUID); } } else { foreach (ScenePresence agent in friendsHere) { agent.ControllingClient.SendAgentOffline(agentUUID); } } } catch(Exception e) { m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e); } } // no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region, // which should be caught on the next iteration... Hashtable result = new Hashtable(); int idx = 0; foreach (UUID uuid in friendsNotHere) { result["friendID_" + idx++] = uuid.ToString(); } result["friendCount"] = idx; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } public XmlRpcResponse processTerminateFriend(XmlRpcRequest req, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)req.Params[0]; bool success = false; UUID agentID; UUID friendID; if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) && requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID)) { // try to find it and if it is there, prevent it to vanish before we sent the message lock (m_rootAgents) { if (m_rootAgents.ContainsKey(agentID)) { m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID); GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID); success = true; } } } // return whether we were successful Hashtable result = new Hashtable(); result["success"] = success; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } #endregion #region Scene events private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message // There's no way to send a message from the sim // to a user to 'add a friend' without causing dialog box spam // Subscribe to instant messages client.OnInstantMessage += OnInstantMessage; // Friend list management client.OnApproveFriendRequest += OnApproveFriendRequest; client.OnDenyFriendRequest += OnDenyFriendRequest; client.OnTerminateFriendship += OnTerminateFriendship; // ... calling card handling... client.OnOfferCallingCard += OnOfferCallingCard; client.OnAcceptCallingCard += OnAcceptCallingCard; client.OnDeclineCallingCard += OnDeclineCallingCard; // we need this one exactly once per agent session (see comments in the handler below) client.OnEconomyDataRequest += OnEconomyDataRequest; // if it leaves, we want to know, too client.OnLogout += OnLogout; } private void ClientClosed(UUID AgentId, Scene scene) { // agent's client was closed. As we handle logout in OnLogout, this here has only to handle // TPing away (root agent is closed) or TPing/crossing in a region far enough away (client // agent is closed). // NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around // in one of the regions here anymore. lock (m_rootAgents) { if (m_rootAgents.ContainsKey(AgentId)) { m_rootAgents.Remove(AgentId); } } } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { lock (m_rootAgents) { m_rootAgents[avatar.UUID] = avatar.RegionHandle; // Claim User! my user! Mine mine mine! } } private void MakeChildAgent(ScenePresence avatar) { lock (m_rootAgents) { if (m_rootAgents.ContainsKey(avatar.UUID)) { // only delete if the region matches. As this is a shared module, the avatar could be // root agent in another region on this server. if (m_rootAgents[avatar.UUID] == avatar.RegionHandle) { m_rootAgents.Remove(avatar.UUID); // m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); } } } } #endregion private ScenePresence GetRootPresenceFromAgentID(UUID AgentID) { ScenePresence returnAgent = null; lock (m_scenes) { ScenePresence queryagent = null; foreach (Scene scene in m_scenes.Values) { queryagent = scene.GetScenePresence(AgentID); if (queryagent != null) { if (!queryagent.IsChildAgent) { returnAgent = queryagent; break; } } } } return returnAgent; } private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID) { ScenePresence returnAgent = null; lock (m_scenes) { ScenePresence queryagent = null; foreach (Scene scene in m_scenes.Values) { queryagent = scene.GetScenePresence(AgentID); if (queryagent != null) { returnAgent = queryagent; break; } } } return returnAgent; } public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage) { CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId); if (userInfo != null) { GridInstantMessage msg = new GridInstantMessage( toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId, (byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero); FriendshipOffered(msg); } else { m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId); } } #region FriendRequestHandling private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { // Friend Requests go by Instant Message.. using the dialog param // https://wiki.secondlife.com/wiki/ImprovedInstantMessage if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38 { // fromAgentName is the *destination* name (the friend we offer friendship to) ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID)); im.fromAgentName = initiator != null ? initiator.Name : "(hippo)"; FriendshipOffered(im); } else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39 { FriendshipAccepted(client, im); } else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40 { FriendshipDeclined(client, im); } } /// <summary> /// Invoked when a user offers a friendship. /// </summary> /// /// <param name="im"></param> /// <param name="client"></param> private void FriendshipOffered(GridInstantMessage im) { // this is triggered by the initiating agent: // A local agent offers friendship to some possibly remote friend. // A IM is triggered, processed here and sent to the friend (possibly in a remote region). m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}", im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline); // 1.20 protocol sends an UUID in the message field, instead of the friendship offer text. // For interoperability, we have to clear that if (Util.isUUID(im.message)) im.message = ""; // be sneeky and use the initiator-UUID as transactionID. This means we can be stateless. // we have to look up the agent name on friendship-approval, though. im.imSessionID = im.fromAgentID; if (m_TransferModule != null) { // Send it to whoever is the destination. // If new friend is local, it will send an IM to the viewer. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server m_TransferModule.SendInstantMessage( im, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } /// <summary> /// Invoked when a user accepts a friendship offer. /// </summary> /// <param name="im"></param> /// <param name="client"></param> private void FriendshipAccepted(IClientAPI client, GridInstantMessage im) { m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})", client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); } /// <summary> /// Invoked when a user declines a friendship offer. /// </summary> /// May not currently be used - see OnDenyFriendRequest() instead /// <param name="im"></param> /// <param name="client"></param> private void FriendshipDeclined(IClientAPI client, GridInstantMessage im) { UUID fromAgentID = new UUID(im.fromAgentID); UUID toAgentID = new UUID(im.toAgentID); // declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator // toAgentID is initiator, fromAgentID declined friendship m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})", client != null ? client.AgentId.ToString() : "<null>", fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); // Send the decline to whoever is the destination. GridInstantMessage msg = new GridInstantMessage( client.Scene, fromAgentID, client.Name, toAgentID, im.dialog, im.message, im.offline != 0, im.Position); // If new friend is local, it will send an IM to the viewer. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } private void OnGridInstantMessage(GridInstantMessage msg) { // This event won't be raised unless we have that agent, // so we can depend on the above not trying to send // via grid again //m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}", // msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog); if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered || msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted || msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined) { // this should succeed as we *know* the root agent is here. m_TransferModule.SendInstantMessage(msg, delegate(bool success) { //m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted) { // for accept friendship, we have to do a bit more ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName); } } private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName) { m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}", fromAgentID, fromName, toAgentID); // a new friend was added in the initiator's and friend's data, so the cache entries are wrong now. lock (m_friendLists) { m_friendLists.Invalidate(fromAgentID.ToString()); m_friendLists.Invalidate(toAgentID.ToString()); } // now send presence update and add a calling card for the new friend ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID); if (initiator == null) { // quite wrong. Shouldn't happen. m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID); return; } m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online", initiator.Name, fromName); // tell initiator that friend is online initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID }); // find the folder for the friend... //InventoryFolderImpl folder = // initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard); IInventoryService invService = initiator.Scene.InventoryService; InventoryFolderBase folder = invService.GetFolderForType(toAgentID, AssetType.CallingCard); if (folder != null) { // ... and add the calling card CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName); } } private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}", client.Name, client.AgentId, agentID, friendID); // store the new friend persistently for both avatars m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline); // The cache entries aren't valid anymore either, as we just added a friend to both sides. lock (m_friendLists) { m_friendLists.Invalidate(agentID.ToString()); m_friendLists.Invalidate(friendID.ToString()); } // if it's a local friend, we don't have to do the lookup ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID); if (friendPresence != null) { m_log.Debug("[FRIEND]: Local agent detected."); // create calling card CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name); // local message means OnGridInstantMessage won't be triggered, so do the work here. friendPresence.ControllingClient.SendInstantMessage( new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipAccepted, agentID.ToString(), false, Vector3.Zero)); ApproveFriendship(agentID, friendID, client.Name); } else { m_log.Debug("[FRIEND]: Remote agent detected."); // fetch the friend's name for the calling card. CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID); // create calling card CreateCallingCard(client, friendID, callingCardFolders[0], info.UserProfile.FirstName + " " + info.UserProfile.SurName); // Compose (remote) response to friend. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipAccepted, agentID.ToString(), false, Vector3.Zero); if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } // tell client that new friend is online client.SendAgentOnline(new UUID[] { friendID }); } private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}", client.Name, client.AgentId, agentID, friendID); // Compose response to other agent. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipDeclined, agentID.ToString(), false, Vector3.Zero); // send decline to initiator if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID) { // client.AgentId == agentID! // this removes the friends from the stored friendlists. After the next login, they will be gone... m_initialScene.StoreRemoveFriendship(agentID, exfriendID); // ... now tell the two involved clients that they aren't friends anymore. // I don't know why we have to tell <agent>, as this was caused by her, but that's how it works in SL... client.SendTerminateFriend(exfriendID); // now send the friend, if online ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID); if (presence != null) { m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID); presence.ControllingClient.SendTerminateFriend(agentID); } else { // retry 3 times, in case the agent TPed from the last known region... for (int retry = 0; retry < 3; ++retry) { // wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID); if (null == data) break; if (!data.AgentOnline) { m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID); break; // if ex-friend isn't online, we don't need to send } m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}", agentID, exfriendID, data.Handle); // try to send to foreign region, retry if it fails (friend TPed away, for example) if (TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break; } } // clean up cache: FriendList is wrong now... lock (m_friendLists) { m_friendLists.Invalidate(agentID.ToString()); m_friendLists.Invalidate(exfriendID.ToString()); } } #endregion #region CallingCards private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID) { m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}", client.AgentId, destID, transactionID); // This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent // (or the root instead of the child) ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); if (destAgent == null) { client.SendAlertMessage("The person you have offered a card to can't be found anymore."); return; } lock (m_pendingCallingcardRequests) { m_pendingCallingcardRequests[transactionID] = client.AgentId; } // inform the destination agent about the offer destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID); } private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name) { InventoryItemBase item = new InventoryItemBase(); item.AssetID = UUID.Zero; item.AssetType = (int)AssetType.CallingCard; item.BasePermissions = (uint)PermissionMask.Copy; item.CreationDate = Util.UnixTimeSinceEpoch(); item.CreatorId = creator.ToString(); item.CurrentPermissions = item.BasePermissions; item.Description = ""; item.EveryOnePermissions = (uint)PermissionMask.None; item.Flags = 0; item.Folder = folder; item.GroupID = UUID.Zero; item.GroupOwned = false; item.ID = UUID.Random(); item.InvType = (int)InventoryType.CallingCard; item.Name = name; item.NextPermissions = item.EveryOnePermissions; item.Owner = client.AgentId; item.SalePrice = 10; item.SaleType = (byte)SaleType.Not; ((Scene)client.Scene).AddInventoryItem(client, item); } private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID) { m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}", client.AgentId, client.FirstName, client.LastName, transactionID, folderID); UUID destID; lock (m_pendingCallingcardRequests) { if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) { m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", client.Name); return; } // else found pending calling card request with that transaction. m_pendingCallingcardRequests.Remove(transactionID); } ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); // inform sender of the card that destination declined the offer if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID); // put a calling card into the inventory of receiver CreateCallingCard(client, destID, folderID, destAgent.Name); } private void OnDeclineCallingCard(IClientAPI client, UUID transactionID) { m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}", client.Name, client.AgentId, transactionID); UUID destID; lock (m_pendingCallingcardRequests) { if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) { m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", client.Name); return; } // else found pending calling card request with that transaction. m_pendingCallingcardRequests.Remove(transactionID); } ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); // inform sender of the card that destination declined the offer if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID); } /// <summary> /// Send presence information about a client to other clients in both this region and others. /// </summary> /// <param name="client"></param> /// <param name="friendList"></param> /// <param name="iAmOnline"></param> private void SendPresenceState(IClientAPI client, List<FriendListItem> friendList, bool iAmOnline) { //m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out"); if (friendList == null || friendList.Count == 0) { //m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name); return; // nothing we can do if she doesn't have friends... } // collect sets of friendIDs; to send to (online and offline), and to receive from // TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets. // I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago... List<UUID> friendIDsToSendTo = new List<UUID>(); List<UUID> candidateFriendIDsToReceive = new List<UUID>(); foreach (FriendListItem item in friendList) { if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0) { // friend is allowed to see my presence => add if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0) friendIDsToSendTo.Add(item.Friend); if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) candidateFriendIDsToReceive.Add(item.Friend); } } // we now have a list of "interesting" friends (which we have to find out on-/offline state for), // friends we want to send our online state to (if *they* are online, too), and // friends we want to receive online state for (currently unknown whether online or not) // as this processing might take some time and friends might TP away, we try up to three times to // reach them. Most of the time, we *will* reach them, and this loop won't loop int retry = 0; do { // build a list of friends to look up region-information and on-/offline-state for List<UUID> friendIDsToLookup = new List<UUID>(friendIDsToSendTo); foreach (UUID uuid in candidateFriendIDsToReceive) { if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid); } m_log.DebugFormat( "[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}", friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name); // we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't // necessarily contain the correct online state... Dictionary<UUID, FriendRegionInfo> friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup); m_log.DebugFormat( "[FRIEND]: Found {0} regionInfos for {1} friends of {2}", friendRegions.Count, friendIDsToLookup.Count, client.Name); // argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops. UUID[] agentArr = new UUID[] { client.AgentId }; // first, send to friend presence state to me, if I'm online... if (iAmOnline) { List<UUID> friendIDsToReceive = new List<UUID>(); for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i) { UUID uuid = candidateFriendIDsToReceive[i]; FriendRegionInfo info; if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) { friendIDsToReceive.Add(uuid); } } m_log.DebugFormat( "[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name); if (friendIDsToReceive.Count > 0) client.SendAgentOnline(friendIDsToReceive.ToArray()); // clear them for a possible second iteration; we don't have to repeat this candidateFriendIDsToReceive.Clear(); } // now, send my presence state to my friends for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i) { UUID uuid = friendIDsToSendTo[i]; FriendRegionInfo info; if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) { // any client is good enough, root or child... ScenePresence agent = GetAnyPresenceFromAgentID(uuid); if (agent != null) { //m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name); // friend is online and on this server... if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr); else agent.ControllingClient.SendAgentOffline(agentArr); // done, remove it friendIDsToSendTo.RemoveAt(i); } } else { //m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i); // friend is offline => no need to try sending friendIDsToSendTo.RemoveAt(i); } } m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count); // we now have all the friends left that are online (we think), but not on this region-server if (friendIDsToSendTo.Count > 0) { // sort them into regions Dictionary<ulong, List<UUID>> friendsInRegion = new Dictionary<ulong,List<UUID>>(); foreach (UUID uuid in friendIDsToSendTo) { ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already List<UUID> friends; if (!friendsInRegion.TryGetValue(handle, out friends)) { friends = new List<UUID>(); friendsInRegion[handle] = friends; } friends.Add(uuid); } m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count); // clear uuids list and collect missed friends in it for the next retry friendIDsToSendTo.Clear(); // send bulk updates to the region foreach (KeyValuePair<ulong, List<UUID>> pair in friendsInRegion) { //m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line", // pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off"); friendIDsToSendTo.AddRange(InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline)); } } // now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them. // In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again... } while (++retry < 3 && friendIDsToSendTo.Count > 0); } private void OnEconomyDataRequest(UUID agentID) { // KLUDGE: This is the only way I found to get a message (only) after login was completed and the // client is connected enough to receive UDP packets). // This packet seems to be sent only once, just after connection was established to the first // region after login. // We use it here to trigger a presence update; the old update-on-login was never be heard by // the freshly logged in viewer, as it wasn't connected to the region at that time. // TODO: Feel free to replace this by a better solution if you find one. // get the agent. This should work every time, as we just got a packet from it //ScenePresence agent = GetRootPresenceFromAgentID(agentID); // KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit ScenePresence agent = GetAnyPresenceFromAgentID(agentID); // just to be paranoid... if (agent == null) { m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID); return; } List<FriendListItem> fl; lock (m_friendLists) { fl = (List<FriendListItem>)m_friendLists.Get(agent.ControllingClient.AgentId.ToString(), m_initialScene.GetFriendList); } // tell everyone that we are online SendPresenceState(agent.ControllingClient, fl, true); } private void OnLogout(IClientAPI remoteClient) { List<FriendListItem> fl; lock (m_friendLists) { fl = (List<FriendListItem>)m_friendLists.Get(remoteClient.AgentId.ToString(), m_initialScene.GetFriendList); } // tell everyone that we are offline SendPresenceState(remoteClient, fl, false); } } #endregion }
using System; using numl.Utils; using numl.Model; using System.Linq; using System.Dynamic; using numl.Tests.Data; using Xunit; using System.Collections.Generic; namespace numl.Tests.DataTests { [Trait("Category", "Data")] public class SimpleConversionTests { public static IEnumerable<string> ShortStrings { get { yield return "OnE!"; yield return "TWo2"; yield return "t#hrE^e"; yield return "T%hrE@e"; } } public static IEnumerable<string> WordStrings { get { yield return "TH@e QUi#CK bRow!N fox 12"; yield return "s@upeR B#roWN BEaR"; yield return "1829! UGlY FoX"; yield return "ThE QuICk beAr"; } } [Fact] public void Test_Univariate_Conversions() { // boolean Assert.Equal(1, Ject.Convert(true)); Assert.Equal(-1, Ject.Convert(false)); // numeric types Assert.Equal(1d, Ject.Convert((Byte)1)); // byte Assert.Equal(1d, Ject.Convert((SByte)1)); // sbyte Assert.Equal(0.4d, Ject.Convert((Decimal)0.4m)); // decimal Assert.Equal(0.1d, Ject.Convert((Double)0.1d)); // double Assert.Equal(300d, Ject.Convert((Single)300f)); // single Assert.Equal(1d, Ject.Convert((Int16)1)); // int16 Assert.Equal(2d, Ject.Convert((UInt16)2)); // uint16 Assert.Equal(2323432, Ject.Convert((Int32)2323432)); // int32 Assert.Equal(2323432d, Ject.Convert((UInt32)2323432)); // uint32 Assert.Equal(1232323434345d, Ject.Convert((Int64)1232323434345)); // int64 Assert.Equal(1232323434345d, Ject.Convert((UInt64)1232323434345)); // uint64 Assert.Equal(1232323434345d, Ject.Convert((long)1232323434345)); // long // enum Assert.Equal(0d, Ject.Convert(FakeEnum.Item0)); Assert.Equal(1d, Ject.Convert(FakeEnum.Item1)); Assert.Equal(2d, Ject.Convert(FakeEnum.Item2)); Assert.Equal(3d, Ject.Convert(FakeEnum.Item3)); Assert.Equal(4d, Ject.Convert(FakeEnum.Item4)); Assert.Equal(5d, Ject.Convert(FakeEnum.Item5)); Assert.Equal(6d, Ject.Convert(FakeEnum.Item6)); Assert.Equal(7d, Ject.Convert(FakeEnum.Item7)); Assert.Equal(8d, Ject.Convert(FakeEnum.Item8)); Assert.Equal(9d, Ject.Convert(FakeEnum.Item9)); // char Assert.Equal(65d, Ject.Convert('A')); // timespan Assert.Equal(300d, Ject.Convert(TimeSpan.FromSeconds(300))); } [Fact] public void Test_Univariate_Back_Conversions() { // boolean Assert.Equal(true, Ject.Convert(1, typeof(bool))); Assert.Equal(false, Ject.Convert(0, typeof(bool))); Assert.Equal(false, Ject.Convert(-1, typeof(bool))); // numeric types Assert.Equal((Byte)1, Ject.Convert(1d, typeof(Byte))); // byte Assert.Equal((SByte)1, Ject.Convert(1d, typeof(SByte))); // sbyte Assert.Equal((Decimal)0.4m, Ject.Convert(0.4d, typeof(Decimal))); // decimal Assert.Equal((Double)0.1d, Ject.Convert(0.1d, typeof(Double))); // double Assert.Equal((Single)300f, Ject.Convert(300d, typeof(Single))); // single Assert.Equal((Int16)1, Ject.Convert(1d, typeof(Int16))); // int16 Assert.Equal((UInt16)2, Ject.Convert(2d, typeof(UInt16))); // uint16 Assert.Equal((Int32)2323432, Ject.Convert(2323432, typeof(Int32))); // int32 Assert.Equal((UInt32)2323432, Ject.Convert(2323432d, typeof(UInt32))); // uint32 Assert.Equal((Int64)1232323434345, Ject.Convert(1232323434345d, typeof(Int64))); // int64 Assert.Equal((UInt64)1232323434345, Ject.Convert(1232323434345d, typeof(UInt64))); // uint64 Assert.Equal((long)1232323434345, Ject.Convert(1232323434345d, typeof(long))); // long // enum Assert.Equal(FakeEnum.Item0, Ject.Convert(0d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item1, Ject.Convert(1d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item2, Ject.Convert(2d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item3, Ject.Convert(3d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item4, Ject.Convert(4d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item5, Ject.Convert(5d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item6, Ject.Convert(6d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item7, Ject.Convert(7d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item8, Ject.Convert(8d, typeof(FakeEnum))); Assert.Equal(FakeEnum.Item9, Ject.Convert(9d, typeof(FakeEnum))); // char Assert.Equal('A', Ject.Convert(65d, typeof(char))); // timespan Assert.Equal(TimeSpan.FromSeconds(300), Ject.Convert(300d, typeof(TimeSpan))); } [Fact] public void Test_Char_Dictionary_Gen() { var d = StringHelpers.BuildCharArray(ShortStrings); // should have the following: // O, N, E, #SYM#, T, W, #NUM#, H, R var dict = new string[] { "O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R", }; Assert.Equal(dict, d); } [Fact] public void Test_Enum_Dictionary_Gen() { var d = StringHelpers.BuildEnumArray(ShortStrings); // should have the following: // ONE, TWO2, THREE var dict = new string[] { "ONE", "TWO2", "THREE", }; Assert.Equal(dict, d); } [Fact] public void Test_Word_Dictionary_Gen() { var d = StringHelpers.BuildDistinctWordArray(WordStrings); // should have the following: var dict = new string[] { "THE", "QUICK", "BROWN", "FOX", "#NUM#", "SUPER", "BEAR", "UGLY", }; Assert.Equal(dict, d); } [Fact] public void Test_Fast_Reflection_Get_Standard() { var o = new Student { Age = 23, Friends = 12, GPA = 3.2, Grade = Grade.A, Name = "Jordan Spears", Tall = true, Nice = false }; var age = Ject.Get(o, "Age"); Assert.Equal(23, (int)age); var friends = Ject.Get(o, "Friends"); Assert.Equal(12, (int)friends); var gpa = Ject.Get(o, "GPA"); Assert.Equal(3.2, (double)gpa); var grade = Ject.Get(o, "Grade"); Assert.Equal(Grade.A, (Grade)grade); var name = Ject.Get(o, "Name"); Assert.Equal("Jordan Spears", (string)name); var tall = Ject.Get(o, "Tall"); Assert.Equal(true, (bool)tall); var nice = Ject.Get(o, "Nice"); Assert.Equal(false, (bool)nice); } [Fact] public void Test_Fast_Reflection_Set_Standard() { var o = new Student { Age = 23, Friends = 12, GPA = 3.2, Grade = Grade.A, Name = "Jordan Spears", Tall = true, Nice = false }; Ject.Set(o, "Age", 25); Assert.Equal(25, o.Age); Ject.Set(o, "Friends", 1); Assert.Equal(1, o.Friends); Ject.Set(o, "GPA", 1.2); Assert.Equal(1.2, o.GPA); Ject.Set(o, "Grade", Grade.C); Assert.Equal(Grade.C, o.Grade); Ject.Set(o, "Name", "Seth Juarez"); Assert.Equal("Seth Juarez", o.Name); Ject.Set(o, "Tall", false); Assert.Equal(false, o.Tall); Ject.Set(o, "Nice", true); Assert.Equal(true, o.Nice); } [Fact] public void Test_Fast_Reflection_Get_Dictionary() { var o = new Dictionary<string, object>(); o["Age"] = 23; o["Friends"] = 12; o["GPA"] = 3.2; o["Grade"] = Grade.A; o["Name"] = "Jordan Spears"; o["Tall"] = true; o["Nice"] = false; var age = Ject.Get(o, "Age"); Assert.Equal(23, (int)age); var friends = Ject.Get(o, "Friends"); Assert.Equal(12, (int)friends); var gpa = Ject.Get(o, "GPA"); Assert.Equal(3.2, (double)gpa); var grade = Ject.Get(o, "Grade"); Assert.Equal(Grade.A, (Grade)grade); var name = Ject.Get(o, "Name"); Assert.Equal("Jordan Spears", (string)name); var tall = Ject.Get(o, "Tall"); Assert.Equal(true, (bool)tall); var nice = Ject.Get(o, "Nice"); Assert.Equal(false, (bool)nice); } [Fact] public void Test_Fast_Reflection_Set_Dictionary() { var o = new Dictionary<string, object>(); o["Age"] = 23; o["Friends"] = 12; o["GPA"] = 3.2; o["Grade"] = Grade.A; o["Name"] = "Jordan Spears"; o["Tall"] = true; o["Nice"] = false; Ject.Set(o, "Age", 25); Assert.Equal(25, o["Age"]); Ject.Set(o, "Friends", 1); Assert.Equal(1, o["Friends"]); Ject.Set(o, "GPA", 1.2); Assert.Equal(1.2, o["GPA"]); Ject.Set(o, "Grade", Grade.C); Assert.Equal(Grade.C, o["Grade"]); Ject.Set(o, "Name", "Seth Juarez"); Assert.Equal("Seth Juarez", o["Name"]); Ject.Set(o, "Tall", false); Assert.Equal(false, o["Tall"]); Ject.Set(o, "Nice", true); Assert.Equal(true, o["Nice"]); } [Fact] public void Test_Vector_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", Type = typeof(int) }, new Property { Name = "Height", Type=typeof(double) }, new Property { Name = "Weight", Type = typeof(decimal) }, new Property { Name = "Good", Type=typeof(bool) }, }; var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false }; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(o); Assert.Equal(truths, actual); } //[Fact] //public void Test_Vector_DataRow_Conversion_Simple_Numbers() //{ // Descriptor d = new Descriptor(); // d.Features = new Property[] // { // new Property { Name = "Age", }, // new Property { Name = "Height", }, // new Property { Name = "Weight", }, // new Property { Name = "Good", }, // }; // DataTable table = new DataTable("student"); // var age = table.Columns.Add("Age", typeof(int)); // var height = table.Columns.Add("Height", typeof(double)); // var weight = table.Columns.Add("Weight", typeof(decimal)); // var good = table.Columns.Add("Good", typeof(bool)); // DataRow row = table.NewRow(); // row[age] = 23; // row[height] = 6.21; // row[weight] = 220m; // row[good] = false; // var truths = new double[] { 23, 6.21, 220, -1 }; // var actual = d.Convert(row); // Assert.Equal(truths, actual); //} [Fact] public void Test_Vector_Dictionary_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", }, new Property { Name = "Height", }, new Property { Name = "Weight", }, new Property { Name = "Good", }, }; Dictionary<string, object> item = new Dictionary<string, object>(); item["Age"] = 23; item["Height"] = 6.21; item["Weight"] = 220m; item["Good"] = false; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(item); Assert.Equal(truths, actual); } [Fact] public void Test_Vector_Expando_Conversion_Simple_Numbers() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age", }, new Property { Name = "Height", }, new Property { Name = "Weight", }, new Property { Name = "Good", }, }; dynamic item = new ExpandoObject(); item.Age = 23; item.Height = 6.21; item.Weight = 220m; item.Good = false; var truths = new double[] { 23, 6.21, 220, -1 }; var actual = d.Convert(item); Assert.Equal(truths, actual); } [Fact] public void Test_Vector_Conversion_Simple_Numbers_And_Strings() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildDistinctWordArray(WordStrings); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Words", Dictionary = dictionary }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY] // [ 1, 0, 1, 0, 1, 0, 0, 0] var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "the brown 432" }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 1, 0, 1, 0, 1, 0, 0, 0, /* END TEXT */ 220, -1 }; var actual = d.Convert(o); Assert.Equal(truths, actual); // offset test Assert.Equal(10, d.Features[3].Start); Assert.Equal(11, d.Features[4].Start); } [Fact] public void Test_Vector_Conversion_Simple_Numbers_And_Strings_As_Enum() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildDistinctWordArray(WordStrings); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Words", Dictionary = dictionary, AsEnum = true }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // [THE, QUICK, BROWN, FOX, #NUM#, SUPER, BEAR, UGLY] // [ 0, 1, 2, 3, 4, 5, 6, 7] var o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "QUICK" }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 1, /* END TEXT */ 220, -1 }; var actual = d.Convert(o); Assert.Equal(truths, actual); o = new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Words = "sUpEr" }; // array generated by descriptor ordering truths = new double[] { 23, 6.21, /* BEGIN TEXT */ 5, /* END TEXT */ 220, -1 }; actual = d.Convert(o); Assert.Equal(truths, actual); } [Fact] public void Test_Vector_Conversion_Simple_Numbers_And_Chars() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildCharArray(ShortStrings); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Chars", Dictionary = dictionary, SplitType = StringSplitType.Character }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"] // [ 2, 1, 0, 1, 0, 0, 1, 0, 3] var o = new { Age = 23, Height = 6.21d, Chars = "oon!3RrR", Weight = 220m, Good = false, }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 2, 1, 0, 1, 0, 0, 1, 0, 3, /* END CHARS */ 220, -1 }; var actual = d.Convert(o); Assert.Equal(truths, actual); } [Fact] public void Test_Vector_Conversion_Simple_Numbers_And_Chars_As_Enum() { Descriptor d = new Descriptor(); var dictionary = StringHelpers.BuildCharArray(ShortStrings); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new StringProperty { Name = "Chars", Dictionary = dictionary, SplitType = StringSplitType.Character, AsEnum = true }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; // ["O", "N", "E", "#SYM#", "T", "W", "#NUM#", "H", "R"] // [ 2, 1, 0, 1, 0, 0, 1, 0, 3] var o = new { Age = 23, Height = 6.21d, Chars = "N", Weight = 220m, Good = false, }; // array generated by descriptor ordering var truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 1, /* END CHARS */ 220, -1 }; var actual = d.Convert(o); Assert.Equal(truths, actual); o = new { Age = 23, Height = 6.21d, Chars = "!", Weight = 220m, Good = false, }; // array generated by descriptor ordering truths = new double[] { 23, 6.21, /* BEGIN CHARS */ 3, /* END CHARS */ 220, -1 }; actual = d.Convert(o); Assert.Equal(truths, actual); } [Fact] public void Test_Matrix_Conversion_Simple() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; var o = new[] { new { Age = 23, Height = 6.21d, Weight = 220m, Good = false }, new { Age = 12, Height = 4.2d, Weight = 120m, Good = true }, new { Age = 9, Height = 6.0d, Weight = 340m, Good = true }, new { Age = 87, Height = 3.7d, Weight = 79m, Good = false } }; // array generated by descriptor ordering // (returns IEnumerable, but should pass) var truths = new double[][] { new double[] { 23, 6.21, 220, -1 }, new double[] { 12, 4.2, 120, 1 }, new double[] { 9, 6.0, 340, 1 }, new double[] { 87, 3.7, 79, -1 } }; var actual = d.Convert(o); var array = actual.Select(s => s.ToArray()).ToArray(); Assert.Equal(truths, array); } [Fact] public void Test_Matrix_Conversion_With_Label() { Descriptor d = new Descriptor(); d.Features = new Property[] { new Property { Name = "Age" }, new Property { Name = "Height" }, new Property { Name = "Weight" }, new Property { Name = "Good" }, }; d.Label = new Property { Name = "Nice" }; var o = new[] { new { Age = 23, Height = 6.21d, Weight = 220m, Good = false, Nice = true }, new { Age = 12, Height = 4.2d, Weight = 120m, Good = true, Nice = false }, new { Age = 9, Height = 6.0d, Weight = 340m, Good = true, Nice = true }, new { Age = 87, Height = 3.7d, Weight = 79m, Good = false, Nice = false } }; // array generated by descriptor ordering // (returns IEnumerable, but should pass) var truths = new double[][] { new double[] { 23, 6.21, 220, -1, 1 }, new double[] { 12, 4.2, 120, 1, -1 }, new double[] { 9, 6.0, 340, 1, 1 }, new double[] { 87, 3.7, 79, -1, -1 } }; var actual = d.Convert(o); var array = actual.Select(s => s.ToArray()).ToArray(); Assert.Equal(truths, array); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Models; using umbraco.BasePages; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.interfaces; using umbraco.uicontrols; using Content = umbraco.cms.businesslogic.Content; using ContentType = umbraco.cms.businesslogic.ContentType; using Media = umbraco.cms.businesslogic.media.Media; using Property = umbraco.cms.businesslogic.property.Property; using StylesheetProperty = umbraco.cms.businesslogic.web.StylesheetProperty; namespace umbraco.controls { public class ContentControlLoadEventArgs : CancelEventArgs { } /// <summary> /// Summary description for ContentControl. /// </summary> public class ContentControl : TabView { internal Dictionary<string, IDataType> DataTypes = new Dictionary<string, IDataType>(); private readonly Content _content; private UmbracoEnsuredPage _prntpage; public event EventHandler SaveAndPublish; public event EventHandler SaveToPublish; public event EventHandler Save; private readonly publishModes _canPublish = publishModes.NoPublish; public TabPage tpProp; public bool DoesPublish = false; public TextBox NameTxt = new TextBox(); public PlaceHolder NameTxtHolder = new PlaceHolder(); public RequiredFieldValidator NameTxtValidator = new RequiredFieldValidator(); private readonly CustomValidator _nameTxtCustomValidator = new CustomValidator(); private static readonly string UmbracoPath = SystemDirectories.Umbraco; public Pane PropertiesPane = new Pane(); // zb-00036 #29889 : load it only once List<ContentType.TabI> _virtualTabs; //default to true! private bool _savePropertyDataWhenInvalid = true; private ContentType _contentType; public Content ContentObject { get { return _content; } } /// <summary> /// This property controls whether the content property values are persisted even if validation /// fails. If set to false, then the values will not be persisted. /// </summary> /// <remarks> /// This is required because when we are editing content we should be persisting invalid values to the database /// as this makes it easier for editors to come back and fix up their changes before they publish. Of course we /// don't publish if the page is invalid. In the case of media and members, we don't want to persist the values /// to the database when the page is invalid because there is no published state. /// Relates to: http://issues.umbraco.org/issue/U4-227 /// </remarks> public bool SavePropertyDataWhenInvalid { get { return _savePropertyDataWhenInvalid; } set { _savePropertyDataWhenInvalid = value; } } [Obsolete("This is no longer used and will be removed from the codebase in future versions")] private string _errorMessage = ""; [Obsolete("This is no longer used and will be removed from the codebase in future versions")] public string ErrorMessage { set { _errorMessage = value; } } [Obsolete("This is no longer used and will be removed from the codebase in future versions")] protected void standardSaveAndPublishHandler(object sender, EventArgs e) { } /// <summary> /// Constructor to set default properties. /// </summary> /// <param name="c"></param> /// <param name="CanPublish"></param> /// <param name="Id"></param> /// <remarks> /// This method used to create all of the child controls too which is BAD since /// the page hasn't started initializing yet. Control IDs were not being named /// correctly, etc... I've moved the child control setup/creation to the CreateChildControls /// method where they are suposed to be. /// </remarks> public ContentControl(Content c, publishModes CanPublish, string Id) { ID = Id; this._canPublish = CanPublish; _content = c; Width = 350; Height = 350; _prntpage = (UmbracoEnsuredPage)Page; // zb-00036 #29889 : load it only once if (_virtualTabs == null) _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); foreach (ContentType.TabI t in _virtualTabs) { TabPage tp = NewTabPage(t.Caption); AddSaveAndPublishButtons(ref tp); } } /// <summary> /// Create and setup all of the controls child controls. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); _prntpage = (UmbracoEnsuredPage)Page; int i = 0; Hashtable inTab = new Hashtable(); // zb-00036 #29889 : load it only once if (_virtualTabs == null) _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); if(_contentType == null) _contentType = ContentType.GetContentType(_content.ContentType.Id); foreach (ContentType.TabI tab in _virtualTabs) { var tabPage = this.Panels[i] as TabPage; if (tabPage == null) { throw new ArgumentException("Unable to load tab \"" + tab.Caption + "\""); } tabPage.Style.Add("text-align", "center"); //Legacy vs New API loading of PropertyTypes if (_contentType.ContentTypeItem != null) { LoadPropertyTypes(_contentType.ContentTypeItem, tabPage, inTab, tab.Id, tab.Caption); } else { LoadPropertyTypes(tab, tabPage, inTab); } i++; } // Add property pane tpProp = NewTabPage(ui.Text("general", "properties", null)); AddSaveAndPublishButtons(ref tpProp); tpProp.Controls.Add( new LiteralControl("<div id=\"errorPane_" + tpProp.ClientID + "\" style=\"display: none; text-align: left; color: red;width: 100%; border: 1px solid red; background-color: #FCDEDE\"><div><b>There were errors - data has not been saved!</b><br/></div></div>")); //if the property is not in a tab, add it to the general tab var props = _content.GenericProperties; foreach (Property p in props) { if (inTab[p.PropertyType.Id.ToString()] == null) AddControlNew(p, tpProp, ui.Text("general", "properties", null)); } } /// <summary> /// Loades PropertyTypes by Tab/PropertyGroup using the new API. /// </summary> /// <param name="contentType"></param> /// <param name="tabPage"></param> /// <param name="inTab"></param> /// <param name="tabId"></param> /// <param name="tabCaption"></param> private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption) { var propertyGroups = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId); var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple<int, string, int>(y.Id, y.Alias, y.SortOrder))); foreach (var items in propertyTypeAliases) { var property = _content.getProperty(items.Item2); if (property != null) { AddControlNew(property, tabPage, tabCaption); if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture))) inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true); } else { throw new ArgumentNullException( string.Format( "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", items.Item2, items.Item1, _content.ContentType.Alias, _content.Id, tabCaption)); } } } /// <summary> /// Loades PropertyTypes by Tab using the Legacy API. /// </summary> /// <param name="tab"></param> /// <param name="tabPage"></param> /// <param name="inTab"></param> private void LoadPropertyTypes(ContentType.TabI tab, TabPage tabPage, Hashtable inTab) { // Iterate through the property types and add them to the tab // zb-00036 #29889 : fix property types getter to get the right set of properties // ge : had a bit of a corrupt db and got weird NRE errors so rewrote this to catch the error and rethrow with detail var propertyTypes = tab.GetPropertyTypes(_content.ContentType.Id); foreach (var propertyType in propertyTypes.OrderBy(x => x.SortOrder)) { var property = _content.getProperty(propertyType); if (property != null && tabPage != null) { AddControlNew(property, tabPage, tab.Caption); // adding this check, as we occasionally get an already in dictionary error, though not sure why if (!inTab.ContainsKey(propertyType.Id.ToString(CultureInfo.InvariantCulture))) inTab.Add(propertyType.Id.ToString(CultureInfo.InvariantCulture), true); } else { throw new ArgumentNullException( string.Format( "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", propertyType.Alias, propertyType.Id, _content.ContentType.Alias, _content.Id, tab.Caption)); } } } /// <summary> /// Initializes the control and ensures child controls are setup /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); // Add extras for the property tabpage. . ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); FireBeforeContentControlLoad(contentcontrolEvent); if (!contentcontrolEvent.Cancel) { NameTxt.ID = "NameTxt"; if (!Page.IsPostBack) { NameTxt.Text = _content.Text; } // Name validation NameTxtValidator.ControlToValidate = NameTxt.ID; _nameTxtCustomValidator.ControlToValidate = NameTxt.ID; string[] errorVars = { ui.Text("name") }; NameTxtValidator.ErrorMessage = " " + ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null) + "<br/>"; NameTxtValidator.EnableClientScript = false; NameTxtValidator.Display = ValidatorDisplay.Dynamic; _nameTxtCustomValidator.EnableClientScript = false; _nameTxtCustomValidator.Display = ValidatorDisplay.Dynamic; _nameTxtCustomValidator.ServerValidate += NameTxtCustomValidatorServerValidate; _nameTxtCustomValidator.ValidateEmptyText = false; NameTxtHolder.Controls.Add(NameTxt); NameTxtHolder.Controls.Add(NameTxtValidator); NameTxtHolder.Controls.Add(_nameTxtCustomValidator); PropertiesPane.addProperty(ui.Text("general", "name", null), NameTxtHolder); Literal ltt = new Literal(); ltt.Text = _content.User.Name; PropertiesPane.addProperty(ui.Text("content", "createBy", null), ltt); ltt = new Literal(); ltt.Text = _content.CreateDateTime.ToString(); PropertiesPane.addProperty(ui.Text("content", "createDate", null), ltt); ltt = new Literal(); ltt.Text = _content.Id.ToString(); PropertiesPane.addProperty("Id", ltt); if (_content is Media) { PropertiesPane.addProperty(ui.Text("content", "mediatype"), new LiteralControl(_content.ContentType.Alias)); } tpProp.Controls.AddAt(0, PropertiesPane); tpProp.Style.Add("text-align", "center"); } } /// <summary> /// Custom validates the content name field /// </summary> /// <param name="source"></param> /// <param name="args"></param> /// <remarks> /// We need to ensure people are not entering XSS attacks on this field /// http://issues.umbraco.org/issue/U4-485 /// /// This doesn't actually 'validate' but changes the text field value and strips html /// </remarks> void NameTxtCustomValidatorServerValidate(object source, ServerValidateEventArgs args) { NameTxt.Text = NameTxt.Text.StripHtml(); args.IsValid = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); FireAfterContentControlLoad(contentcontrolEvent); } /// <summary> /// Sets the name (text) and values on the data types of the document /// </summary> private void SetNameAndDataTypeValues() { //we only continue saving anything if: // SavePropertyDataWhenInvalid == true // OR if the page is actually valid. if (SavePropertyDataWhenInvalid || Page.IsValid) { foreach (var property in DataTypes) { var defaultData = property.Value.Data as DefaultData; if (defaultData != null) { defaultData.PropertyTypeAlias = property.Key; defaultData.NodeId = _content.Id; } property.Value.DataEditor.Save(); } //don't update if the name is empty if (!NameTxt.Text.IsNullOrWhiteSpace()) { _content.Text = NameTxt.Text; } } } private void SaveClick(object sender, ImageClickEventArgs e) { SetNameAndDataTypeValues(); if (Save != null) { Save(this, new EventArgs()); } } private void DoSaveAndPublish(object sender, ImageClickEventArgs e) { DoesPublish = true; SetNameAndDataTypeValues(); //NOTE: This is only here to keep backwards compatibility. // see: http://issues.umbraco.org/issue/U4-1660 Save(this, new EventArgs()); if (SaveAndPublish != null) { SaveAndPublish(this, new EventArgs()); } } private void DoSaveToPublish(object sender, ImageClickEventArgs e) { SaveClick(sender, e); if (SaveToPublish != null) { SaveToPublish(this, new EventArgs()); } } private void AddSaveAndPublishButtons(ref TabPage tp) { MenuImageButton menuSave = tp.Menu.NewImageButton(); menuSave.ID = tp.ID + "_save"; menuSave.ImageUrl = UmbracoPath + "/images/editor/save.gif"; menuSave.Click += new ImageClickEventHandler(SaveClick); menuSave.OnClickCommand = "invokeSaveHandlers();"; menuSave.AltText = ui.Text("buttons", "save", null); if (_canPublish == publishModes.Publish) { MenuImageButton menuPublish = tp.Menu.NewImageButton(); menuPublish.ID = tp.ID + "_publish"; menuPublish.ImageUrl = UmbracoPath + "/images/editor/saveAndPublish.gif"; menuPublish.OnClickCommand = "invokeSaveHandlers();"; menuPublish.Click += new ImageClickEventHandler(DoSaveAndPublish); menuPublish.AltText = ui.Text("buttons", "saveAndPublish", null); } else if (_canPublish == publishModes.SendToPublish) { MenuImageButton menuToPublish = tp.Menu.NewImageButton(); menuToPublish.ID = tp.ID + "_topublish"; menuToPublish.ImageUrl = UmbracoPath + "/images/editor/saveToPublish.gif"; menuToPublish.OnClickCommand = "invokeSaveHandlers();"; menuToPublish.Click += new ImageClickEventHandler(DoSaveToPublish); menuToPublish.AltText = ui.Text("buttons", "saveToPublish", null); } } private void AddControlNew(Property p, TabPage tp, string cap) { IDataType dt = p.PropertyType.DataTypeDefinition.DataType; dt.DataEditor.Editor.ID = string.Format("prop_{0}", p.PropertyType.Alias); dt.Data.PropertyId = p.Id; //Add the DataType to an internal dictionary, which will be used to call the save method on the IDataEditor //and to retrieve the value from IData in editContent.aspx.cs, so that it can be set on the legacy Document class. DataTypes.Add(p.PropertyType.Alias, dt); // check for buttons IDataFieldWithButtons df1 = dt.DataEditor.Editor as IDataFieldWithButtons; if (df1 != null) { ((Control)df1).ID = p.PropertyType.Alias; if (df1.MenuIcons.Length > 0) tp.Menu.InsertSplitter(); // Add buttons int c = 0; bool atEditHtml = false; bool atSplitter = false; foreach (object o in df1.MenuIcons) { try { MenuIconI m = (MenuIconI)o; MenuIconI mi = tp.Menu.NewIcon(); mi.ImageURL = m.ImageURL; mi.OnClickCommand = m.OnClickCommand; mi.AltText = m.AltText; mi.ID = tp.ID + "_" + m.ID; if (m.ID == "html") atEditHtml = true; else atEditHtml = false; atSplitter = false; } catch { tp.Menu.InsertSplitter(); atSplitter = true; } // Testing custom styles in editor if (atSplitter && atEditHtml && dt.DataEditor.TreatAsRichTextEditor) { DropDownList ddl = tp.Menu.NewDropDownList(); ddl.Style.Add("margin-bottom", "5px"); ddl.Items.Add(ui.Text("buttons", "styleChoose", null)); ddl.ID = tp.ID + "_editorStyle"; if (StyleSheet.GetAll().Length > 0) { foreach (StyleSheet s in StyleSheet.GetAll()) { foreach (StylesheetProperty sp in s.Properties) { ddl.Items.Add(new ListItem(sp.Text, sp.Alias)); } } } ddl.Attributes.Add("onChange", "addStyle(this, '" + p.PropertyType.Alias + "');"); atEditHtml = false; } c++; } } // check for element additions IMenuElement menuElement = dt.DataEditor.Editor as IMenuElement; if (menuElement != null) { // add separator tp.Menu.InsertSplitter(); // add the element tp.Menu.NewElement(menuElement.ElementName, menuElement.ElementIdPreFix + p.Id.ToString(), menuElement.ElementClass, menuElement.ExtraMenuWidth); } Pane pp = new Pane(); Control holder = new Control(); holder.Controls.Add(dt.DataEditor.Editor); if (p.PropertyType.DataTypeDefinition.DataType.DataEditor.ShowLabel) { string caption = p.PropertyType.Name; if (p.PropertyType.Description != null && p.PropertyType.Description != String.Empty) switch (UmbracoSettings.PropertyContextHelpOption) { case "icon": caption += " <img src=\"" + this.ResolveUrl(SystemDirectories.Umbraco) + "/images/help.png\" class=\"umbPropertyContextHelp\" alt=\"" + p.PropertyType.Description + "\" title=\"" + p.PropertyType.Description + "\" />"; break; case "text": caption += "<br /><small>" + umbraco.library.ReplaceLineBreaks(p.PropertyType.Description) + "</small>"; break; } pp.addProperty(caption, holder); } else pp.addProperty(holder); // Validation if (p.PropertyType.Mandatory) { try { RequiredFieldValidator rq = new RequiredFieldValidator(); rq.ControlToValidate = dt.DataEditor.Editor.ID; Control component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); ValidationPropertyAttribute attribute = (ValidationPropertyAttribute) TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; PropertyDescriptor pd = null; if (attribute != null) { pd = TypeDescriptor.GetProperties(component, (Attribute[])null)[attribute.Name]; } if (pd != null) { rq.EnableClientScript = false; rq.Display = ValidatorDisplay.Dynamic; string[] errorVars = { p.PropertyType.Name, cap }; rq.ErrorMessage = ui.Text("errorHandling", "errorMandatory", errorVars, null) + "<br/>"; holder.Controls.AddAt(0, rq); } } catch (Exception valE) { HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE); } } // RegExp Validation if (p.PropertyType.ValidationRegExp != "") { try { RegularExpressionValidator rv = new RegularExpressionValidator(); rv.ControlToValidate = dt.DataEditor.Editor.ID; Control component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); ValidationPropertyAttribute attribute = (ValidationPropertyAttribute) TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; PropertyDescriptor pd = null; if (attribute != null) { pd = TypeDescriptor.GetProperties(component, (Attribute[])null)[attribute.Name]; } if (pd != null) { rv.ValidationExpression = p.PropertyType.ValidationRegExp; rv.EnableClientScript = false; rv.Display = ValidatorDisplay.Dynamic; string[] errorVars = { p.PropertyType.Name, cap }; rv.ErrorMessage = ui.Text("errorHandling", "errorRegExp", errorVars, null) + "<br/>"; holder.Controls.AddAt(0, rv); } } catch (Exception valE) { HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE); } } // This is once again a nasty nasty hack to fix gui when rendering wysiwygeditor if (dt.DataEditor.TreatAsRichTextEditor) { tp.Controls.Add(dt.DataEditor.Editor); } else { Panel ph = new Panel(); ph.Attributes.Add("style", "padding: 0; position: relative;"); // NH 4.7.1, latest styles added to support CP item: 30363 ph.Controls.Add(pp); tp.Controls.Add(ph); } } public enum publishModes { Publish, SendToPublish, NoPublish } // EVENTS public delegate void BeforeContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); public delegate void AfterContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); /// <summary> /// Occurs when [before content control load]. /// </summary> public static event BeforeContentControlLoadEventHandler BeforeContentControlLoad; /// <summary> /// Fires the before content control load. /// </summary> /// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param> protected virtual void FireBeforeContentControlLoad(ContentControlLoadEventArgs e) { if (BeforeContentControlLoad != null) BeforeContentControlLoad(this, e); } /// <summary> /// Occurs when [before content control load]. /// </summary> public static event AfterContentControlLoadEventHandler AfterContentControlLoad; /// <summary> /// Fires the before content control load. /// </summary> /// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param> protected virtual void FireAfterContentControlLoad(ContentControlLoadEventArgs e) { if (AfterContentControlLoad != null) AfterContentControlLoad(this, e); } } }
using System; using System.Collections.Generic; using Box2D; using Box2D.Collision; using Box2D.Common; using Box2D.Collision.Shapes; using Box2D.Dynamics; using Box2D.Dynamics.Contacts; using Microsoft.Xna.Framework; using CocosSharp; using Random = CocosSharp.CCRandom; namespace tests { internal class CCPhysicsSprite : CCSprite { private b2Body m_pBody; // strong ref public CCPhysicsSprite(CCTexture2D f, CCRect r) : base(f, r) { } public b2Body PhysicsBody { get { return (m_pBody); } set { m_pBody = value; } } public override CCAffineTransform AffineLocalTransform { get { if (m_pBody == null) return base.AffineLocalTransform; b2Vec2 pos = m_pBody.Position; float x = pos.x * Box2DTestLayer.PTM_RATIO; float y = pos.y * Box2DTestLayer.PTM_RATIO; if (IgnoreAnchorPointForPosition) { x += AnchorPointInPoints.X; y += AnchorPointInPoints.Y; } // Make matrix float radians = m_pBody.Angle; var c = (float)Math.Cos (radians); var s = (float)Math.Sin (radians); if (!AnchorPointInPoints.Equals (CCPoint.Zero)) { x += c * -AnchorPointInPoints.X + -s * -AnchorPointInPoints.Y; y += s * -AnchorPointInPoints.X + c * -AnchorPointInPoints.Y; } // Rot, Translate Matrix var m_sTransform = new CCAffineTransform (c, s, -s, c, x, y); return m_sTransform; } } } public class Box2DTestLayer : CCLayer { public class Myb2Listener : b2ContactListener { public override void PreSolve(b2Contact contact, b2Manifold oldManifold) { } public override void PostSolve(Box2D.Dynamics.Contacts.b2Contact contact, ref b2ContactImpulse impulse) { } } public const int PTM_RATIO = 32; private const int kTagParentNode = 1; private readonly CCTexture2D m_pSpriteTexture; // weak ref private b2World _world; private CCSpriteBatchNode _batch; public Box2DTestLayer() { //Set up sprite // Use batch node. Faster _batch = new CCSpriteBatchNode("Images/blocks", 100); m_pSpriteTexture = _batch.Texture; AddChild(_batch, 0, kTagParentNode); Camera = AppDelegate.SharedCamera; } public override void OnEnter() { base.OnEnter(); var listener = new CCEventListenerTouchAllAtOnce(); listener.OnTouchesEnded = onTouchesEnded; AddEventListener(listener); CCSize s = Layer.VisibleBoundsWorldspace.Size; // init physics initPhysics(); // create reset button createResetButton(); addNewSpriteAtPosition(new CCPoint(s.Width / 2, s.Height / 2)); CCLabelTtf label = new CCLabelTtf("Tap screen", "MarkerFelt", 32); AddChild(label, 0); label.Color = new CCColor3B(0, 0, 255); label.Position = new CCPoint(s.Width / 2, s.Height - 50); Schedule (); } private void initPhysics() { CCSize s = Layer.VisibleBoundsWorldspace.Size; var gravity = new b2Vec2(0.0f, -10.0f); _world = new b2World(gravity); float debugWidth = s.Width / PTM_RATIO * 2f; float debugHeight = s.Height / PTM_RATIO * 2f; //CCBox2dDraw debugDraw = new CCBox2dDraw(new b2Vec2(debugWidth / 2f + 10, s.Height - debugHeight - 10), 2); //debugDraw.AppendFlags(b2DrawFlags.e_shapeBit); //_world.SetDebugDraw(debugDraw); _world.SetAllowSleeping(true); _world.SetContinuousPhysics(true); //m_debugDraw = new GLESDebugDraw( PTM_RATIO ); //world->SetDebugDraw(m_debugDraw); //uint32 flags = 0; //flags += b2Draw::e_shapeBit; // flags += b2Draw::e_jointBit; // flags += b2Draw::e_aabbBit; // flags += b2Draw::e_pairBit; // flags += b2Draw::e_centerOfMassBit; //m_debugDraw->SetFlags(flags); // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). // The body is also added to the world. b2BodyDef def = new b2BodyDef(); def.allowSleep = true; def.position = b2Vec2.Zero; def.type = b2BodyType.b2_staticBody; b2Body groundBody = _world.CreateBody(def); groundBody.SetActive(true); // Define the ground box shape. // bottom b2EdgeShape groundBox = new b2EdgeShape(); groundBox.Set(b2Vec2.Zero, new b2Vec2(s.Width / PTM_RATIO, 0)); b2FixtureDef fd = new b2FixtureDef(); fd.shape = groundBox; groundBody.CreateFixture(fd); // top groundBox = new b2EdgeShape(); groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO)); fd.shape = groundBox; groundBody.CreateFixture(fd); // left groundBox = new b2EdgeShape(); groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), b2Vec2.Zero); fd.shape = groundBox; groundBody.CreateFixture(fd); // right groundBox = new b2EdgeShape(); groundBox.Set(new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, 0)); fd.shape = groundBox; groundBody.CreateFixture(fd); // _world.Dump(); } public void createResetButton() { CCMenuItemImage res = new CCMenuItemImage("Images/r1", "Images/r2", reset); CCMenu menu = new CCMenu(res); CCSize s = Layer.VisibleBoundsWorldspace.Size; menu.Position = new CCPoint(s.Width / 2, 30); AddChild(menu, -1); } public void reset(object sender) { CCScene s = new Box2DTestScene(); var child = new Box2DTestLayer(); s.AddChild(child); Director.ReplaceScene(s); } /* public override void Draw() { // // IMPORTANT: // This is only for debug purposes // It is recommend to disable it // base.Draw(); //ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); //kmGLPushMatrix(); CCDrawingPrimitives.Begin(); _world.DrawDebugData(); CCDrawingPrimitives.End(); //world.DrawDebugData(); //kmGLPopMatrix(); } */ private const int kTagForPhysicsSprite = 99999; public void addNewSpriteAtPosition(CCPoint p) { CCLog.Log("Add sprite #{2} : {0} x {1}", p.X, p.Y, _batch.ChildrenCount + 1); //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is //just randomly picking one of the images int idx = (CCRandom.Float_0_1() > .5 ? 0 : 1); int idy = (CCRandom.Float_0_1() > .5 ? 0 : 1); var sprite = new CCPhysicsSprite(m_pSpriteTexture, new CCRect(32 * idx, 32 * idy, 32, 32)); _batch.AddChild(sprite, 0, kTagForPhysicsSprite); sprite.Position = new CCPoint(p.X, p.Y); // Define the dynamic body. //Set up a 1m squared box in the physics world b2BodyDef def = new b2BodyDef(); def.position = new b2Vec2(p.X / PTM_RATIO, p.Y / PTM_RATIO); def.type = b2BodyType.b2_dynamicBody; b2Body body = _world.CreateBody(def); // Define another box shape for our dynamic body. var dynamicBox = new b2PolygonShape(); dynamicBox.SetAsBox(.5f, .5f); //These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fd = new b2FixtureDef(); fd.shape = dynamicBox; fd.density = 1f; fd.friction = 0.3f; b2Fixture fixture = body.CreateFixture(fd); sprite.PhysicsBody = body; //_world.SetContactListener(new Myb2Listener()); // _world.Dump(); } public override void Update(float dt) { _world.Step(dt, 8, 1); //_world.Step(dt, 10, 3); foreach (CCPhysicsSprite sprite in _batch.Children) { if (sprite.Visible && sprite.PhysicsBody.Position.y < 0f) { _world.DestroyBody (sprite.PhysicsBody); sprite.Visible = false; } else { sprite.UpdateTransformedSpriteTextureQuads(); } } //#if WINDOWS || WINDOWSGL || LINUX || MACOS // // This needs replacing with EventDispatcher // CCInputState.Instance.Update(dt); // PlayerIndex p; // if (CCInputState.Instance.IsKeyPress(Microsoft.Xna.Framework.Input.Keys.D, PlayerIndex.One, out p)) // { // _world.Dump(); //#if PROFILING // b2Profile profile = _world.Profile; // CCLog.Log("]-----------[{0:F4}]-----------------------[", profile.step); // CCLog.Log("Solve Time = {0:F4}", profile.solve); // CCLog.Log("# bodies = {0}", profile.bodyCount); // CCLog.Log("# contacts = {0}", profile.contactCount); // CCLog.Log("# joints = {0}", profile.jointCount); // CCLog.Log("# toi iters = {0}", profile.toiSolverIterations); // if (profile.step > 0f) // { // CCLog.Log("Solve TOI Time = {0:F4} {1:F2}%", profile.solveTOI, profile.solveTOI / profile.step * 100f); // CCLog.Log("Solve TOI Advance Time = {0:F4} {1:F2}%", profile.solveTOIAdvance, profile.solveTOIAdvance / profile.step * 100f); // } // // CCLog.Log("BroadPhase Time = {0:F4}", profile.broadphase); // CCLog.Log("Collision Time = {0:F4}", profile.collide); // CCLog.Log("Solve Velocity Time = {0:F4}", profile.solveVelocity); // CCLog.Log("Solve Position Time = {0:F4}", profile.solvePosition); // CCLog.Log("Step Time = {0:F4}", profile.step); //#endif // } //#endif } void onTouchesEnded(List<CCTouch> touches, CCEvent touchEvent) { //Add a new body/atlas sprite at the touched location foreach (CCTouch touch in touches) { CCPoint location = Layer.ScreenToWorldspace(touch.LocationOnScreen); addNewSpriteAtPosition(location); } } } internal class Box2DTestScene : TestScene { protected override void NextTestCase() { } protected override void PreviousTestCase() { } protected override void RestTestCase() { } public override void runThisTest() { CCLayer pLayer = new Box2DTestLayer(); AddChild(pLayer); Director.ReplaceScene(this); } } }
using System.Net; using FluentAssertions; using FluentAssertions.Extensions; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.Sorting; public sealed class SortTests : IClassFixture<IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext>> { private readonly IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> _testContext; private readonly QueryStringFakers _fakers = new(); public SortTests(IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> testContext) { _testContext = testContext; testContext.UseController<BlogPostsController>(); testContext.UseController<BlogsController>(); testContext.UseController<WebAccountsController>(); } [Fact] public async Task Can_sort_in_primary_resources() { // Arrange List<BlogPost> posts = _fakers.BlogPost.Generate(3); posts[0].Caption = "B"; posts[1].Caption = "A"; posts[2].Caption = "C"; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); const string route = "/blogPosts?sort=caption"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(3); responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(posts[0].StringId); responseDocument.Data.ManyValue[2].Id.Should().Be(posts[2].StringId); } [Fact] public async Task Cannot_sort_in_single_primary_resource() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}?sort=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified sort is invalid."); error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource)."); error.Source.ShouldNotBeNull(); error.Source.Parameter.Should().Be("sort"); } [Fact] public async Task Can_sort_in_secondary_resources() { // Arrange Blog blog = _fakers.Blog.Generate(); blog.Posts = _fakers.BlogPost.Generate(3); blog.Posts[0].Caption = "B"; blog.Posts[1].Caption = "A"; blog.Posts[2].Caption = "C"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/posts?sort=caption"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(3); responseDocument.Data.ManyValue[0].Id.Should().Be(blog.Posts[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(blog.Posts[0].StringId); responseDocument.Data.ManyValue[2].Id.Should().Be(blog.Posts[2].StringId); } [Fact] public async Task Cannot_sort_in_single_secondary_resource() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}/author?sort=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified sort is invalid."); error.Detail.Should().Be("This query string parameter can only be used on a collection of resources (not on a single resource)."); error.Source.ShouldNotBeNull(); error.Source.Parameter.Should().Be("sort"); } [Fact] public async Task Can_sort_on_OneToMany_relationship() { // Arrange List<Blog> blogs = _fakers.Blog.Generate(2); blogs[0].Posts = _fakers.BlogPost.Generate(2); blogs[1].Posts = _fakers.BlogPost.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Blog>(); dbContext.Blogs.AddRange(blogs); await dbContext.SaveChangesAsync(); }); const string route = "/blogs?sort=count(posts)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(blogs[0].StringId); } [Fact] public async Task Can_sort_on_ManyToMany_relationship() { // Arrange List<BlogPost> posts = _fakers.BlogPost.Generate(2); posts[0].Labels = _fakers.Label.Generate(1).ToHashSet(); posts[1].Labels = _fakers.Label.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); const string route = "/blogPosts?sort=-count(labels)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(posts[0].StringId); } [Fact] public async Task Can_sort_in_scope_of_OneToMany_relationship() { // Arrange WebAccount account = _fakers.WebAccount.Generate(); account.Posts = _fakers.BlogPost.Generate(3); account.Posts[0].Caption = "B"; account.Posts[1].Caption = "A"; account.Posts[2].Caption = "C"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Accounts.Add(account); await dbContext.SaveChangesAsync(); }); string route = $"/webAccounts/{account.StringId}?include=posts&sort[posts]=caption"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(account.StringId); responseDocument.Included.ShouldHaveCount(3); responseDocument.Included[0].Id.Should().Be(account.Posts[1].StringId); responseDocument.Included[1].Id.Should().Be(account.Posts[0].StringId); responseDocument.Included[2].Id.Should().Be(account.Posts[2].StringId); } [Fact] public async Task Can_sort_in_scope_of_OneToMany_relationship_on_secondary_endpoint() { // Arrange Blog blog = _fakers.Blog.Generate(); blog.Owner = _fakers.WebAccount.Generate(); blog.Owner.Posts = _fakers.BlogPost.Generate(3); blog.Owner.Posts[0].Caption = "B"; blog.Owner.Posts[1].Caption = "A"; blog.Owner.Posts[2].Caption = "C"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Blogs.Add(blog); await dbContext.SaveChangesAsync(); }); string route = $"/blogs/{blog.StringId}/owner?include=posts&sort[posts]=caption"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(blog.Owner.StringId); responseDocument.Included.ShouldHaveCount(3); responseDocument.Included[0].Id.Should().Be(blog.Owner.Posts[1].StringId); responseDocument.Included[1].Id.Should().Be(blog.Owner.Posts[0].StringId); responseDocument.Included[2].Id.Should().Be(blog.Owner.Posts[2].StringId); } [Fact] public async Task Can_sort_in_scope_of_ManyToMany_relationship() { // Arrange BlogPost post = _fakers.BlogPost.Generate(); post.Labels = _fakers.Label.Generate(3).ToHashSet(); post.Labels.ElementAt(0).Name = "B"; post.Labels.ElementAt(1).Name = "A"; post.Labels.ElementAt(2).Name = "C"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(); }); string route = $"/blogPosts/{post.StringId}?include=labels&sort[labels]=name"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(post.StringId); responseDocument.Included.ShouldHaveCount(3); responseDocument.Included[0].Id.Should().Be(post.Labels.ElementAt(1).StringId); responseDocument.Included[1].Id.Should().Be(post.Labels.ElementAt(0).StringId); responseDocument.Included[2].Id.Should().Be(post.Labels.ElementAt(2).StringId); } [Fact] public async Task Can_sort_on_multiple_fields_in_multiple_scopes() { // Arrange List<Blog> blogs = _fakers.Blog.Generate(2); blogs[0].Title = "Z"; blogs[1].Title = "Y"; blogs[0].Posts = _fakers.BlogPost.Generate(4); blogs[0].Posts[0].Caption = "B"; blogs[0].Posts[1].Caption = "A"; blogs[0].Posts[2].Caption = "A"; blogs[0].Posts[3].Caption = "C"; blogs[0].Posts[0].Url = ""; blogs[0].Posts[1].Url = "www.some2.com"; blogs[0].Posts[2].Url = "www.some1.com"; blogs[0].Posts[3].Url = ""; blogs[0].Posts[0].Comments = _fakers.Comment.Generate(3).ToHashSet(); blogs[0].Posts[0].Comments.ElementAt(0).CreatedAt = 1.January(2015).AsUtc(); blogs[0].Posts[0].Comments.ElementAt(1).CreatedAt = 1.January(2014).AsUtc(); blogs[0].Posts[0].Comments.ElementAt(2).CreatedAt = 1.January(2016).AsUtc(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Blog>(); dbContext.Blogs.AddRange(blogs); await dbContext.SaveChangesAsync(); }); const string route = "/blogs?include=posts.comments&sort=title&sort[posts]=caption,url&sort[posts.comments]=-createdAt"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(blogs[0].StringId); responseDocument.Included.ShouldHaveCount(7); responseDocument.Included[0].Type.Should().Be("blogPosts"); responseDocument.Included[0].Id.Should().Be(blogs[0].Posts[2].StringId); responseDocument.Included[1].Type.Should().Be("blogPosts"); responseDocument.Included[1].Id.Should().Be(blogs[0].Posts[1].StringId); responseDocument.Included[2].Type.Should().Be("blogPosts"); responseDocument.Included[2].Id.Should().Be(blogs[0].Posts[0].StringId); responseDocument.Included[3].Type.Should().Be("comments"); responseDocument.Included[3].Id.Should().Be(blogs[0].Posts[0].Comments.ElementAt(2).StringId); responseDocument.Included[4].Type.Should().Be("comments"); responseDocument.Included[4].Id.Should().Be(blogs[0].Posts[0].Comments.ElementAt(0).StringId); responseDocument.Included[5].Type.Should().Be("comments"); responseDocument.Included[5].Id.Should().Be(blogs[0].Posts[0].Comments.ElementAt(1).StringId); responseDocument.Included[6].Type.Should().Be("blogPosts"); responseDocument.Included[6].Id.Should().Be(blogs[0].Posts[3].StringId); } [Fact] public async Task Can_sort_on_ManyToOne_relationship() { // Arrange List<BlogPost> posts = _fakers.BlogPost.Generate(2); posts[0].Author = _fakers.WebAccount.Generate(); posts[1].Author = _fakers.WebAccount.Generate(); posts[0].Author!.DisplayName = "Conner"; posts[1].Author!.DisplayName = "Smith"; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BlogPost>(); dbContext.Posts.AddRange(posts); await dbContext.SaveChangesAsync(); }); const string route = "/blogPosts?sort=-author.displayName"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(posts[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(posts[0].StringId); } [Fact] public async Task Can_sort_in_multiple_scopes() { // Arrange List<Blog> blogs = _fakers.Blog.Generate(2); blogs[0].Title = "Cooking"; blogs[1].Title = "Technology"; blogs[1].Owner = _fakers.WebAccount.Generate(); blogs[1].Owner!.Posts = _fakers.BlogPost.Generate(2); blogs[1].Owner!.Posts[0].Caption = "One"; blogs[1].Owner!.Posts[1].Caption = "Two"; blogs[1].Owner!.Posts[1].Comments = _fakers.Comment.Generate(2).ToHashSet(); blogs[1].Owner!.Posts[1].Comments.ElementAt(0).CreatedAt = 1.January(2000).AsUtc(); blogs[1].Owner!.Posts[1].Comments.ElementAt(0).CreatedAt = 10.January(2010).AsUtc(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Blog>(); dbContext.Blogs.AddRange(blogs); await dbContext.SaveChangesAsync(); }); const string route = "/blogs?include=owner.posts.comments&sort=-title&sort[owner.posts]=-caption&sort[owner.posts.comments]=-createdAt"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(blogs[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(blogs[0].StringId); responseDocument.Included.ShouldHaveCount(5); responseDocument.Included[0].Type.Should().Be("webAccounts"); responseDocument.Included[0].Id.Should().Be(blogs[1].Owner!.StringId); responseDocument.Included[1].Type.Should().Be("blogPosts"); responseDocument.Included[1].Id.Should().Be(blogs[1].Owner!.Posts[1].StringId); responseDocument.Included[2].Type.Should().Be("comments"); responseDocument.Included[2].Id.Should().Be(blogs[1].Owner!.Posts[1].Comments.ElementAt(1).StringId); responseDocument.Included[3].Type.Should().Be("comments"); responseDocument.Included[3].Id.Should().Be(blogs[1].Owner!.Posts[1].Comments.ElementAt(0).StringId); responseDocument.Included[4].Type.Should().Be("blogPosts"); responseDocument.Included[4].Id.Should().Be(blogs[1].Owner!.Posts[0].StringId); } [Fact] public async Task Cannot_sort_in_unknown_scope() { // Arrange const string route = $"/webAccounts?sort[{Unknown.Relationship}]=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified sort is invalid."); error.Detail.Should().Be($"Relationship '{Unknown.Relationship}' does not exist on resource type 'webAccounts'."); error.Source.ShouldNotBeNull(); error.Source.Parameter.Should().Be($"sort[{Unknown.Relationship}]"); } [Fact] public async Task Cannot_sort_in_unknown_nested_scope() { // Arrange const string route = $"/webAccounts?sort[posts.{Unknown.Relationship}]=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("The specified sort is invalid."); error.Detail.Should().Be($"Relationship '{Unknown.Relationship}' in 'posts.{Unknown.Relationship}' does not exist on resource type 'blogPosts'."); error.Source.ShouldNotBeNull(); error.Source.Parameter.Should().Be($"sort[posts.{Unknown.Relationship}]"); } [Fact] public async Task Cannot_sort_on_attribute_with_blocked_capability() { // Arrange const string route = "/webAccounts?sort=dateOfBirth"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Sorting on the requested attribute is not allowed."); error.Detail.Should().Be("Sorting on attribute 'dateOfBirth' is not allowed."); error.Source.ShouldNotBeNull(); error.Source.Parameter.Should().Be("sort"); } [Fact] public async Task Can_sort_descending_by_ID() { // Arrange List<WebAccount> accounts = _fakers.WebAccount.Generate(3); accounts[0].Id = 3000; accounts[1].Id = 2000; accounts[2].Id = 1000; accounts[0].DisplayName = "B"; accounts[1].DisplayName = "A"; accounts[2].DisplayName = "A"; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebAccount>(); dbContext.Accounts.AddRange(accounts); await dbContext.SaveChangesAsync(); }); const string route = "/webAccounts?sort=displayName,-id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(3); responseDocument.Data.ManyValue[0].Id.Should().Be(accounts[1].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(accounts[2].StringId); responseDocument.Data.ManyValue[2].Id.Should().Be(accounts[0].StringId); } [Fact] public async Task Sorts_by_ID_if_none_specified() { // Arrange List<WebAccount> accounts = _fakers.WebAccount.Generate(4); accounts[0].Id = 300; accounts[1].Id = 200; accounts[2].Id = 100; accounts[3].Id = 400; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebAccount>(); dbContext.Accounts.AddRange(accounts); await dbContext.SaveChangesAsync(); }); const string route = "/webAccounts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.ShouldHaveCount(4); responseDocument.Data.ManyValue[0].Id.Should().Be(accounts[2].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(accounts[1].StringId); responseDocument.Data.ManyValue[2].Id.Should().Be(accounts[0].StringId); responseDocument.Data.ManyValue[3].Id.Should().Be(accounts[3].StringId); } }
//////////////////////////////////////////////////////////////////////////////// // ________ _____ __ // / _____/_______ _____ ____ ____ _/ ____\__ __ | | // / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| | // \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__ // \______ /|__| (____ / \___ >\___ >|__| |____/ |____/ // \/ \/ \/ \/ // ============================================================================= // Designed & Developed by Brad Jones <brad @="bjc.id.au" /> // ============================================================================= //////////////////////////////////////////////////////////////////////////////// namespace Graceful.Tests { using Xunit; using System; using System.Data; using Graceful.Utils; using System.Collections.Generic; public class TypeMapperTests { class IsClrTypeTestClass {} class UserTestClass : Model { public string Name { get; set; } } [Fact] public void GetDBTypeTest() { Assert.Equal(SqlDbType.BigInt, TypeMapper.GetDBType(typeof(Int64))); Assert.Equal(SqlDbType.Int, TypeMapper.GetDBType(typeof(Int32))); Assert.Equal(SqlDbType.SmallInt, TypeMapper.GetDBType(typeof(Int16))); Assert.Equal(SqlDbType.Decimal, TypeMapper.GetDBType(typeof(Decimal))); Assert.Equal(SqlDbType.Float, TypeMapper.GetDBType(typeof(Double))); Assert.Equal(SqlDbType.Real, TypeMapper.GetDBType(typeof(Single))); Assert.Equal(SqlDbType.TinyInt, TypeMapper.GetDBType(typeof(Byte))); Assert.Equal(SqlDbType.VarBinary, TypeMapper.GetDBType(typeof(Byte[]))); Assert.Equal(SqlDbType.Bit, TypeMapper.GetDBType(typeof(Boolean))); Assert.Equal(SqlDbType.Char, TypeMapper.GetDBType(typeof(Char))); Assert.Equal(SqlDbType.Char, TypeMapper.GetDBType(typeof(Char[]))); Assert.Equal(SqlDbType.NVarChar, TypeMapper.GetDBType(typeof(String))); Assert.Equal(SqlDbType.DateTime2, TypeMapper.GetDBType(typeof(DateTime))); Assert.Equal(SqlDbType.DateTimeOffset, TypeMapper.GetDBType(typeof(DateTimeOffset))); Assert.Equal(SqlDbType.Time, TypeMapper.GetDBType(typeof(TimeSpan))); Assert.Equal(SqlDbType.UniqueIdentifier, TypeMapper.GetDBType(typeof(Guid))); Assert.Equal(SqlDbType.Structured, TypeMapper.GetDBType(typeof(DataTable))); } [Fact] public void GetDBTypeNullableTest() { Assert.Equal(SqlDbType.BigInt, TypeMapper.GetDBType(typeof(Int64?))); Assert.Equal(SqlDbType.Int, TypeMapper.GetDBType(typeof(Int32?))); Assert.Equal(SqlDbType.SmallInt, TypeMapper.GetDBType(typeof(Int16?))); Assert.Equal(SqlDbType.Decimal, TypeMapper.GetDBType(typeof(Decimal?))); Assert.Equal(SqlDbType.Float, TypeMapper.GetDBType(typeof(Double?))); Assert.Equal(SqlDbType.Real, TypeMapper.GetDBType(typeof(Single?))); Assert.Equal(SqlDbType.TinyInt, TypeMapper.GetDBType(typeof(Byte?))); Assert.Equal(SqlDbType.Bit, TypeMapper.GetDBType(typeof(Boolean?))); Assert.Equal(SqlDbType.Char, TypeMapper.GetDBType(typeof(Char?))); Assert.Equal(SqlDbType.DateTime2, TypeMapper.GetDBType(typeof(DateTime?))); Assert.Equal(SqlDbType.DateTimeOffset, TypeMapper.GetDBType(typeof(DateTimeOffset?))); Assert.Equal(SqlDbType.Time, TypeMapper.GetDBType(typeof(TimeSpan?))); Assert.Equal(SqlDbType.UniqueIdentifier, TypeMapper.GetDBType(typeof(Guid?))); } [Fact] public void GetDBTypeFromValueTest() { Assert.Equal(SqlDbType.BigInt, TypeMapper.GetDBType((Int64)1)); Assert.Equal(SqlDbType.Int, TypeMapper.GetDBType((Int32)1)); Assert.Equal(SqlDbType.SmallInt, TypeMapper.GetDBType((Int16)1)); Assert.Equal(SqlDbType.Decimal, TypeMapper.GetDBType((Decimal)1.2)); Assert.Equal(SqlDbType.Float, TypeMapper.GetDBType((Double)1.2)); Assert.Equal(SqlDbType.Real, TypeMapper.GetDBType((Single)1.2)); Assert.Equal(SqlDbType.TinyInt, TypeMapper.GetDBType((Byte)1)); Assert.Equal(SqlDbType.VarBinary, TypeMapper.GetDBType(new Byte[]{1,2,3})); Assert.Equal(SqlDbType.Bit, TypeMapper.GetDBType(true)); Assert.Equal(SqlDbType.Char, TypeMapper.GetDBType('a')); Assert.Equal(SqlDbType.Char, TypeMapper.GetDBType(new Char[]{'a', 'b'})); Assert.Equal(SqlDbType.NVarChar, TypeMapper.GetDBType("abc")); Assert.Equal(SqlDbType.DateTime2, TypeMapper.GetDBType(DateTime.UtcNow)); Assert.Equal(SqlDbType.DateTimeOffset, TypeMapper.GetDBType(DateTimeOffset.Now)); Assert.Equal(SqlDbType.Time, TypeMapper.GetDBType(TimeSpan.FromDays(1))); Assert.Equal(SqlDbType.UniqueIdentifier, TypeMapper.GetDBType(Guid.NewGuid())); Assert.Equal(SqlDbType.Structured, TypeMapper.GetDBType(new DataTable())); } [Fact] public void GetClrTypeTest() { Assert.Equal(typeof(Int64), TypeMapper.GetClrType(SqlDbType.BigInt)); Assert.Equal(typeof(Int32), TypeMapper.GetClrType(SqlDbType.Int)); Assert.Equal(typeof(Int16), TypeMapper.GetClrType(SqlDbType.SmallInt)); Assert.Equal(typeof(Decimal), TypeMapper.GetClrType(SqlDbType.Decimal)); Assert.Equal(typeof(Decimal), TypeMapper.GetClrType(SqlDbType.Money)); Assert.Equal(typeof(Decimal), TypeMapper.GetClrType(SqlDbType.SmallMoney)); Assert.Equal(typeof(Double), TypeMapper.GetClrType(SqlDbType.Float)); Assert.Equal(typeof(Single), TypeMapper.GetClrType(SqlDbType.Real)); Assert.Equal(typeof(Byte), TypeMapper.GetClrType(SqlDbType.TinyInt)); Assert.Equal(typeof(Byte[]), TypeMapper.GetClrType(SqlDbType.Binary)); Assert.Equal(typeof(Byte[]), TypeMapper.GetClrType(SqlDbType.Image)); Assert.Equal(typeof(Byte[]), TypeMapper.GetClrType(SqlDbType.Timestamp)); Assert.Equal(typeof(Byte[]), TypeMapper.GetClrType(SqlDbType.VarBinary)); Assert.Equal(typeof(Boolean), TypeMapper.GetClrType(SqlDbType.Bit)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.Char)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.NChar)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.NText)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.NVarChar)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.Text)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.VarChar)); Assert.Equal(typeof(String), TypeMapper.GetClrType(SqlDbType.Xml)); Assert.Equal(typeof(DateTime), TypeMapper.GetClrType(SqlDbType.DateTime)); Assert.Equal(typeof(DateTime), TypeMapper.GetClrType(SqlDbType.SmallDateTime)); Assert.Equal(typeof(DateTime), TypeMapper.GetClrType(SqlDbType.Date)); Assert.Equal(typeof(DateTime), TypeMapper.GetClrType(SqlDbType.DateTime2)); Assert.Equal(typeof(DateTimeOffset), TypeMapper.GetClrType(SqlDbType.DateTimeOffset)); Assert.Equal(typeof(TimeSpan), TypeMapper.GetClrType(SqlDbType.Time)); Assert.Equal(typeof(Guid), TypeMapper.GetClrType(SqlDbType.UniqueIdentifier)); Assert.Equal(typeof(Object), TypeMapper.GetClrType(SqlDbType.Variant)); Assert.Equal(typeof(Object), TypeMapper.GetClrType(SqlDbType.Udt)); Assert.Equal(typeof(DataTable), TypeMapper.GetClrType(SqlDbType.Structured)); } [Fact] public void GetSqlDbTypeFromStringTest() { Assert.Equal(SqlDbType.BigInt, TypeMapper.GetSqlDbTypeFromString("BigInt")); Assert.Equal(SqlDbType.Int, TypeMapper.GetSqlDbTypeFromString("Int")); Assert.Equal(SqlDbType.SmallInt, TypeMapper.GetSqlDbTypeFromString("SmallInt")); Assert.Equal(SqlDbType.Decimal, TypeMapper.GetSqlDbTypeFromString("Decimal")); Assert.Equal(SqlDbType.Float, TypeMapper.GetSqlDbTypeFromString("Float")); Assert.Equal(SqlDbType.Real, TypeMapper.GetSqlDbTypeFromString("Real")); Assert.Equal(SqlDbType.TinyInt, TypeMapper.GetSqlDbTypeFromString("TinyInt")); Assert.Equal(SqlDbType.VarBinary, TypeMapper.GetSqlDbTypeFromString("VarBinary")); Assert.Equal(SqlDbType.Bit, TypeMapper.GetSqlDbTypeFromString("Bit")); Assert.Equal(SqlDbType.Char, TypeMapper.GetSqlDbTypeFromString("Char")); Assert.Equal(SqlDbType.NVarChar, TypeMapper.GetSqlDbTypeFromString("NVarChar")); Assert.Equal(SqlDbType.DateTime2, TypeMapper.GetSqlDbTypeFromString("DateTime2")); Assert.Equal(SqlDbType.DateTimeOffset, TypeMapper.GetSqlDbTypeFromString("DateTimeOffset")); Assert.Equal(SqlDbType.Time, TypeMapper.GetSqlDbTypeFromString("Time")); Assert.Equal(SqlDbType.UniqueIdentifier, TypeMapper.GetSqlDbTypeFromString("UniqueIdentifier")); Assert.Equal(SqlDbType.Structured, TypeMapper.GetSqlDbTypeFromString("Structured")); } [Fact] public void IsClrTypeTest() { Assert.False(TypeMapper.IsClrType(typeof(IsClrTypeTestClass))); Assert.False(TypeMapper.IsClrType(new IsClrTypeTestClass())); Assert.True(TypeMapper.IsClrType(typeof(Enum))); Assert.True(TypeMapper.IsClrType(typeof(String))); Assert.True(TypeMapper.IsClrType(typeof(Char))); Assert.True(TypeMapper.IsClrType(typeof(Guid))); Assert.True(TypeMapper.IsClrType(typeof(Boolean))); Assert.True(TypeMapper.IsClrType(typeof(Byte))); Assert.True(TypeMapper.IsClrType(typeof(Int16))); Assert.True(TypeMapper.IsClrType(typeof(Int32))); Assert.True(TypeMapper.IsClrType(typeof(Int64))); Assert.True(TypeMapper.IsClrType(typeof(Single))); Assert.True(TypeMapper.IsClrType(typeof(Double))); Assert.True(TypeMapper.IsClrType(typeof(Decimal))); Assert.True(TypeMapper.IsClrType(typeof(SByte))); Assert.True(TypeMapper.IsClrType(typeof(UInt16))); Assert.True(TypeMapper.IsClrType(typeof(UInt32))); Assert.True(TypeMapper.IsClrType(typeof(UInt64))); Assert.True(TypeMapper.IsClrType(typeof(DateTime))); Assert.True(TypeMapper.IsClrType(typeof(DateTimeOffset))); Assert.True(TypeMapper.IsClrType(typeof(TimeSpan))); Assert.True(TypeMapper.IsClrType(typeof(System.Char?))); Assert.True(TypeMapper.IsClrType(typeof(System.Guid?))); Assert.True(TypeMapper.IsClrType(typeof(System.Boolean?))); Assert.True(TypeMapper.IsClrType(typeof(System.Byte?))); Assert.True(TypeMapper.IsClrType(typeof(System.Int16?))); Assert.True(TypeMapper.IsClrType(typeof(System.Int32?))); Assert.True(TypeMapper.IsClrType(typeof(System.Int64?))); Assert.True(TypeMapper.IsClrType(typeof(System.Single?))); Assert.True(TypeMapper.IsClrType(typeof(System.Double?))); Assert.True(TypeMapper.IsClrType(typeof(System.Decimal?))); Assert.True(TypeMapper.IsClrType(typeof(System.SByte?))); Assert.True(TypeMapper.IsClrType(typeof(System.UInt16?))); Assert.True(TypeMapper.IsClrType(typeof(System.UInt32?))); Assert.True(TypeMapper.IsClrType(typeof(System.UInt64?))); Assert.True(TypeMapper.IsClrType(typeof(System.DateTime?))); Assert.True(TypeMapper.IsClrType(typeof(System.DateTimeOffset?))); Assert.True(TypeMapper.IsClrType(typeof(System.TimeSpan?))); } [Fact] public void IsNullableTest() { Assert.True(TypeMapper.IsNullable(typeof(int?))); int? x = null; Assert.True(TypeMapper.IsNullable(x)); int? y = 1; Assert.True(TypeMapper.IsNullable(y)); } [Fact] public void IsEntityTest() { Assert.True(TypeMapper.IsEntity(typeof(Models.User))); Assert.False(TypeMapper.IsEntity(typeof(IsClrTypeTestClass))); } [Fact] public void IsListTest() { var names = new List<string>{ "Bob", "Fred" }; Assert.True(TypeMapper.IsList(names.GetType())); Assert.True(TypeMapper.IsList(names)); Assert.False(TypeMapper.IsList(typeof(string))); } [Fact] public void IsListOfEntities() { var names = new List<string>{ "Bob", "Fred" }; var users = new List<UserTestClass> { new UserTestClass { Name = "Bob"}, new UserTestClass { Name = "Fred"} }; Assert.False(TypeMapper.IsListOfEntities(names.GetType())); Assert.False(TypeMapper.IsListOfEntities(names)); Assert.True(TypeMapper.IsListOfEntities(users.GetType())); Assert.True(TypeMapper.IsListOfEntities(users)); Assert.True(TypeMapper.IsListOfEntities(users.GetType(), typeof(UserTestClass))); Assert.True(TypeMapper.IsListOfEntities(users, typeof(UserTestClass))); Assert.False(TypeMapper.IsListOfEntities(users, typeof(IsClrTypeTestClass))); } } }
/* * Copyright 2012-2014 Jeremy Feinstein * Copyright 2013-2014 Tomasz Cielecki * * 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 Android.Content; using Android.Graphics; using Android.OS; using Android.Support.V4.View; using Android.Util; using Android.Views; using Android.Views.Animations; using Android.Widget; namespace SlidingMenuSharp { public delegate void PageSelectedEventHandler(object sender, PageSelectedEventArgs e); public delegate void PageScrolledEventHandler(object sender, PageScrolledEventArgs e); public delegate void PageScrollStateChangedEventHandler(object sender, PageScrollStateChangedEventArgs e); public class CustomViewAbove : ViewGroup { private new const string Tag = "CustomViewAbove"; private const bool UseCache = false; private const int MaxSettleDuration = 600; // ms private const int MinDistanceForFling = 25; // dips private readonly IInterpolator _interpolator = new CVAInterpolator(); private class CVAInterpolator : Java.Lang.Object, IInterpolator { public float GetInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } } private View _content; private int _curItem; private Scroller _scroller; private bool _scrollingCacheEnabled; private bool _scrolling; private bool _isBeingDragged; private bool _isUnableToDrag; private int _touchSlop; private float _initialMotionX; /** * Position of the last motion event. */ private float _lastMotionX; private float _lastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ protected int ActivePointerId = InvalidPointer; /** * Sentinel value for no current active pointer. * Used by {@link #ActivePointerId}. */ private const int InvalidPointer = -1; /** * Determines speed during touch scrolling */ protected VelocityTracker VelocityTracker; private int _minimumVelocity; protected int MaximumVelocity; private int _flingDistance; private CustomViewBehind _viewBehind; // private int mMode; private bool _enabled = true; private readonly IList<View> _ignoredViews = new List<View>(); private bool _quickReturn; private float _scrollX; public PageSelectedEventHandler PageSelected; public PageScrolledEventHandler PageScrolled; public PageScrollStateChangedEventHandler PageScrollState; public EventHandler Closed; public EventHandler Opened; public CustomViewAbove(Context context) : this(context, null) { } public CustomViewAbove(Context context, IAttributeSet attrs) : base(context, attrs) { InitCustomViewAbove(); } void InitCustomViewAbove() { TouchMode = TouchMode.Margin; SetWillNotDraw(false); DescendantFocusability = DescendantFocusability.AfterDescendants; Focusable = true; _scroller = new Scroller(Context, _interpolator); var configuration = ViewConfiguration.Get(Context); _touchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration); _minimumVelocity = configuration.ScaledMinimumFlingVelocity; MaximumVelocity = configuration.ScaledMaximumFlingVelocity; var density = Context.Resources.DisplayMetrics.Density; _flingDistance = (int) (MinDistanceForFling*density); PageSelected += (sender, args) => { if (_viewBehind == null) return; switch (args.Position) { case 0: case 2: _viewBehind.ChildrenEnabled = true; break; case 1: _viewBehind.ChildrenEnabled = false; break; } }; } public void SetCurrentItem(int item) { SetCurrentItemInternal(item, true, false); } public void SetCurrentItem(int item, bool smoothScroll) { SetCurrentItemInternal(item, smoothScroll, false); } public int GetCurrentItem() { return _curItem; } void SetCurrentItemInternal(int item, bool smoothScroll, bool always, int velocity = 0) { if (!always && _curItem == item) { ScrollingCacheEnabled = false; return; } item = _viewBehind.GetMenuPage(item); var dispatchSelected = _curItem != item; _curItem = item; var destX = GetDestScrollX(_curItem); if (dispatchSelected && PageSelected != null) { PageSelected(this, new PageSelectedEventArgs { Position = item }); } if (smoothScroll) { SmoothScrollTo(destX, 0, velocity); } else { CompleteScroll(); ScrollTo(destX, 0); } } public void AddIgnoredView(View v) { if (!_ignoredViews.Contains(v)) _ignoredViews.Add(v); } public void RemoveIgnoredView(View v) { _ignoredViews.Remove(v); } public void ClearIgnoredViews() { _ignoredViews.Clear(); } static float DistanceInfluenceForSnapDuration(float f) { f -= 0.5f; f *= 0.3f*(float)Math.PI/2.0f; return FloatMath.Sin(f); } public int GetDestScrollX(int page) { switch (page) { case 0: case 2: return _viewBehind.GetMenuLeft(_content, page); case 1: return _content.Left; } return 0; } private int LeftBound { get { return _viewBehind.GetAbsLeftBound(_content); } } private int RightBound { get { return _viewBehind.GetAbsRightBound(_content); } } public int ContentLeft { get { return _content.Left + _content.PaddingLeft; } } public bool IsMenuOpen { get { return _curItem == 0 || _curItem == 2; } } private bool IsInIgnoredView(MotionEvent ev) { var rect = new Rect(); foreach (var v in _ignoredViews) { v.GetHitRect(rect); if (rect.Contains((int) ev.GetX(), (int) ev.GetY())) return true; } return false; } public int BehindWidth { get { return _viewBehind == null ? 0 : _viewBehind.BehindWidth; } } public int GetChildWidth(int i) { switch (i) { case 0: return BehindWidth; case 1: return _content.Width; default: return 0; } } public bool IsSlidingEnabled { get { return _enabled; } set { _enabled = value; } } void SmoothScrollTo(int x, int y, int velocity = 0) { if (ChildCount == 0) { ScrollingCacheEnabled = false; return; } var sx = ScrollX; var sy = ScrollY; var dx = x - sx; var dy = y - sy; if (dx == 0 && dy == 0) { CompleteScroll(); if (IsMenuOpen) { if (null != Opened) Opened(this, EventArgs.Empty); } else { if (null != Closed) Closed(this, EventArgs.Empty); } return; } ScrollingCacheEnabled = true; _scrolling = true; var width = BehindWidth; var halfWidth = width / 2; var distanceRatio = Math.Min(1f, 1.0f * Math.Abs(dx) / width); var distance = halfWidth + halfWidth * DistanceInfluenceForSnapDuration(distanceRatio); int duration; velocity = Math.Abs(velocity); if (velocity > 0) duration = (int)(4 * Math.Round(1000 * Math.Abs(distance / velocity))); else { var pageDelta = (float) Math.Abs(dx) / width; duration = (int) ((pageDelta + 1) * 100); } duration = Math.Min(duration, MaxSettleDuration); _scroller.StartScroll(sx, sy, dx, dy, duration); Invalidate(); } public View Content { get { return _content; } set { if (_content != null) RemoveView(_content); _content = value; AddView(_content); } } public CustomViewBehind CustomViewBehind { set { _viewBehind = value; } } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { var width = GetDefaultSize(0, widthMeasureSpec); var height = GetDefaultSize(0, heightMeasureSpec); SetMeasuredDimension(width, height); var contentWidth = GetChildMeasureSpec(widthMeasureSpec, 0, width); var contentHeight = GetChildMeasureSpec(heightMeasureSpec, 0, height); _content.Measure(contentWidth, contentHeight); } protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { base.OnSizeChanged(w, h, oldw, oldh); if (w == oldw) return; CompleteScroll(); ScrollTo(GetDestScrollX(_curItem), ScrollY); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { var width = r - l; var height = b - t; _content.Layout(0, 0, width, height); } public int AboveOffset { set { _content.SetPadding(value, _content.PaddingTop, _content.PaddingRight, _content.PaddingBottom); } } public override void ComputeScroll() { if (!_scroller.IsFinished) { if (_scroller.ComputeScrollOffset()) { var oldX = ScrollX; var oldY = ScrollY; var x = _scroller.CurrX; var y = _scroller.CurrY; if (oldX != x ||oldY != y) { ScrollTo(x, y); OnPageScrolled(x); } Invalidate(); return; } } CompleteScroll(); } protected void OnPageScrolled(int xpos) { var widthWithMargin = Width; var position = xpos / widthWithMargin; var offsetPixels = xpos % widthWithMargin; var offset = (float)offsetPixels / widthWithMargin; if (null != PageScrolled) PageScrolled(this, new PageScrolledEventArgs { Position = position, PositionOffset = offset, PositionOffsetPixels = offsetPixels }); } private void CompleteScroll() { var needPopulate = _scrolling; if (needPopulate) { ScrollingCacheEnabled = false; _scroller.AbortAnimation(); var oldX = ScrollX; var oldY = ScrollY; var x = _scroller.CurrX; var y = _scroller.CurrY; if (oldX != x || oldY != y) ScrollTo(x, y); if (IsMenuOpen) { if (null != Opened) Opened(this, EventArgs.Empty); } else { if (null != Closed) Closed(this, EventArgs.Empty); } } _scrolling = false; } public TouchMode TouchMode { get; set; } private bool ThisTouchAllowed(MotionEvent ev) { var x = (int) (ev.GetX() + _scrollX); if (IsMenuOpen) { return _viewBehind.MenuOpenTouchAllowed(_content, _curItem, x); } switch (TouchMode) { case TouchMode.Fullscreen: return !IsInIgnoredView(ev); case TouchMode.None: return false; case TouchMode.Margin: return _viewBehind.MarginTouchAllowed(_content, x); } return false; } private bool ThisSlideAllowed(float dx) { var allowed = IsMenuOpen ? _viewBehind.MenuOpenSlideAllowed(dx) : _viewBehind.MenuClosedSlideAllowed(dx); #if DEBUG Log.Verbose(Tag, "this slide allowed" + allowed + " dx: " + dx); #endif return allowed; } private int GetPointerIndex(MotionEvent ev, int id) { var activePointerIndex = MotionEventCompat.FindPointerIndex(ev, id); if (activePointerIndex == -1) ActivePointerId = InvalidPointer; return activePointerIndex; } public override bool OnInterceptTouchEvent(MotionEvent ev) { if (!_enabled) return false; var action = (int) ev.Action & MotionEventCompat.ActionMask; #if DEBUG if (action == (int) MotionEventActions.Down) Log.Verbose(Tag, "Recieved ACTION_DOWN"); #endif if (action == (int) MotionEventActions.Cancel || action == (int) MotionEventActions.Up || (action != (int) MotionEventActions.Down && _isUnableToDrag)) { EndDrag(); return false; } switch (action) { case (int) MotionEventActions.Move: DetermineDrag(ev); break; case (int) MotionEventActions.Down: var index = MotionEventCompat.GetActionIndex(ev); ActivePointerId = MotionEventCompat.GetPointerId(ev, index); if (ActivePointerId == InvalidPointer) break; _lastMotionX = _initialMotionX = MotionEventCompat.GetX(ev, index); _lastMotionY = MotionEventCompat.GetY(ev, index); if (ThisTouchAllowed(ev)) { _isBeingDragged = false; _isUnableToDrag = false; if (IsMenuOpen && _viewBehind.MenuTouchInQuickReturn(_content, _curItem, ev.GetX() + _scrollX)) _quickReturn = true; } else _isUnableToDrag = true; break; case (int) MotionEventActions.PointerUp: OnSecondaryPointerUp(ev); break; } if (!_isBeingDragged) { if (VelocityTracker == null) VelocityTracker = VelocityTracker.Obtain(); VelocityTracker.AddMovement(ev); } return _isBeingDragged || _quickReturn; } public override bool OnTouchEvent(MotionEvent ev) { if (!_enabled) return false; if (!_isBeingDragged && !ThisTouchAllowed(ev)) return false; if (VelocityTracker == null) VelocityTracker = VelocityTracker.Obtain(); VelocityTracker.AddMovement(ev); var action = (int)ev.Action & MotionEventCompat.ActionMask; switch (action) { case (int) MotionEventActions.Down: CompleteScroll(); var index = MotionEventCompat.GetActionIndex(ev); ActivePointerId = MotionEventCompat.GetPointerId(ev, index); _lastMotionX = _initialMotionX = ev.GetX(); break; case (int) MotionEventActions.Move: if (!_isBeingDragged) { DetermineDrag(ev); if (_isUnableToDrag) return false; } if (_isBeingDragged) { var activePointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId == InvalidPointer) break; var x = MotionEventCompat.GetX(ev, activePointerIndex); var deltaX = _lastMotionX - x; _lastMotionX = x; var oldScrollX = ScrollX; var scrollX = oldScrollX + deltaX; var leftBound = LeftBound; var rightBound = RightBound; if (scrollX < leftBound) scrollX = leftBound; else if (scrollX > rightBound) scrollX = rightBound; _lastMotionX += scrollX - (int) scrollX; ScrollTo((int) scrollX, ScrollY); OnPageScrolled((int)scrollX); } break; case (int) MotionEventActions.Up: if (_isBeingDragged) { var velocityTracker = VelocityTracker; velocityTracker.ComputeCurrentVelocity(1000, MaximumVelocity); var initialVelocity = (int) VelocityTrackerCompat.GetXVelocity(velocityTracker, ActivePointerId); var scrollX = ScrollX; var pageOffset = (float) (scrollX - GetDestScrollX(_curItem)) / BehindWidth; var activePointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId != InvalidPointer) { var x = MotionEventCompat.GetX(ev, activePointerIndex); var totalDelta = (int) (x - _initialMotionX); var nextPage = DetermineTargetPage(pageOffset, initialVelocity, totalDelta); SetCurrentItemInternal(nextPage, true, true, initialVelocity); } else SetCurrentItemInternal(_curItem, true, true, initialVelocity); ActivePointerId = InvalidPointer; EndDrag(); } else if (_quickReturn && _viewBehind.MenuTouchInQuickReturn(_content, _curItem, ev.GetX() + _scrollX)) { SetCurrentItem(1); EndDrag(); } break; case (int) MotionEventActions.Cancel: if (_isBeingDragged) { SetCurrentItemInternal(_curItem, true, true); ActivePointerId = InvalidPointer; EndDrag(); } break; case MotionEventCompat.ActionPointerDown: var indexx = MotionEventCompat.GetActionIndex(ev); _lastMotionX = MotionEventCompat.GetX(ev, indexx); ActivePointerId = MotionEventCompat.GetPointerId(ev, indexx); break; case MotionEventCompat.ActionPointerUp: OnSecondaryPointerUp(ev); var pointerIndex = GetPointerIndex(ev, ActivePointerId); if (ActivePointerId == InvalidPointer) break; _lastMotionX = MotionEventCompat.GetX(ev, pointerIndex); break; } return true; } private void DetermineDrag(MotionEvent ev) { var activePointerId = ActivePointerId; var pointerIndex = GetPointerIndex(ev, activePointerId); if (activePointerId == InvalidPointer || pointerIndex == InvalidPointer) return; var x = MotionEventCompat.GetX(ev, pointerIndex); var dx = x - _lastMotionX; var xDiff = Math.Abs(dx); var y = MotionEventCompat.GetY(ev, pointerIndex); var dy = y - _lastMotionY; var yDiff = Math.Abs(dy); if (xDiff > (IsMenuOpen ? _touchSlop / 2 : _touchSlop) && xDiff > yDiff && ThisSlideAllowed(dx)) { StartDrag(); _lastMotionX = x; _lastMotionY = y; _scrollingCacheEnabled = true; } else if (xDiff > _touchSlop) _isUnableToDrag = true; } public override void ScrollTo(int x, int y) { base.ScrollTo(x, y); _scrollX = x; _viewBehind.ScrollBehindTo(_content, x, y); #if __ANDROID_11__ ((SlidingMenu) Parent).ManageLayers(PercentOpen); #endif } private int DetermineTargetPage(float pageOffset, int velocity, int deltaX) { var targetPage = _curItem; if (Math.Abs(deltaX) > _flingDistance && Math.Abs(velocity) > _minimumVelocity) { if (velocity > 0 && deltaX > 0) targetPage -= 1; else if (velocity < 0 && deltaX < 0) targetPage += 1; } else targetPage = (int) Math.Round(_curItem + pageOffset); return targetPage; } public float PercentOpen { get { return Math.Abs(_scrollX - _content.Left) / BehindWidth; } } protected override void DispatchDraw(Canvas canvas) { base.DispatchDraw(canvas); _viewBehind.DrawShadow(_content, canvas); _viewBehind.DrawFade(_content, canvas, PercentOpen); _viewBehind.DrawSelector(_content, canvas, PercentOpen); } private void OnSecondaryPointerUp(MotionEvent ev) { #if DEBUG Log.Verbose(Tag, "OnSecondaryPointerUp called"); #endif var pointerIndex = MotionEventCompat.GetActionIndex(ev); var pointerId = MotionEventCompat.GetPointerId(ev, pointerIndex); if (pointerId == ActivePointerId) { var newPointerIndex = pointerIndex == 0 ? 1 : 0; _lastMotionX = MotionEventCompat.GetX(ev, newPointerIndex); ActivePointerId = MotionEventCompat.GetPointerId(ev, newPointerIndex); if (VelocityTracker != null) VelocityTracker.Clear(); } } private void StartDrag() { _isBeingDragged = true; _quickReturn = false; } private void EndDrag() { _quickReturn = false; _isBeingDragged = false; _isUnableToDrag = false; ActivePointerId = InvalidPointer; if (VelocityTracker == null) return; VelocityTracker.Recycle(); VelocityTracker = null; } private bool ScrollingCacheEnabled { set { if (_scrollingCacheEnabled != value) { _scrollingCacheEnabled = value; if (UseCache) { var size = ChildCount; for (var i = 0; i < size; ++i) { var child = GetChildAt(i); if (child.Visibility != ViewStates.Gone) child.DrawingCacheEnabled = value; } } } } } protected bool CanScroll(View v, bool checkV, int dx, int x, int y) { var viewGroup = v as ViewGroup; if (viewGroup != null) { var scrollX = v.ScrollX; var scrollY = v.ScrollY; var count = viewGroup.ChildCount; for (var i = count - 1; i >= 0; i--) { var child = viewGroup.GetChildAt(i); if (x + scrollX >= child.Left && x + scrollX < child.Right && y + scrollY >= child.Top && y + scrollY < child.Bottom && CanScroll(child, true, dx, x + scrollX - child.Left, y + scrollY - child.Top)) return true; } } return checkV && ViewCompat.CanScrollHorizontally(v, -dx); } public override bool DispatchKeyEvent(KeyEvent e) { return base.DispatchKeyEvent(e) || ExecuteKeyEvent(e); } public bool ExecuteKeyEvent(KeyEvent ev) { var handled = false; if (ev.Action == KeyEventActions.Down) { switch (ev.KeyCode) { case Keycode.DpadLeft: handled = ArrowScroll(FocusSearchDirection.Left); break; case Keycode.DpadRight: handled = ArrowScroll(FocusSearchDirection.Right); break; case Keycode.Tab: if ((int)Build.VERSION.SdkInt >= 11) { if (KeyEventCompat.HasNoModifiers(ev)) handled = ArrowScroll(FocusSearchDirection.Forward); #if __ANDROID_11__ else if (ev.IsMetaPressed) handled = ArrowScroll(FocusSearchDirection.Backward); #endif } break; } } return handled; } public bool ArrowScroll(FocusSearchDirection direction) { var currentFocused = FindFocus(); var handled = false; var nextFocused = FocusFinder.Instance.FindNextFocus(this, currentFocused == this ? null : currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == FocusSearchDirection.Left) handled = nextFocused.RequestFocus(); else if (direction == FocusSearchDirection.Right) { if (currentFocused != null && nextFocused.Left <= currentFocused.Left) handled = PageRight(); else handled = nextFocused.RequestFocus(); } } else if (direction == FocusSearchDirection.Left || direction == FocusSearchDirection.Backward) handled = PageLeft(); else if (direction == FocusSearchDirection.Right || direction == FocusSearchDirection.Forward) handled = PageRight(); if (handled) PlaySoundEffect(SoundEffectConstants.GetContantForFocusDirection(direction)); return handled; } bool PageLeft() { if (_curItem > 0) { SetCurrentItem(_curItem-1, true); return true; } return false; } bool PageRight() { if (_curItem < 1) { SetCurrentItem(_curItem+1, true); return true; } return false; } } }
/* Copyright (C) 2005 Dominic Thuillier This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ using System; using QuantLib; namespace BermudanSwaption { class Run { private const int numRows = 5; private const int numCols = 5; private static int[] swapLenghts = { 1, 2, 3, 4, 5 }; private static double[] swaptionVols = { 0.1490, 0.1340, 0.1228, 0.1189, 0.1148, 0.1290, 0.1201, 0.1146, 0.1108, 0.1040, 0.1149, 0.1112, 0.1070, 0.1010, 0.0957, 0.1047, 0.1021, 0.0980, 0.0951, 0.1270, 0.1000, 0.0950, 0.0900, 0.1230, 0.1160 }; private static void calibrateModel( ShortRateModel model, CalibrationHelperVector helpers, double lambda ) { Simplex om = new Simplex( lambda ); model.calibrate(helpers, om, new EndCriteria(1000, 250, 1e-7, 1e-7, 1e-7)); // Output the implied Black volatilities for (int i=0; i<numRows; i++) { int j = numCols - i -1; // 1x5, 2x4, 3x3, 4x2, 5x1 int k = i*numCols + j; double npv = helpers[i].modelValue(); double implied = helpers[i].impliedVolatility( npv, 1e-4, 1000, 0.05, 0.50 ); double diff = implied - swaptionVols[k]; Console.WriteLine( "{0}x{1}: model {2}, market {3} ({4})", i+1, swapLenghts[j], implied, swaptionVols[k], diff ); } } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { DateTime startTime = DateTime.Now; Date todaysDate = new Date(15, Month.February, 2002); Calendar calendar = new TARGET(); Date settlementDate = new Date(19, Month.February, 2002); Settings.instance().setEvaluationDate( todaysDate ); // flat yield term structure impling 1x5 swap at 5% Quote flatRate = new SimpleQuote(0.04875825); FlatForward myTermStructure = new FlatForward( settlementDate, new QuoteHandle( flatRate ), new Actual365Fixed() ); RelinkableYieldTermStructureHandle rhTermStructure = new RelinkableYieldTermStructureHandle(); rhTermStructure.linkTo( myTermStructure ); // Define the ATM/OTM/ITM swaps Period fixedLegTenor = new Period(1,TimeUnit.Years); BusinessDayConvention fixedLegConvention = BusinessDayConvention.Unadjusted; BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing; DayCounter fixedLegDayCounter = new Thirty360( Thirty360.Convention.European ); Period floatingLegTenor = new Period(6,TimeUnit.Months); double dummyFixedRate = 0.03; IborIndex indexSixMonths = new Euribor6M( rhTermStructure ); Date startDate = calendar.advance(settlementDate,1,TimeUnit.Years, floatingLegConvention); Date maturity = calendar.advance(startDate,5,TimeUnit.Years, floatingLegConvention); Schedule fixedSchedule = new Schedule(startDate,maturity, fixedLegTenor,calendar,fixedLegConvention,fixedLegConvention, DateGeneration.Rule.Forward,false); Schedule floatSchedule = new Schedule(startDate,maturity, floatingLegTenor,calendar,floatingLegConvention, floatingLegConvention,DateGeneration.Rule.Forward,false); VanillaSwap swap = new VanillaSwap( VanillaSwap.Payer, 1000.0, fixedSchedule, dummyFixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); DiscountingSwapEngine swapEngine = new DiscountingSwapEngine(rhTermStructure); swap.setPricingEngine(swapEngine); double fixedATMRate = swap.fairRate(); double fixedOTMRate = fixedATMRate * 1.2; double fixedITMRate = fixedATMRate * 0.8; VanillaSwap atmSwap = new VanillaSwap( VanillaSwap.Payer, 1000.0, fixedSchedule, fixedATMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter() ); VanillaSwap otmSwap = new VanillaSwap( VanillaSwap.Payer, 1000.0, fixedSchedule, fixedOTMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); VanillaSwap itmSwap = new VanillaSwap( VanillaSwap.Payer, 1000.0, fixedSchedule, fixedITMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); atmSwap.setPricingEngine(swapEngine); otmSwap.setPricingEngine(swapEngine); itmSwap.setPricingEngine(swapEngine); // defining the swaptions to be used in model calibration PeriodVector swaptionMaturities = new PeriodVector(); swaptionMaturities.Add( new Period(1, TimeUnit.Years) ); swaptionMaturities.Add( new Period(2, TimeUnit.Years) ); swaptionMaturities.Add( new Period(3, TimeUnit.Years) ); swaptionMaturities.Add( new Period(4, TimeUnit.Years) ); swaptionMaturities.Add( new Period(5, TimeUnit.Years) ); CalibrationHelperVector swaptions = new CalibrationHelperVector(); // List of times that have to be included in the timegrid DoubleVector times = new DoubleVector(); for ( int i=0; i<numRows; i++) { int j = numCols - i -1; // 1x5, 2x4, 3x3, 4x2, 5x1 int k = i*numCols + j; Quote vol = new SimpleQuote( swaptionVols[k] ); SwaptionHelper helper = new SwaptionHelper( swaptionMaturities[i], new Period(swapLenghts[j], TimeUnit.Years), new QuoteHandle(vol), indexSixMonths, indexSixMonths.tenor(), indexSixMonths.dayCounter(), indexSixMonths.dayCounter(), rhTermStructure ); swaptions.Add( helper ); times.AddRange( helper.times() ); } // Building time-grid TimeGrid grid = new TimeGrid( times, 30); // defining the models // G2 modelG2 = new G2(rhTermStructure)); HullWhite modelHW = new HullWhite( rhTermStructure ); HullWhite modelHW2 = new HullWhite( rhTermStructure ); BlackKarasinski modelBK = new BlackKarasinski( rhTermStructure ); // model calibrations // Console.WriteLine( "G2 (analytic formulae) calibration" ); // for (int i=0; i<swaptions.Count; i++) // swaptions[i].setPricingEngine( new G2SwaptionEngine( modelG2, 6.0, 16 ) ); // // calibrateModel( modelG2, swaptions, 0.05); // Console.WriteLine( "calibrated to:" ); // Console.WriteLine( "a = " + modelG2.parameters()[0] ); // Console.WriteLine( "sigma = " + modelG2.parameters()[1] ); // Console.WriteLine( "b = " + modelG2.parameters()[2] ); // Console.WriteLine( "eta = " + modelG2.parameters()[3] ); // Console.WriteLine( "rho = " + modelG2.parameters()[4] ); Console.WriteLine( "Hull-White (analytic formulae) calibration" ); for (int i=0; i<swaptions.Count; i++) swaptions[i].setPricingEngine( new JamshidianSwaptionEngine(modelHW)); calibrateModel( modelHW, swaptions, 0.05); // Console.WriteLine( "calibrated to:" ); // Console.WriteLine( "a = " + modelHW.parameters()[0] ); // Console.WriteLine( "sigma = " + modelHW.parameters()[1] ); Console.WriteLine( "Hull-White (numerical) calibration" ); for (int i=0; i<swaptions.Count; i++) swaptions[i].setPricingEngine( new TreeSwaptionEngine(modelHW2,grid)); calibrateModel(modelHW2, swaptions, 0.05); // std::cout << "calibrated to:\n" // << "a = " << modelHW2->params()[0] << ", " // << "sigma = " << modelHW2->params()[1] // << std::endl << std::endl; Console.WriteLine( "Black-Karasinski (numerical) calibration" ); for (int i=0; i<swaptions.Count; i++) swaptions[i].setPricingEngine( new TreeSwaptionEngine(modelBK,grid)); calibrateModel(modelBK, swaptions, 0.05); // std::cout << "calibrated to:\n" // << "a = " << modelBK->params()[0] << ", " // << "sigma = " << modelBK->params()[1] // << std::endl << std::endl; // ATM Bermudan swaption pricing Console.WriteLine( "Payer bermudan swaption struck at {0} (ATM)", fixedATMRate ); DateVector bermudanDates = new DateVector(); Schedule schedule = new Schedule(startDate,maturity, new Period(3,TimeUnit.Months),calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward,false); for (uint i=0; i<schedule.size(); i++) bermudanDates.Add( schedule.date( i ) ); Exercise bermudaExercise = new BermudanExercise( bermudanDates ); Swaption bermudanSwaption = new Swaption( atmSwap, bermudaExercise); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelHW, 50)); Console.WriteLine( "HW: " + bermudanSwaption.NPV() ); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelHW2, 50)); Console.WriteLine( "HW (num): " + bermudanSwaption.NPV() ); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelBK, 50)); Console.WriteLine( "BK (num): " + bermudanSwaption.NPV() ); DateTime endTime = DateTime.Now; TimeSpan delta = endTime - startTime; Console.WriteLine(); Console.WriteLine("Run completed in {0} s", delta.TotalSeconds); Console.WriteLine(); } } }
// 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 ShiftRightLogicalUInt6464() { var test = new ImmUnaryOpTest__ShiftRightLogicalUInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalUInt6464 { private struct TestStruct { public Vector256<UInt64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt6464 testClass) { var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector256<UInt64> _clsVar; private Vector256<UInt64> _fld; private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalUInt6464() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public ImmUnaryOpTest__ShiftRightLogicalUInt6464() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalUInt6464(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt64>(Vector256<UInt64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Static; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static partial class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** Indicates examples tests. */ public const string CategoryExamples = "EXAMPLES_TEST"; /** */ private const int DfltBusywaitSleepInterval = 200; /** Work dir. */ private static readonly string WorkDir = // ReSharper disable once AssignNullToNotNullAttribute Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ignite_work"); /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms64m", "-Xmx99m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", "-DIGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP=false" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions(bool? jvmDebug = null) { IList<string> ops = new List<string>(TestJvmOpts); if (jvmDebug ?? JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000) { int left = timeout; while (true) { if (grid.GetCluster().GetNodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } /// <summary> /// Gets the static discovery. /// </summary> public static TcpDiscoverySpi GetStaticDiscovery() { return new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }; } /// <summary> /// Gets the primary keys. /// </summary> public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName, IClusterNode node = null) { var aff = ignite.GetAffinity(cacheName); node = node ?? ignite.GetCluster().GetLocalNode(); return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x)); } /// <summary> /// Gets the primary key. /// </summary> public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null) { return GetPrimaryKeys(ignite, cacheName, node).First(); } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, 0, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, expectedCount, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout) { var handleRegistry = ((Ignite)grid).HandleRegistry; expectedCount++; // Skip default lifecycle bean if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout)) return; var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList(); if (items.Any()) { Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'", grid.Name, expectedCount, handleRegistry.Count, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } } /// <summary> /// Serializes and deserializes back an object. /// </summary> public static T SerializeDeserialize<T>(T obj, bool raw = false) { var cfg = new BinaryConfiguration { Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null }; var marsh = new Marshaller(cfg) { CompactFooter = false }; return marsh.Unmarshal<T>(marsh.Marshal(obj)); } /// <summary> /// Clears the work dir. /// </summary> public static void ClearWorkDir() { if (!Directory.Exists(WorkDir)) { return; } // Delete everything we can. Some files may be locked. foreach (var e in Directory.GetFileSystemEntries(WorkDir, "*", SearchOption.AllDirectories)) { try { File.Delete(e); } catch (Exception) { // Ignore } try { Directory.Delete(e, true); } catch (Exception) { // Ignore } } } /// <summary> /// Gets the dot net source dir. /// </summary> public static DirectoryInfo GetDotNetSourceDir() { // ReSharper disable once AssignNullToNotNullAttribute var dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); while (dir != null) { if (dir.GetFiles().Any(x => x.Name == "Apache.Ignite.sln")) return dir; dir = dir.Parent; } throw new InvalidOperationException("Could not resolve Ignite.NET source directory."); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ServiceStack.Common; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using ServiceStack.WebHost.Endpoints.Extensions; namespace ServiceStack.ServiceHost { public class ServiceMetadata { public ServiceMetadata() { this.RequestTypes = new HashSet<Type>(); this.ServiceTypes = new HashSet<Type>(); this.ResponseTypes = new HashSet<Type>(); this.OperationsMap = new Dictionary<Type, Operation>(); this.OperationsResponseMap = new Dictionary<Type, Operation>(); this.OperationNamesMap = new Dictionary<string, Operation>(); this.Routes = new ServiceRoutes(); } public Dictionary<Type, Operation> OperationsMap { get; protected set; } public Dictionary<Type, Operation> OperationsResponseMap { get; protected set; } public Dictionary<string, Operation> OperationNamesMap { get; protected set; } public HashSet<Type> RequestTypes { get; protected set; } public HashSet<Type> ServiceTypes { get; protected set; } public HashSet<Type> ResponseTypes { get; protected set; } public ServiceRoutes Routes { get; set; } public IEnumerable<Operation> Operations { get { return OperationsMap.Values; } } public void Add(Type serviceType, Type requestType, Type responseType) { this.ServiceTypes.Add(serviceType); this.RequestTypes.Add(requestType); var restrictTo = requestType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault() ?? serviceType.GetCustomAttributes(true) .OfType<RestrictAttribute>().FirstOrDefault(); var operation = new Operation { ServiceType = serviceType, RequestType = requestType, ResponseType = responseType, RestrictTo = restrictTo, Actions = GetImplementedActions(serviceType, requestType), Routes = new List<RestPath>(), }; this.OperationsMap[requestType] = operation; this.OperationNamesMap[requestType.Name.ToLower()] = operation; if (responseType != null) { this.ResponseTypes.Add(responseType); this.OperationsResponseMap[responseType] = operation; } } public void AfterInit() { foreach (var restPath in Routes.RestPaths) { Operation operation; if (!OperationsMap.TryGetValue(restPath.RequestType, out operation)) continue; operation.Routes.Add(restPath); } } public List<OperationDto> GetOperationDtos() { return OperationsMap.Values .SafeConvertAll(x => x.ToOperationDto()) .OrderBy(x => x.Name) .ToList(); } public Operation GetOperation(Type operationType) { Operation op; OperationsMap.TryGetValue(operationType, out op); return op; } public List<string> GetImplementedActions(Type serviceType, Type requestType) { if (typeof(IService).IsAssignableFrom(serviceType)) { return serviceType.GetActions() .Where(x => x.GetParameters()[0].ParameterType == requestType) .Select(x => x.Name.ToUpper()) .ToList(); } var oldApiActions = serviceType .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(x => ToNewApiAction(x.Name)) .Where(x => x != null) .ToList(); return oldApiActions; } public static string ToNewApiAction(string oldApiAction) { switch (oldApiAction) { case "Get": case "OnGet": return "GET"; case "Put": case "OnPut": return "PUT"; case "Post": case "OnPost": return "POST"; case "Delete": case "OnDelete": return "DELETE"; case "Patch": case "OnPatch": return "PATCH"; case "Execute": case "Run": return "ANY"; } return null; } public Type GetOperationType(string operationTypeName) { Operation operation; OperationNamesMap.TryGetValue(operationTypeName.ToLower(), out operation); return operation != null ? operation.RequestType : null; } public Type GetServiceTypeByRequest(Type requestType) { Operation operation; OperationsMap.TryGetValue(requestType, out operation); return operation != null ? operation.ServiceType : null; } public Type GetServiceTypeByResponse(Type responseType) { Operation operation; OperationsResponseMap.TryGetValue(responseType, out operation); return operation != null ? operation.ServiceType : null; } public Type GetResponseTypeByRequest(Type requestType) { Operation operation; OperationsMap.TryGetValue(requestType, out operation); return operation != null ? operation.ResponseType : null; } public List<Type> GetAllTypes() { var allTypes = new List<Type>(RequestTypes); foreach (var responseType in ResponseTypes) { allTypes.AddIfNotExists(responseType); } return allTypes; } public List<string> GetAllOperationNames() { return Operations.Select(x => x.RequestType.Name).OrderBy(operation => operation).ToList(); } public List<string> GetOperationNamesForMetadata(IHttpRequest httpReq) { return GetAllOperationNames(); } public List<string> GetOperationNamesForMetadata(IHttpRequest httpReq, Format format) { return GetAllOperationNames(); } public bool IsVisible(IHttpRequest httpReq, Operation operation) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; if (operation.RestrictTo == null) return true; //Less fine-grained on /metadata pages. Only check Network and Format var reqAttrs = httpReq.GetAttributes(); var showToNetwork = CanShowToNetwork(operation, reqAttrs); return showToNetwork; } public bool IsVisible(IHttpRequest httpReq, Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLowerInvariant(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; var isVisible = IsVisible(httpReq, operation); if (!isVisible) return false; if (operation.RestrictTo == null) return true; var allowsFormat = operation.RestrictTo.CanShowTo((EndpointAttributes)(long)format); return allowsFormat; } public bool CanAccess(IHttpRequest httpReq, Format format, string operationName) { var reqAttrs = httpReq.GetAttributes(); return CanAccess(reqAttrs, format, operationName); } public bool CanAccess(EndpointAttributes reqAttrs, Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; if (operation.RestrictTo == null) return true; var allow = operation.RestrictTo.HasAccessTo(reqAttrs); if (!allow) return false; var allowsFormat = operation.RestrictTo.HasAccessTo((EndpointAttributes)(long)format); return allowsFormat; } public bool CanAccess(Format format, string operationName) { if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return true; Operation operation; OperationNamesMap.TryGetValue(operationName.ToLower(), out operation); if (operation == null) return false; var canCall = HasImplementation(operation, format); if (!canCall) return false; if (operation.RestrictTo == null) return true; var allowsFormat = operation.RestrictTo.HasAccessTo((EndpointAttributes)(long)format); return allowsFormat; } public bool HasImplementation(Operation operation, Format format) { if (format == Format.Soap11 || format == Format.Soap12) { if (operation.Actions == null) return false; return operation.Actions.Contains("POST") || operation.Actions.Contains(ActionContext.AnyAction); } return true; } private static bool CanShowToNetwork(Operation operation, EndpointAttributes reqAttrs) { if (reqAttrs.IsLocalhost()) return operation.RestrictTo.CanShowTo(EndpointAttributes.Localhost) || operation.RestrictTo.CanShowTo(EndpointAttributes.LocalSubnet); return operation.RestrictTo.CanShowTo( reqAttrs.IsLocalSubnet() ? EndpointAttributes.LocalSubnet : EndpointAttributes.External); } } public class Operation { public string Name { get { return RequestType.Name; } } public Type RequestType { get; set; } public Type ServiceType { get; set; } public Type ResponseType { get; set; } public RestrictAttribute RestrictTo { get; set; } public List<string> Actions { get; set; } public List<RestPath> Routes { get; set; } public bool IsOneWay { get { return ResponseType == null; } } } public class OperationDto { public string Name { get; set; } public string ResponseName { get; set; } public string ServiceName { get; set; } public List<string> RestrictTo { get; set; } public List<string> VisibleTo { get; set; } public List<string> Actions { get; set; } public Dictionary<string, string> Routes { get; set; } } public class XsdMetadata { public ServiceMetadata Metadata { get; set; } public bool Flash { get; set; } public XsdMetadata(ServiceMetadata metadata, bool flash = false) { Metadata = metadata; Flash = flash; } public List<Type> GetAllTypes() { var allTypes = new List<Type>(Metadata.RequestTypes); allTypes.AddRange(Metadata.ResponseTypes); return allTypes; } public List<string> GetReplyOperationNames(Format format) { return Metadata.OperationsMap.Values .Where(x => EndpointHost.Config != null && EndpointHost.Config.MetadataPagesConfig.CanAccess(format, x.Name)) .Where(x => !x.IsOneWay) .Select(x => x.RequestType.Name) .ToList(); } public List<string> GetOneWayOperationNames(Format format) { return Metadata.OperationsMap.Values .Where(x => EndpointHost.Config != null && EndpointHost.Config.MetadataPagesConfig.CanAccess(format, x.Name)) .Where(x => x.IsOneWay) .Select(x => x.RequestType.Name) .ToList(); } /// <summary> /// Gets the name of the base most type in the heirachy tree with the same. /// /// We get an exception when trying to create a schema with multiple types of the same name /// like when inheriting from a DataContract with the same name. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static Type GetBaseTypeWithTheSameName(Type type) { var typesWithSameName = new Stack<Type>(); var baseType = type; do { if (baseType.Name == type.Name) typesWithSameName.Push(baseType); } while ((baseType = baseType.BaseType) != null); return typesWithSameName.Pop(); } } public static class ServiceMetadataExtensions { public static OperationDto ToOperationDto(this Operation operation) { var to = new OperationDto { Name = operation.Name, ResponseName = operation.IsOneWay ? null : operation.ResponseType.Name, ServiceName = operation.ServiceType.Name, Actions = operation.Actions, Routes = operation.Routes.ToDictionary(x => x.Path.PairWith(x.AllowedVerbs)), }; if (operation.RestrictTo != null) { to.RestrictTo = operation.RestrictTo.AccessibleToAny.ToList().ConvertAll(x => x.ToString()); to.VisibleTo = operation.RestrictTo.VisibleToAny.ToList().ConvertAll(x => x.ToString()); } return to; } public static string GetDescription(this Type operationType) { var apiAttr = operationType.GetCustomAttributes(typeof(ApiAttribute), true).OfType<ApiAttribute>().FirstOrDefault(); return apiAttr != null ? apiAttr.Description : ""; } public static List<ApiMemberAttribute> GetApiMembers(this Type operationType) { var members = operationType.GetMembers(BindingFlags.Instance | BindingFlags.Public); List<ApiMemberAttribute> attrs = new List<ApiMemberAttribute>(); foreach (var member in members) { var memattr = member.GetCustomAttributes(typeof(ApiMemberAttribute), true) .OfType<ApiMemberAttribute>() .Select(x => { x.Name = x.Name ?? member.Name; return x; }); attrs.AddRange(memattr); } return attrs; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { public override string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags) { Debug.Assert(symbol != null); if (node == null) { switch (symbol.Kind) { case SymbolKind.Field: return GetVariablePrototype((IFieldSymbol)symbol, flags); case SymbolKind.Method: return GetFunctionPrototype((IMethodSymbol)symbol, flags); case SymbolKind.Property: return GetPropertyPrototype((IPropertySymbol)symbol, flags); case SymbolKind.Event: return GetEventPrototype((IEventSymbol)symbol, flags); case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)symbol; if (namedType.TypeKind == TypeKind.Delegate) { return GetDelegatePrototype((INamedTypeSymbol)symbol, flags); } break; } Debug.Fail("Invalid symbol kind: " + symbol.Kind); throw Exceptions.ThrowEUnexpected(); } else { var methodDeclaration = node as BaseMethodDeclarationSyntax; if (methodDeclaration != null) { return GetFunctionPrototype(methodDeclaration, (IMethodSymbol)symbol, flags); } var propertyDeclaration = node as BasePropertyDeclarationSyntax; if (propertyDeclaration != null) { return GetPropertyPrototype(propertyDeclaration, (IPropertySymbol)symbol, flags); } var variableDeclarator = node as VariableDeclaratorSyntax; if (variableDeclarator != null && symbol.Kind == SymbolKind.Field) { return GetVariablePrototype(variableDeclarator, (IFieldSymbol)symbol, flags); } var enumMember = node as EnumMemberDeclarationSyntax; if (enumMember != null) { return GetVariablePrototype(enumMember, (IFieldSymbol)symbol, flags); } var delegateDeclaration = node as DelegateDeclarationSyntax; if (delegateDeclaration != null) { return GetDelegatePrototype(delegateDeclaration, (INamedTypeSymbol)symbol, flags); } // Crazily, events for source are not implemented by the legacy C# // code model implementation, but they are for metadata events. Debug.Fail(string.Format("Invalid node/symbol kind: {0}/{1}", node.Kind(), symbol.Kind)); throw Exceptions.ThrowENotImpl(); } } private string GetDelegatePrototype(INamedTypeSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. // Note that we only throw E_FAIL in this case. All others throw E_INVALIDARG. throw Exceptions.ThrowEFail(); } // The unique signature is simply the node key. return GetExternalSymbolFullName(symbol); } var builder = new StringBuilder(); AppendDelegatePrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetDelegatePrototype(DelegateDeclarationSyntax node, INamedTypeSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendDelegatePrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetEventPrototype(IEventSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendEventPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetFunctionPrototype(IMethodSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type | PrototypeFlags.ParameterTypes; } var builder = new StringBuilder(); AppendFunctionPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetFunctionPrototype(BaseMethodDeclarationSyntax node, IMethodSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendFunctionPrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetPropertyPrototype(IPropertySymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendPropertyPrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetPropertyPrototype(BasePropertyDeclarationSyntax node, IPropertySymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendPropertyPrototype(builder, symbol, flags, GetName(node)); return builder.ToString(); } private string GetVariablePrototype(IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. flags = PrototypeFlags.FullName | PrototypeFlags.Type; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, symbol.Name); return builder.ToString(); } private string GetVariablePrototype(VariableDeclaratorSyntax node, IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, GetName(node)); if ((flags & PrototypeFlags.Initializer) != 0 && node.Initializer != null && node.Initializer.Value != null && !node.Initializer.Value.IsMissing) { builder.Append(" = "); builder.Append(node.Initializer.Value); } return builder.ToString(); } private string GetVariablePrototype(EnumMemberDeclarationSyntax node, IFieldSymbol symbol, PrototypeFlags flags) { if ((flags & PrototypeFlags.Signature) != 0) { if (flags != PrototypeFlags.Signature) { // vsCMPrototypeUniqueSignature can't be combined with anything else. throw Exceptions.ThrowEInvalidArg(); } // The unique signature is simply the node key. return GetNodeKey(node).Name; } var builder = new StringBuilder(); AppendVariablePrototype(builder, symbol, flags, GetName(node)); if ((flags & PrototypeFlags.Initializer) != 0 && node.EqualsValue != null && node.EqualsValue.Value != null && !node.EqualsValue.Value.IsMissing) { builder.Append(" = "); builder.Append(node.EqualsValue.Value); } return builder.ToString(); } private void AppendDelegatePrototype(StringBuilder builder, INamedTypeSymbol symbol, PrototypeFlags flags, string baseName) { builder.Append("delegate "); if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.DelegateInvokeMethod.ReturnType)); if (((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) || ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0)) { builder.Append(' '); } } var addSpace = true; switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; case PrototypeFlags.NoName: addSpace = false; break; } if ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0) { if (addSpace) { builder.Append(' '); } builder.Append('('); AppendParametersPrototype(builder, symbol.DelegateInvokeMethod.Parameters, flags); builder.Append(')'); } } private void AppendEventPrototype(StringBuilder builder, IEventSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; } } private void AppendFunctionPrototype(StringBuilder builder, IMethodSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.ReturnType)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } var addSpace = true; switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; case PrototypeFlags.NoName: addSpace = false; break; } if ((flags & (PrototypeFlags.ParameterNames | PrototypeFlags.ParameterTypes)) != 0) { if (addSpace) { builder.Append(' '); } builder.Append('('); AppendParametersPrototype(builder, symbol.Parameters, flags); builder.Append(')'); } } private void AppendPropertyPrototype(StringBuilder builder, IPropertySymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: if (symbol.IsIndexer) { builder.Append("this["); AppendParametersPrototype(builder, symbol.Parameters, PrototypeFlags.ParameterTypes | PrototypeFlags.ParameterNames); builder.Append("]"); } else { builder.Append(baseName); } break; } } private void AppendVariablePrototype(StringBuilder builder, IFieldSymbol symbol, PrototypeFlags flags, string baseName) { if ((flags & PrototypeFlags.Type) != 0) { builder.Append(GetAsStringForCodeTypeRef(symbol.Type)); if ((flags & PrototypeFlags.NameMask) != PrototypeFlags.NoName) { builder.Append(' '); } } switch (flags & PrototypeFlags.NameMask) { case PrototypeFlags.FullName: AppendTypeNamePrototype(builder, includeNamespaces: true, includeGenerics: false, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.TypeName: AppendTypeNamePrototype(builder, includeNamespaces: false, includeGenerics: true, symbol: symbol.ContainingSymbol); builder.Append('.'); goto case PrototypeFlags.BaseName; case PrototypeFlags.BaseName: builder.Append(baseName); break; } } private void AppendParametersPrototype(StringBuilder builder, ImmutableArray<IParameterSymbol> parameters, PrototypeFlags flags) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } AppendParameterPrototype(builder, flags, parameter); first = false; } } private void AppendParameterPrototype(StringBuilder builder, PrototypeFlags flags, IParameterSymbol parameter) { var addSpace = false; if ((flags & PrototypeFlags.ParameterTypes) != 0) { if (parameter.RefKind == RefKind.Ref) { builder.Append("ref "); } else if (parameter.RefKind == RefKind.Out) { builder.Append("out "); } else if (parameter.IsParams) { builder.Append("params "); } builder.Append(GetAsStringForCodeTypeRef(parameter.Type)); addSpace = true; } if ((flags & PrototypeFlags.ParameterNames) != 0) { if (addSpace) { builder.Append(' '); } builder.Append(parameter.Name); } } private static void AppendTypeNamePrototype(StringBuilder builder, bool includeNamespaces, bool includeGenerics, ISymbol symbol) { var symbols = new Stack<ISymbol>(); while (symbol != null) { if (symbol.Kind == SymbolKind.Namespace) { if (!includeNamespaces || ((INamespaceSymbol)symbol).IsGlobalNamespace) { break; } } symbols.Push(symbol); symbol = symbol.ContainingSymbol; } var first = true; while (symbols.Count > 0) { var current = symbols.Pop(); if (!first) { builder.Append('.'); } builder.Append(current.Name); if (current.Kind == SymbolKind.NamedType) { var namedType = (INamedTypeSymbol)current; if (includeGenerics && namedType.Arity > 0) { builder.Append('<'); builder.Append(',', namedType.Arity - 1); builder.Append('>'); } } first = false; } } } }
using System; using NUnit.Framework; using strange.framework.api; using strange.extensions.injector.impl; using strange.extensions.mediation.impl; using strange.extensions.mediation.api; using System.Collections.Generic; using strange.framework.impl; namespace strange.unittests { [TestFixture()] public class TestAbstractMediationBinder { private TestMediationBinder mediationBinder; private InjectionBinder injectionBinder; [SetUp] public void SetUp() { injectionBinder = new InjectionBinder (); mediationBinder = new TestMediationBinder (); mediationBinder.injectionBinder = injectionBinder; } [Test] public void TestRawBindingIsMediationBinding() { IBinding binding = mediationBinder.GetRawBinding (); Assert.IsInstanceOf<IMediationBinding> (binding); } [Test] public void TestAwakeTriggersMappingAndInjection() { mediationBinder.Bind<TestView> ().To<TestMediator> (); injectionBinder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> (); TestView view = new TestView (); mediationBinder.Trigger (MediationEvent.AWAKE, view); Assert.IsTrue (view.registeredWithContext); Assert.IsNotNull (view.testInjection); TestMediator mediator = mediationBinder.mediators [view] as TestMediator; Assert.AreEqual (1, mediationBinder.mediators.Count); Assert.IsNotNull (mediator); Assert.IsInstanceOf<TestMediator> (mediator); Assert.IsTrue (mediator.preregistered); Assert.IsTrue (mediator.registered); Assert.IsFalse (mediator.removed); } [Test] public void TestAwakeTriggersInjectionForUnmappedView() { injectionBinder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> (); TestView view = new TestView (); mediationBinder.Trigger (MediationEvent.AWAKE, view); Assert.IsNotNull (view.testInjection); TestMediator mediator = null; if (mediationBinder.mediators.ContainsKey(view)) { mediator = mediationBinder.mediators [view] as TestMediator; } Assert.AreEqual (0, mediationBinder.mediators.Count); Assert.IsNull (mediator); } [Test] public void TestEnableTriggersMediatorEnabled() { mediationBinder.Bind<TestView> ().To<TestMediator> (); injectionBinder.Bind<ClassToBeInjected>().To<ClassToBeInjected>(); TestView view = new TestView (); mediationBinder.Trigger(MediationEvent.AWAKE, view); TestMediator mediator = mediationBinder.mediators[view] as TestMediator; mediationBinder.Trigger(MediationEvent.ENABLED, view); Assert.IsTrue(mediator.enabled); } [Test] public void TestDisableTriggersMediatorDisabled() { mediationBinder.Bind<TestView> ().To<TestMediator> (); injectionBinder.Bind<ClassToBeInjected>().To<ClassToBeInjected>(); TestView view = new TestView (); mediationBinder.Trigger(MediationEvent.AWAKE, view); TestMediator mediator = mediationBinder.mediators[view] as TestMediator; mediationBinder.Trigger(MediationEvent.DISABLED, view); Assert.IsTrue(mediator.disabled); } [Test] public void TestDestroyedTriggersUnmapping() { mediationBinder.Bind<TestView> ().To<TestMediator> (); injectionBinder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> (); TestView view = new TestView (); mediationBinder.Trigger (MediationEvent.AWAKE, view); TestMediator mediator = mediationBinder.mediators [view] as TestMediator; mediationBinder.Trigger (MediationEvent.DESTROYED, view); Assert.IsTrue (mediator.removed); Assert.AreEqual (0, mediationBinder.mediators.Count); } [Test] public void TestErrorIfClassMappedToItself() { mediationBinder.Bind<TestView> ().To<TestView> (); injectionBinder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> (); TestView view = new TestView (); TestDelegate testDelegate = delegate { mediationBinder.Trigger (MediationEvent.AWAKE, view); }; MediationException ex = Assert.Throws<MediationException>(testDelegate); //Because we've mapped view to self Assert.AreEqual (MediationExceptionType.MEDIATOR_VIEW_STACK_OVERFLOW, ex.type); } [Test] public void TestInjectViews() { injectionBinder.Bind<ClassToBeInjected>().To<ClassToBeInjected>(); TestView view = new TestView(); IView one = new TestView(); IView two = new TestView(); IView three = new TestView(); IView[] views = { view, one, two, three }; view.Views = views; mediationBinder.TestInjectViewAndChildren(view); Assert.AreEqual(true, one.registeredWithContext); Assert.AreEqual(true, two.registeredWithContext); Assert.AreEqual(true, three.registeredWithContext); } [Test] public void TestSimpleRuntimeBinding() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView\",\"To\":\"strange.unittests.TestMediator\"}]"; mediationBinder.ConsumeBindings (jsonString); IBinding binding = mediationBinder.GetBinding<TestView> (); Assert.NotNull (binding); Assert.AreEqual ((binding as IMediationBinding).key, typeof(TestView)); object[] value = (binding as IMediationBinding).value as object[]; Assert.AreEqual (value[0], typeof(TestMediator)); } [Test] public void TestMultipleRuntimeBindings() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView\",\"To\":\"strange.unittests.TestMediator\"}, {\"Bind\":\"strange.unittests.TestView2\",\"To\":\"strange.unittests.TestMediator2\"}]"; mediationBinder.ConsumeBindings (jsonString); IBinding binding = mediationBinder.GetBinding<TestView> (); Assert.NotNull (binding); Assert.AreEqual ((binding as IMediationBinding).key, typeof(TestView)); object[] value = (binding as IMediationBinding).value as object[]; Assert.AreEqual (value[0], typeof(TestMediator)); IBinding binding2 = mediationBinder.GetBinding<TestView2> (); Assert.NotNull (binding2); Assert.AreEqual ((binding2 as IMediationBinding).key, typeof(TestView2)); object[] value2 = (binding2 as IMediationBinding).value as object[]; Assert.AreEqual (value2[0], typeof(TestMediator2)); } [Test] public void TestBindOneViewToManyMediators() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView\",\"To\":[\"strange.unittests.TestMediator\",\"strange.unittests.TestMediator2\"]}]"; mediationBinder.ConsumeBindings (jsonString); IBinding binding = mediationBinder.GetBinding<TestView> (); Assert.NotNull (binding); Assert.AreEqual ((binding as IMediationBinding).key, typeof(TestView)); object[] value = (binding as IMediationBinding).value as object[]; Assert.Contains (typeof(TestMediator), value); Assert.Contains (typeof(TestMediator2), value); } [Test] public void TestBindViewToMediatorSyntax() { string jsonString = "[{\"BindView\":\"strange.unittests.TestView\",\"ToMediator\":[\"strange.unittests.TestMediator\",\"strange.unittests.TestMediator2\"]}]"; mediationBinder.ConsumeBindings (jsonString); IBinding binding = mediationBinder.GetBinding<TestView> (); Assert.NotNull (binding); Assert.AreEqual ((binding as IMediationBinding).key, typeof(TestView)); object[] value = (binding as IMediationBinding).value as object[]; Assert.Contains (typeof(TestMediator), value); Assert.Contains (typeof(TestMediator2), value); } [Test] public void TestBindToAbstraction() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView2\",\"To\":\"strange.unittests.TestMediator\",\"ToAbstraction\":\"strange.unittests.TestView\"}]"; mediationBinder.ConsumeBindings (jsonString); injectionBinder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> (); IBinding binding = mediationBinder.GetBinding<TestView2> (); Assert.NotNull (binding); Assert.AreEqual ((binding as IMediationBinding).key, typeof(TestView2)); object[] value = (binding as IMediationBinding).value as object[]; Assert.Contains (typeof(TestMediator), value); TestView2 view = new TestView2 (); mediationBinder.Trigger (MediationEvent.AWAKE, view); Assert.IsTrue (view.registeredWithContext); Assert.IsNotNull (view.testInjection); TestMediator mediator = mediationBinder.mediators [view] as TestMediator; Assert.AreEqual (1, mediationBinder.mediators.Count); Assert.IsNotNull (mediator); Assert.IsInstanceOf<TestMediator> (mediator); Assert.IsInstanceOf<TestView2> (mediator.view); } [Test] public void TestThrowsErrorOnUnresolvedView() { string jsonString = "[{\"Bind\":\"TestView\",\"To\":\"strange.unittests.TestMediator\"}]"; TestDelegate testDelegate = delegate { mediationBinder.ConsumeBindings (jsonString); }; BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because the Bind value isn't fully qualified Assert.AreEqual (BinderExceptionType.RUNTIME_NULL_VALUE, ex.type); } [Test] public void TestThrowsErrorOnUnresolvedMediator() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView\",\"To\":\"TestMediator\"}]"; TestDelegate testDelegate = delegate { mediationBinder.ConsumeBindings (jsonString); }; BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because the To value isn't fully qualified Assert.AreEqual (BinderExceptionType.RUNTIME_NULL_VALUE, ex.type); } [Test] public void TestThrowsErrorOnUnresolvedAbstraction() { string jsonString = "[{\"Bind\":\"strange.unittests.TestView2\",\"To\":\"strange.unittests.TestMediator\",\"ToAbstraction\":\"TestView\"}]"; TestDelegate testDelegate = delegate { mediationBinder.ConsumeBindings (jsonString); }; BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because the Abstraction value isn't fully qualified Assert.AreEqual (BinderExceptionType.RUNTIME_NULL_VALUE, ex.type); } [Test] public void TestMediatorEnabledAtCreationIfEnabled() { mediationBinder.Bind<TestView>().To<TestMediator>(); injectionBinder.Bind<ClassToBeInjected>().To<ClassToBeInjected>(); TestView view = new TestView(); mediationBinder.Trigger(MediationEvent.AWAKE, view); TestMediator mediator = mediationBinder.mediators[view] as TestMediator; Assert.True(mediator.enabled); } [Test] public void TestMediatorNotEnabledAtCreatioIfDisabledn() { mediationBinder.Bind<TestView>().To<TestMediator>(); injectionBinder.Bind<ClassToBeInjected>().To<ClassToBeInjected>(); TestView view = new TestView(); view.enabled = false; mediationBinder.Trigger(MediationEvent.AWAKE, view); TestMediator mediator = mediationBinder.mediators[view] as TestMediator; Assert.False(mediator.enabled); } } class TestMediationBinder : AbstractMediationBinder { public Dictionary<IView, IMediator> mediators = new Dictionary<IView, IMediator>(); protected override IView[] GetViews(IView view) { TestView testView = view as TestView; return testView.Views; } protected override bool HasMediator(IView view, Type mediatorType) { TestView testView = view as TestView; return testView.HasMediator; } override protected object CreateMediator(IView view, Type mediatorType) { IMediator mediator = new TestMediator (); mediators.Add (view, mediator); return mediator; } override protected IMediator DestroyMediator(IView view, Type mediatorType) { IMediator mediator = null; if (mediators.ContainsKey(view)) { mediator = mediators[view]; mediators.Remove(view); mediator.OnRemove (); } return mediator; } protected override object EnableMediator(IView view, Type mediatorType) { IMediator mediator; if (mediators.TryGetValue(view, out mediator)) { mediator.OnEnabled(); } return mediator; } protected override object DisableMediator(IView view, Type mediatorType) { IMediator mediator; if (mediators.TryGetValue(view, out mediator)) { mediator.OnDisabled(); } return mediator; } protected override void ThrowNullMediatorError (Type viewType, Type mediatorType) { throw new MediationException("The view: " + viewType.ToString() + " is mapped to mediator: " + mediatorType.ToString() + ". AddComponent resulted in null, which probably means " + mediatorType.ToString().Substring(mediatorType.ToString().LastIndexOf(".") + 1) + " is not a MonoBehaviour.", MediationExceptionType.NULL_MEDIATOR); } public void TestInjectViewAndChildren(IView view) { InjectViewAndChildren(view); } public void TestPerformKeyValueBindings(List<object> keyList, List<object> valueList) { performKeyValueBindings(keyList, valueList); } } class TestView : IView { [Inject] public ClassToBeInjected testInjection { get; set; } public TestView() { enabled = true; Views = new IView[] { this }; } #region IView implementation private bool _requiresContext; private bool _registeredWithContext; public IView[] Views = {}; public bool HasMediator = false; public bool requiresContext { get { return _requiresContext; } set { _requiresContext = value; } } public bool registeredWithContext { get { return _registeredWithContext; } set { _registeredWithContext = value; } } public bool autoRegisterWithContext { get { return true; } } public bool enabled { get; set; } public bool shouldRegister { get { return true; } } #endregion } class TestView2 : TestView{} class TestMediator : IMediator { [Inject] public TestView view{ get; set; } public bool preregistered = false; public bool registered = false; public bool removed = false; public bool enabled = false; public bool disabled = false; #region IMediator implementation public void PreRegister () { preregistered = true; } public void OnRegister () { registered = true; } public void OnRemove () { removed = true; } public void OnEnabled () { enabled = true; } public void OnDisabled () { disabled = true; } public UnityEngine.GameObject contextView { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } #endregion } class TestMediator2 : TestMediator{} }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Claims { public partial class Claim { public Claim(System.IO.BinaryReader reader) { } public Claim(System.IO.BinaryReader reader, System.Security.Claims.ClaimsIdentity subject) { } protected Claim(System.Security.Claims.Claim other) { } protected Claim(System.Security.Claims.Claim other, System.Security.Claims.ClaimsIdentity subject) { } public Claim(string type, string value) { } public Claim(string type, string value, string valueType) { } public Claim(string type, string value, string valueType, string issuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer) { } public Claim(string type, string value, string valueType, string issuer, string originalIssuer, System.Security.Claims.ClaimsIdentity subject) { } protected virtual byte[] CustomSerializationData { get { return default(byte[]); } } public string Issuer { get { return default(string); } } public string OriginalIssuer { get { return default(string); } } public System.Collections.Generic.IDictionary<string, string> Properties { get { return default(System.Collections.Generic.IDictionary<string, string>); } } public System.Security.Claims.ClaimsIdentity Subject { get { return default(System.Security.Claims.ClaimsIdentity); } } public string Type { get { return default(string); } } public string Value { get { return default(string); } } public string ValueType { get { return default(string); } } public virtual System.Security.Claims.Claim Clone() { return default(System.Security.Claims.Claim); } public virtual System.Security.Claims.Claim Clone(System.Security.Claims.ClaimsIdentity identity) { return default(System.Security.Claims.Claim); } public override string ToString() { return default(string); } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsIdentity : System.Security.Principal.IIdentity { public const string DefaultIssuer = "LOCAL AUTHORITY"; public const string DefaultNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string DefaultRoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public ClaimsIdentity() { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType) { } public ClaimsIdentity(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(System.IO.BinaryReader reader) { } protected ClaimsIdentity(System.Security.Claims.ClaimsIdentity other) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType) { } public ClaimsIdentity(string authenticationType) { } public ClaimsIdentity(string authenticationType, string nameType, string roleType) { } public System.Security.Claims.ClaimsIdentity Actor { get { return default(System.Security.Claims.ClaimsIdentity); } set { } } public virtual string AuthenticationType { get { return default(string); } } public object BootstrapContext { get { return default(object); }[System.Security.SecurityCriticalAttribute]set { } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } } protected virtual byte[] CustomSerializationData { get { return default(byte[]); } } public virtual bool IsAuthenticated { get { return default(bool); } } public string Label { get { return default(string); } set { } } public virtual string Name { get { return default(string); } } public string NameClaimType { get { return default(string); } } public string RoleClaimType { get { return default(string); } } [System.Security.SecurityCriticalAttribute] public virtual void AddClaim(System.Security.Claims.Claim claim) { } [System.Security.SecurityCriticalAttribute] public virtual void AddClaims(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> claims) { } public virtual System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); } protected virtual System.Security.Claims.Claim CreateClaim(System.IO.BinaryReader reader) { return default(System.Security.Claims.Claim); } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); } public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); } public virtual bool HasClaim(string type, string value) { return default(bool); } [System.Security.SecurityCriticalAttribute] public virtual void RemoveClaim(System.Security.Claims.Claim claim) { } [System.Security.SecurityCriticalAttribute] public virtual bool TryRemoveClaim(System.Security.Claims.Claim claim) { return default(bool); } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public partial class ClaimsPrincipal : System.Security.Principal.IPrincipal { public ClaimsPrincipal() { } public ClaimsPrincipal(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } public ClaimsPrincipal(System.IO.BinaryReader reader) { } public ClaimsPrincipal(System.Security.Principal.IIdentity identity) { } public ClaimsPrincipal(System.Security.Principal.IPrincipal principal) { } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } } public static System.Func<System.Security.Claims.ClaimsPrincipal> ClaimsPrincipalSelector { get { return default(System.Func<System.Security.Claims.ClaimsPrincipal>); }[System.Security.SecurityCriticalAttribute]set { } } public static System.Security.Claims.ClaimsPrincipal Current { get { return default(System.Security.Claims.ClaimsPrincipal); } } protected virtual byte[] CustomSerializationData { get { return default(byte[]); } } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> Identities { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>); } } public virtual System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } } public static System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity> PrimaryIdentitySelector { get { return default(System.Func<System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity>, System.Security.Claims.ClaimsIdentity>); }[System.Security.SecurityCriticalAttribute]set { } } [System.Security.SecurityCriticalAttribute] public virtual void AddIdentities(System.Collections.Generic.IEnumerable<System.Security.Claims.ClaimsIdentity> identities) { } [System.Security.SecurityCriticalAttribute] public virtual void AddIdentity(System.Security.Claims.ClaimsIdentity identity) { } public virtual System.Security.Claims.ClaimsPrincipal Clone() { return default(System.Security.Claims.ClaimsPrincipal); } protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader) { return default(System.Security.Claims.ClaimsIdentity); } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> FindAll(string type) { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } public virtual System.Security.Claims.Claim FindFirst(System.Predicate<System.Security.Claims.Claim> match) { return default(System.Security.Claims.Claim); } public virtual System.Security.Claims.Claim FindFirst(string type) { return default(System.Security.Claims.Claim); } public virtual bool HasClaim(System.Predicate<System.Security.Claims.Claim> match) { return default(bool); } public virtual bool HasClaim(string type, string value) { return default(bool); } public virtual bool IsInRole(string role) { return default(bool); } public virtual void WriteTo(System.IO.BinaryWriter writer) { } protected virtual void WriteTo(System.IO.BinaryWriter writer, byte[] userData) { } } public static partial class ClaimTypes { public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"; public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous"; public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication"; public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant"; public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"; public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision"; public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath"; public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"; public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"; public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid"; public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid"; public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid"; public const string DenyOnlyWindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup"; public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns"; public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration"; public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired"; public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"; public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"; public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid"; public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash"; public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone"; public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent"; public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"; public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone"; public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone"; public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"; public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid"; public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid"; public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber"; public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid"; public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn"; public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"; public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"; public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"; public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system"; public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint"; public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"; public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri"; public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata"; public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version"; public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage"; public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"; public const string WindowsDeviceClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim"; public const string WindowsDeviceGroup = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup"; public const string WindowsFqbnVersion = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsfqbnversion"; public const string WindowsSubAuthority = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority"; public const string WindowsUserClaim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim"; public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname"; } public static partial class ClaimValueTypes { public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary"; public const string Base64Octet = "http://www.w3.org/2001/XMLSchema#base64Octet"; public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean"; public const string Date = "http://www.w3.org/2001/XMLSchema#date"; public const string DateTime = "http://www.w3.org/2001/XMLSchema#dateTime"; public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration"; public const string DnsName = "http://schemas.xmlsoap.org/claims/dns"; public const string Double = "http://www.w3.org/2001/XMLSchema#double"; public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue"; public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Fqbn = "http://www.w3.org/2001/XMLSchema#fqbn"; public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary"; public const string Integer = "http://www.w3.org/2001/XMLSchema#integer"; public const string Integer32 = "http://www.w3.org/2001/XMLSchema#integer32"; public const string Integer64 = "http://www.w3.org/2001/XMLSchema#integer64"; public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo"; public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue"; public const string Sid = "http://www.w3.org/2001/XMLSchema#sid"; public const string String = "http://www.w3.org/2001/XMLSchema#string"; public const string Time = "http://www.w3.org/2001/XMLSchema#time"; public const string UInteger32 = "http://www.w3.org/2001/XMLSchema#uinteger32"; public const string UInteger64 = "http://www.w3.org/2001/XMLSchema#uinteger64"; public const string UpnName = "http://schemas.xmlsoap.org/claims/UPN"; public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration"; } } namespace System.Security.Principal { public partial class GenericIdentity : System.Security.Claims.ClaimsIdentity { protected GenericIdentity(System.Security.Principal.GenericIdentity identity) { } public GenericIdentity(string name) { } public GenericIdentity(string name, string type) { } public override string AuthenticationType { get { return default(string); } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } } public override bool IsAuthenticated { get { return default(bool); } } public override string Name { get { return default(string); } } public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); } } public partial class GenericPrincipal : System.Security.Claims.ClaimsPrincipal { public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles) { } public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } } public override bool IsInRole(string role) { return default(bool); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class JobAccountOperationsExtensions { /// <summary> /// Begins creating a new Azure SQL Job Account or updating an existing /// Azure SQL Job Account. To determine the status of the operation /// call GetJobAccountOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static JobAccountOperationResponse BeginCreateOrUpdate(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating a new Azure SQL Job Account or updating an existing /// Azure SQL Job Account. To determine the status of the operation /// call GetJobAccountOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static Task<JobAccountOperationResponse> BeginCreateOrUpdateAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters, CancellationToken.None); } /// <summary> /// Begins deleting the Azure SQL Job Account with the given name. To /// determine the status of the operation call /// GetJobAccountOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be deleted. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static JobAccountOperationResponse BeginDelete(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).BeginDeleteAsync(resourceGroupName, serverName, jobAccountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins deleting the Azure SQL Job Account with the given name. To /// determine the status of the operation call /// GetJobAccountOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be deleted. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static Task<JobAccountOperationResponse> BeginDeleteAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return operations.BeginDeleteAsync(resourceGroupName, serverName, jobAccountName, CancellationToken.None); } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static JobAccountOperationResponse CreateOrUpdate(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static Task<JobAccountOperationResponse> CreateOrUpdateAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters, CancellationToken.None); } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static JobAccountOperationResponse Delete(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).DeleteAsync(resourceGroupName, serverName, jobAccountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static Task<JobAccountOperationResponse> DeleteAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return operations.DeleteAsync(resourceGroupName, serverName, jobAccountName, CancellationToken.None); } /// <summary> /// Returns information about an Azure SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be retrieved. /// </param> /// <returns> /// Represents the response to a Get Azure Sql Job Account request. /// </returns> public static JobAccountGetResponse Get(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).GetAsync(resourceGroupName, serverName, jobAccountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about an Azure SQL Job Account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be retrieved. /// </param> /// <returns> /// Represents the response to a Get Azure Sql Job Account request. /// </returns> public static Task<JobAccountGetResponse> GetAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName, string jobAccountName) { return operations.GetAsync(resourceGroupName, serverName, jobAccountName, CancellationToken.None); } /// <summary> /// Gets the status of an Azure Sql Job Account create or update /// operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static JobAccountOperationResponse GetJobAccountOperationStatus(this IJobAccountOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).GetJobAccountOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of an Azure Sql Job Account create or update /// operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public static Task<JobAccountOperationResponse> GetJobAccountOperationStatusAsync(this IJobAccountOperations operations, string operationStatusLink) { return operations.GetJobAccountOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Returns information about Azure SQL Job Accounts. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Accounts are hosted in. /// </param> /// <returns> /// Represents the response to a List Azure Sql Job Accounts request. /// </returns> public static JobAccountListResponse List(this IJobAccountOperations operations, string resourceGroupName, string serverName) { return Task.Factory.StartNew((object s) => { return ((IJobAccountOperations)s).ListAsync(resourceGroupName, serverName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about Azure SQL Job Accounts. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IJobAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Accounts are hosted in. /// </param> /// <returns> /// Represents the response to a List Azure Sql Job Accounts request. /// </returns> public static Task<JobAccountListResponse> ListAsync(this IJobAccountOperations operations, string resourceGroupName, string serverName) { return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None); } } }
// 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.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// NotificationChannelsOperations operations. /// </summary> internal partial class NotificationChannelsOperations : IServiceOperations<DevTestLabsClient>, INotificationChannelsOperations { /// <summary> /// Initializes a new instance of the NotificationChannelsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal NotificationChannelsOperations(DevTestLabsClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DevTestLabsClient /// </summary> public DevTestLabsClient Client { get; private set; } /// <summary> /// List notificationchannels in a given lab. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NotificationChannel>>> ListWithHttpMessagesAsync(string labName, ODataQuery<NotificationChannel> odataQuery = default(ODataQuery<NotificationChannel>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("labName", labName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NotificationChannel>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<NotificationChannel>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get notificationchannel. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the notificationChannel. /// </param> /// <param name='expand'> /// Specify the $expand query. Example: 'properties($select=webHookUrl)' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NotificationChannel>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NotificationChannel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<NotificationChannel>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or replace an existing notificationChannel. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the notificationChannel. /// </param> /// <param name='notificationChannel'> /// A notification. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NotificationChannel>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, NotificationChannel notificationChannel, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (notificationChannel == null) { throw new ValidationException(ValidationRules.CannotBeNull, "notificationChannel"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("notificationChannel", notificationChannel); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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(notificationChannel != null) { _requestContent = SafeJsonConvert.SerializeObject(notificationChannel, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NotificationChannel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<NotificationChannel>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<NotificationChannel>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete notificationchannel. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the notificationChannel. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Modify properties of notificationchannels. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the notificationChannel. /// </param> /// <param name='notificationChannel'> /// A notification. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NotificationChannel>> UpdateWithHttpMessagesAsync(string labName, string name, NotificationChannelFragment notificationChannel, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (notificationChannel == null) { throw new ValidationException(ValidationRules.CannotBeNull, "notificationChannel"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("notificationChannel", notificationChannel); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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(notificationChannel != null) { _requestContent = SafeJsonConvert.SerializeObject(notificationChannel, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NotificationChannel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<NotificationChannel>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Send notification to provided channel. /// </summary> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the notificationChannel. /// </param> /// <param name='notifyParameters'> /// Properties for generating a Notification. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> NotifyWithHttpMessagesAsync(string labName, string name, NotifyParameters notifyParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (notifyParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "notifyParameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("labName", labName); tracingParameters.Add("name", name); tracingParameters.Add("notifyParameters", notifyParameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Notify", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}/notify").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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(notifyParameters != null) { _requestContent = SafeJsonConvert.SerializeObject(notifyParameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List notificationchannels in a given lab. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NotificationChannel>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NotificationChannel>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<NotificationChannel>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** namespace NUnit.UiKit { using System; using System.Windows.Forms; using System.Drawing; using NUnit.Core; using NUnit.Util; /// <summary> /// Type safe TreeNode for use in the TestSuiteTreeView. /// NOTE: Hides some methods and properties of base class. /// </summary> public class TestSuiteTreeNode : TreeNode { #region Instance variables and constant definitions /// <summary> /// The testcase or testsuite represented by this node /// </summary> private ITest test; /// <summary> /// The result from the last run of the test /// </summary> private TestResult result; /// <summary> /// Private field used for inclusion by category /// </summary> private bool included = true; private bool showFailedAssumptions = false; /// <summary> /// Image indices for various test states - the values /// must match the indices of the image list used /// </summary> public static readonly int InitIndex = 0; public static readonly int SkippedIndex = 0; public static readonly int FailureIndex = 1; public static readonly int SuccessIndex = 2; public static readonly int IgnoredIndex = 3; public static readonly int InconclusiveIndex = 4; #endregion #region Constructors /// <summary> /// Construct a TestNode given a test /// </summary> public TestSuiteTreeNode( TestInfo test ) : base(test.TestName.Name) { this.test = test; UpdateImageIndex(); } /// <summary> /// Construct a TestNode given a TestResult /// </summary> public TestSuiteTreeNode( TestResult result ) : base( result.Test.TestName.Name ) { this.test = result.Test; this.result = result; UpdateImageIndex(); } #endregion #region Properties /// <summary> /// Test represented by this node /// </summary> public ITest Test { get { return this.test; } set { this.test = value; } } /// <summary> /// Test result for this node /// </summary> public TestResult Result { get { return this.result; } set { this.result = value; UpdateImageIndex(); } } /// <summary> /// Return true if the node has a result, otherwise false. /// </summary> public bool HasResult { get { return this.result != null; } } public string TestType { get { return test.TestType; } } public string StatusText { get { if ( result == null ) return test.RunState.ToString(); return result.ResultState.ToString(); } } public bool Included { get { return included; } set { included = value; this.ForeColor = included ? SystemColors.WindowText : Color.LightBlue; } } public bool ShowFailedAssumptions { get { return showFailedAssumptions; } set { if (value != showFailedAssumptions) { showFailedAssumptions = value; if (HasInconclusiveResults) RepopulateTheoryNode(); } } } public bool HasInconclusiveResults { get { bool hasInconclusiveResults = false; if (Result != null) { foreach (TestResult result in Result.Results) { hasInconclusiveResults |= result.ResultState == ResultState.Inconclusive; if (hasInconclusiveResults) break; } } return hasInconclusiveResults; } } #endregion #region Methods /// <summary> /// UPdate the image index based on the result field /// </summary> public void UpdateImageIndex() { ImageIndex = SelectedImageIndex = CalcImageIndex(); } /// <summary> /// Clear the result of this node and all its children /// </summary> public void ClearResults() { this.result = null; ImageIndex = SelectedImageIndex = CalcImageIndex(); foreach(TestSuiteTreeNode node in Nodes) node.ClearResults(); } /// <summary> /// Gets the Theory node associated with the current /// node. If the current node is a Theory, then the /// current node is returned. Otherwise, if the current /// node is a test case under a theory node, then that /// node is returned. Otherwise, null is returned. /// </summary> /// <returns></returns> public TestSuiteTreeNode GetTheoryNode() { if (this.Test.TestType == "Theory") return this; TestSuiteTreeNode parent = this.Parent as TestSuiteTreeNode; if (parent != null && parent.Test.TestType == "Theory") return parent; return null; } /// <summary> /// Regenerate the test cases under a theory, respecting /// the current setting for ShowFailedAssumptions /// </summary> public void RepopulateTheoryNode() { // Ignore if it's not a theory or if it has not been run yet if (this.Test.TestType == "Theory" && this.HasResult) { Nodes.Clear(); foreach (TestResult result in Result.Results) if (showFailedAssumptions || result.ResultState != ResultState.Inconclusive) Nodes.Add(new TestSuiteTreeNode(result)); } } /// <summary> /// Calculate the image index based on the node contents /// </summary> /// <returns>Image index for this node</returns> private int CalcImageIndex() { if (this.result == null) { switch (this.test.RunState) { case RunState.Ignored: return IgnoredIndex; case RunState.NotRunnable: return FailureIndex; default: return InitIndex; } } else { switch (this.result.ResultState) { case ResultState.Inconclusive: return InconclusiveIndex; case ResultState.Skipped: return SkippedIndex; case ResultState.NotRunnable: case ResultState.Failure: case ResultState.Error: case ResultState.Cancelled: return FailureIndex; case ResultState.Ignored: return IgnoredIndex; case ResultState.Success: foreach (TestSuiteTreeNode node in this.Nodes) if (node.ImageIndex == IgnoredIndex) return IgnoredIndex; return SuccessIndex; default: return InitIndex; } } } internal void Accept(TestSuiteTreeNodeVisitor visitor) { visitor.Visit(this); foreach (TestSuiteTreeNode node in this.Nodes) { node.Accept(visitor); } } #endregion } public abstract class TestSuiteTreeNodeVisitor { public abstract void Visit(TestSuiteTreeNode node); } }
using System; using System.Globalization; /// <summary> /// Int64.System.IConvertible.ToSByte(IFormatProvider) /// </summary> public class Int64IConvertibleToSByte { public static int Main() { Int64IConvertibleToSByte ui64IContSByte = new Int64IConvertibleToSByte(); TestLibrary.TestFramework.BeginTestCase("Int64IConvertibleToSByte"); if (ui64IContSByte.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[PosTest]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[NegTest]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest1:The Int64 value which is in the range of SByte IConvertible To SByte 1"); try { long int64A = (long)SByte.MaxValue; IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(provider); if (sbyteA != 127) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:The Int64 value which is in the range of SByte IConvertible To SByte 2"); try { long int64A = (long)SByte.MinValue; IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(null); if (sbyteA != (SByte)int64A) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; CultureInfo myculture = new CultureInfo("el-GR"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("PosTest3:The Int64 value which is in the range of SByte IConvertible To SByte 3"); try { long int64A = this.GetInt32(0, 127); IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(provider); if (sbyteA != (SByte)int64A) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:The Int64 value which is in the range of SByte IConvertible To SByte 4"); try { long int64A = this.GetInt32(1, 129) * (-1); IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(null); if (sbyteA != (SByte)int64A) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("NegTest1:The Int64 value which is out the range of SByte IConvertible To SByte 1"); try { long int64A = Int64.MaxValue; IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(provider); retVal = false; TestLibrary.TestFramework.LogError("N001", "Int64 value out of the range of SByte but not throw exception"); } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("NegTest2:The Int64 value which is out the range of SByte IConvertible To SByte 2"); try { long int64A = TestLibrary.Generator.GetInt64(-55); if (int64A <= 127) { int64A = int64A + 127; } IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(provider); retVal = false; TestLibrary.TestFramework.LogError("N004", "Int64 value out of the range of Byte but not throw exception"); } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N005", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; TestLibrary.TestFramework.BeginScenario("NegTest3:The Int64 value which is out the range of Byte IConvertible To Byte 3"); try { long int64A = TestLibrary.Generator.GetInt64(-55); if (int64A <=128) { int64A = (int64A + 129) * (-1); } else { int64A = int64A * (-1); } IConvertible iConvert = (IConvertible)(int64A); sbyte sbyteA = iConvert.ToSByte(provider); retVal = false; TestLibrary.TestFramework.LogError("N003", "Int64 value out of the range of Byte but not throw exception"); } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections.Generic; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { [Serializable] public class NodeGUI : ScriptableObject { [SerializeField] private int m_nodeWindowId; [SerializeField] private Rect m_baseRect; [SerializeField] private Model.NodeData m_data; [SerializeField] private Model.ConfigGraph m_graph; [SerializeField] private string m_nodeSyle; [SerializeField] private AssetGraphController m_controller; [SerializeField] private List<string> m_errors = new List<string>(); /* show error on node functions. */ private bool m_hasErrors = false; /* show progress on node functions(unused. due to mainthread synchronization problem.) can not update any visual on Editor while building AssetBundles through AssetBundleGraph. */ private float m_progress; private bool m_running; /* * Properties */ public string Name { get { return m_data.Name; } set { m_data.Name = value; this.name = value; } } public string Id { get { return m_data.Id; } } public Model.NodeData Data { get { return m_data; } } public Rect Region { get { return m_baseRect; } } public Model.ConfigGraph ParentGraph { get { return m_graph; } } public AssetGraphController Controller { get { return m_controller; } } public List<string> Errors { get { return m_errors; } } public void ResetErrorStatus () { m_hasErrors = false; UpdateErrors(new List<string>()); } public void AppendErrorSources (List<string> errors) { this.m_hasErrors = true; UpdateErrors(errors); } public int WindowId { get { return m_nodeWindowId; } set { m_nodeWindowId = value; } } public void OnUndoObject(AssetGraphController c) { m_data.ResetInstance (); m_controller = c; } public static NodeGUI CreateNodeGUI(AssetGraphController c, Model.NodeData data) { var newNode = ScriptableObject.CreateInstance<NodeGUI> (); newNode.Init (c, data); return newNode; } private void Init (AssetGraphController c, Model.NodeData data) { m_nodeWindowId = 0; m_controller = c; m_graph = m_controller.TargetGraph; m_data = data; name = m_data.Name; m_baseRect = new Rect(m_data.X, m_data.Y, Model.Settings.GUI.NODE_BASE_WIDTH, Model.Settings.GUI.NODE_BASE_HEIGHT); m_nodeSyle = data.Operation.Object.InactiveStyle; } public NodeGUI Duplicate (AssetGraphController controller, float newX, float newY) { var data = m_data.Duplicate(); data.X = newX; data.Y = newY; return CreateNodeGUI (controller, data); } public void SetActive (bool active) { if(active) { Selection.activeObject = this; m_nodeSyle = m_data.Operation.Object.ActiveStyle; } else { m_nodeSyle = m_data.Operation.Object.InactiveStyle; } } public void UpdateErrors (List<string> errorsSource) { m_errors = errorsSource; } private void RefreshConnectionPos (float yOffset) { for (int i = 0; i < m_data.InputPoints.Count; i++) { var point = m_data.InputPoints[i]; point.UpdateRegion(this, yOffset, i, m_data.InputPoints.Count); } for (int i = 0; i < m_data.OutputPoints.Count; i++) { var point = m_data.OutputPoints[i]; point.UpdateRegion(this, yOffset, i, m_data.OutputPoints.Count); } } private bool IsValidInputConnectionPoint(Model.ConnectionPointData point) { return m_data.Operation.Object.IsValidInputConnectionPoint(point); } /** retrieve mouse events for this node in this GraphEditor window. */ private void HandleNodeMouseEvent () { switch (Event.current.type) { /* handling release of mouse drag from this node to another node. this node doesn't know about where the other node is. the master only knows. only emit event. */ case EventType.Ignore: { NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CONNECTING_END, this, Event.current.mousePosition, null)); break; } /* check if the mouse-down point is over one of the connectionPoint in this node. then emit event. */ case EventType.MouseDown: { Model.ConnectionPointData result = IsOverConnectionPoint(Event.current.mousePosition); if (result != null) { NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CONNECTING_BEGIN, this, Event.current.mousePosition, result)); break; } else { NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CLICKED, this, Event.current.mousePosition, null)); } break; } } /* retrieve mouse events for this node in|out of this GraphTool window. */ switch (Event.current.rawType) { case EventType.MouseUp: { bool eventSent = false; // send EVENT_CONNECTION_ESTABLISHED event if MouseUp performed on ConnectionPoint Action<Model.ConnectionPointData> raiseEventIfHit = (Model.ConnectionPointData point) => { // Only one connectionPoint can send NodeEvent. if(eventSent) { return; } // If InputConnectionPoint is not valid at this moment, ignore if(!IsValidInputConnectionPoint(point)) { return; } if (point.Region.Contains(Event.current.mousePosition)) { NodeGUIUtility.NodeEventHandler( new NodeEvent(NodeEvent.EventType.EVENT_CONNECTION_ESTABLISHED, this, Event.current.mousePosition, point)); eventSent = true; return; } }; m_data.InputPoints.ForEach(raiseEventIfHit); m_data.OutputPoints.ForEach(raiseEventIfHit); break; } } /* right click to open Context menu */ if (Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseUp && Event.current.button == 1)) { var menu = new GenericMenu(); Data.Operation.Object.OnContextMenuGUI(menu); menu.AddItem( new GUIContent("Delete"), false, () => { NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_DELETE, this, Vector2.zero, null)); } ); menu.ShowAsContext(); Event.current.Use(); } } public void DrawConnectionInputPointMark (NodeEvent eventSource, bool justConnecting) { var defaultPointTex = NodeGUIUtility.pointMark; var lastColor = GUI.color; bool shouldDrawEnable = !( eventSource != null && eventSource.eventSourceNode != null && !Model.ConnectionData.CanConnect(eventSource.eventSourceNode.Data, m_data) ); bool shouldDrawWithEnabledColor = shouldDrawEnable && justConnecting && eventSource != null && eventSource.eventSourceNode.Id != this.Id && eventSource.point.IsOutput; foreach (var point in m_data.InputPoints) { if(IsValidInputConnectionPoint(point)) { if(shouldDrawWithEnabledColor) { GUI.color = Model.Settings.GUI.COLOR_CAN_CONNECT; } else { GUI.color = (justConnecting) ? Model.Settings.GUI.COLOR_CAN_NOT_CONNECT : Model.Settings.GUI.COLOR_CONNECTED; } GUI.DrawTexture(point.GetGlobalPointRegion(this), defaultPointTex); GUI.color = lastColor; } } } public void DrawConnectionOutputPointMark (NodeEvent eventSource, bool justConnecting, Event current) { var defaultPointTex = NodeGUIUtility.pointMark; var lastColor = GUI.color; bool shouldDrawEnable = !( eventSource != null && eventSource.eventSourceNode != null && !Model.ConnectionData.CanConnect(m_data, eventSource.eventSourceNode.Data) ); bool shouldDrawWithEnabledColor = shouldDrawEnable && justConnecting && eventSource != null && eventSource.eventSourceNode.Id != this.Id && eventSource.point.IsInput; var globalMousePosition = current.mousePosition; foreach (var point in m_data.OutputPoints) { var pointRegion = point.GetGlobalPointRegion(this); if(shouldDrawWithEnabledColor) { GUI.color = Model.Settings.GUI.COLOR_CAN_CONNECT; } else { GUI.color = (justConnecting) ? Model.Settings.GUI.COLOR_CAN_NOT_CONNECT : Model.Settings.GUI.COLOR_CONNECTED; } GUI.DrawTexture( pointRegion, defaultPointTex ); GUI.color = lastColor; // eventPosition is contained by outputPointRect. if (pointRegion.Contains(globalMousePosition)) { if (current.type == EventType.MouseDown) { NodeGUIUtility.NodeEventHandler( new NodeEvent(NodeEvent.EventType.EVENT_CONNECTING_BEGIN, this, current.mousePosition, point)); } } } } public void DrawNode () { GUIStyle s = NodeGUIUtility.nodeSkin.FindStyle(m_nodeSyle); GUI.Window(m_nodeWindowId, m_baseRect, DrawThisNode, string.Empty, s); } private void DrawThisNode(int id) { UpdateNodeRect (); HandleNodeMouseEvent (); DrawNodeContents(); } private void DrawNodeContents () { var oldColor = GUI.color; var textColor = (EditorGUIUtility.isProSkin)? Color.black : oldColor; var style = new GUIStyle(EditorStyles.label); style.alignment = TextAnchor.MiddleCenter; var connectionNodeStyleOutput = new GUIStyle(EditorStyles.label); connectionNodeStyleOutput.alignment = TextAnchor.MiddleRight; var connectionNodeStyleInput = new GUIStyle(EditorStyles.label); connectionNodeStyleInput.alignment = TextAnchor.MiddleLeft; var titleHeight = style.CalcSize(new GUIContent(Name)).y + Model.Settings.GUI.NODE_TITLE_HEIGHT_MARGIN; var nodeTitleRect = new Rect(0, 0, m_baseRect.width, titleHeight); GUI.color = textColor; GUI.Label(nodeTitleRect, Name, style); GUI.color = oldColor; if (m_running) { EditorGUI.ProgressBar(new Rect(10f, m_baseRect.height - 20f, m_baseRect.width - 20f, 10f), m_progress, string.Empty); } if (m_hasErrors) { GUIStyle errorStyle = new GUIStyle("CN EntryError"); errorStyle.alignment = TextAnchor.MiddleCenter; var labelSize = GUI.skin.label.CalcSize(new GUIContent(Name)); EditorGUI.LabelField(new Rect((nodeTitleRect.width - labelSize.x )/2.0f - 28f, (nodeTitleRect.height-labelSize.y)/2.0f - 7f, 20f, 20f), string.Empty, errorStyle); } // draw & update connectionPoint button interface. Action<Model.ConnectionPointData> drawConnectionPoint = (Model.ConnectionPointData point) => { var label = point.Label; if( label != Model.Settings.DEFAULT_INPUTPOINT_LABEL && label != Model.Settings.DEFAULT_OUTPUTPOINT_LABEL) { var region = point.Region; // if point is output node, then label position offset is minus. otherwise plus. var xOffset = (point.IsOutput) ? - m_baseRect.width : Model.Settings.GUI.INPUT_POINT_WIDTH; var labelStyle = (point.IsOutput) ? connectionNodeStyleOutput : connectionNodeStyleInput; var labelRect = new Rect(region.x + xOffset, region.y - (region.height/2), m_baseRect.width, region.height*2); GUI.color = textColor; GUI.Label(labelRect, label, labelStyle); GUI.color = oldColor; } GUI.backgroundColor = Color.clear; Texture2D tex = (point.IsInput)? NodeGUIUtility.inputPointBG : NodeGUIUtility.outputPointBG; GUI.Button(point.Region, tex, "AnimationKeyframeBackground"); }; m_data.InputPoints.ForEach(drawConnectionPoint); m_data.OutputPoints.ForEach(drawConnectionPoint); GUIStyle catStyle = new GUIStyle("WhiteMiniLabel"); catStyle.alignment = TextAnchor.LowerRight; var categoryRect = new Rect(2f, m_baseRect.height - 14f, m_baseRect.width - 4f, 16f); GUI.Label(categoryRect, m_data.Operation.Object.Category, catStyle); } public void UpdateNodeRect () { // UpdateNodeRect will be called outside OnGUI(), so it use inacurate but simple way to calcurate label width // instead of CalcSize() float labelWidth = GUI.skin.label.CalcSize(new GUIContent(this.Name)).x; float outputLabelWidth = 0f; float inputLabelWidth = 0f; if(m_data.InputPoints.Count > 0) { var inputLabels = m_data.InputPoints.OrderByDescending(p => p.Label.Length).Select(p => p.Label); if (inputLabels.Any()) { inputLabelWidth = GUI.skin.label.CalcSize(new GUIContent(inputLabels.First())).x; } } if(m_data.OutputPoints.Count > 0) { var outputLabels = m_data.OutputPoints.OrderByDescending(p => p.Label.Length).Select(p => p.Label); if (outputLabels.Any()) { outputLabelWidth = GUI.skin.label.CalcSize(new GUIContent(outputLabels.First())).x; } } var titleHeight = GUI.skin.label.CalcSize(new GUIContent(Name)).y + Model.Settings.GUI.NODE_TITLE_HEIGHT_MARGIN; // update node height by number of output connectionPoint. var nPoints = Mathf.Max(m_data.OutputPoints.Count, m_data.InputPoints.Count); this.m_baseRect = new Rect(m_baseRect.x, m_baseRect.y, m_baseRect.width, Model.Settings.GUI.NODE_BASE_HEIGHT + titleHeight + (Model.Settings.GUI.FILTER_OUTPUT_SPAN * Mathf.Max(0, (nPoints - 1))) ); var newWidth = Mathf.Max(Model.Settings.GUI.NODE_BASE_WIDTH, outputLabelWidth + inputLabelWidth + Model.Settings.GUI.NODE_WIDTH_MARGIN); newWidth = Mathf.Max(newWidth, labelWidth + Model.Settings.GUI.NODE_WIDTH_MARGIN); m_baseRect = new Rect(m_baseRect.x, m_baseRect.y, newWidth, m_baseRect.height); RefreshConnectionPos(titleHeight); } private Model.ConnectionPointData IsOverConnectionPoint (Vector2 touchedPoint) { foreach(var p in m_data.InputPoints) { var region = p.Region; if(!IsValidInputConnectionPoint(p)) { continue; } if (region.x <= touchedPoint.x && touchedPoint.x <= region.x + region.width && region.y <= touchedPoint.y && touchedPoint.y <= region.y + region.height ) { return p; } } foreach(var p in m_data.OutputPoints) { var region = p.Region; if (region.x <= touchedPoint.x && touchedPoint.x <= region.x + region.width && region.y <= touchedPoint.y && touchedPoint.y <= region.y + region.height ) { return p; } } return null; } public Rect GetRect () { return m_baseRect; } public Vector2 GetPos () { return m_baseRect.position; } public int GetX () { return (int)m_baseRect.x; } public int GetY () { return (int)m_baseRect.y; } public int GetRightPos () { return (int)(m_baseRect.x + m_baseRect.width); } public int GetBottomPos () { return (int)(m_baseRect.y + m_baseRect.height); } public void SetPos (Vector2 position) { m_baseRect.position = position; m_data.X = position.x; m_data.Y = position.y; } public void MoveBy (Vector2 distance) { m_baseRect.position = m_baseRect.position + distance; m_data.X = m_data.X + distance.x; m_data.Y = m_data.Y + distance.y; } public void SetProgress (float val) { m_progress = val; } public void ShowProgress () { m_running = true; } public void HideProgress () { m_running = false; } public bool Conitains (Vector2 globalPos) { if (m_baseRect.Contains(globalPos)) { return true; } foreach (var point in m_data.OutputPoints) { if (point.GetGlobalPointRegion(this).Contains(globalPos)) { return true; } } return false; } public Model.ConnectionPointData FindConnectionPointByPosition (Vector2 globalPos) { foreach (var point in m_data.InputPoints) { if(!IsValidInputConnectionPoint(point)) { continue; } if (point.GetGlobalRegion(this).Contains(globalPos) || point.GetGlobalPointRegion(this).Contains(globalPos)) { return point; } } foreach (var point in m_data.OutputPoints) { if (point.GetGlobalRegion(this).Contains(globalPos) || point.GetGlobalPointRegion(this).Contains(globalPos)) { return point; } } return null; } public static void ShowTypeNamesMenu (string current, List<string> contents, Action<string> ExistSelected) { var menu = new GenericMenu(); for (var i = 0; i < contents.Count; i++) { var type = contents[i]; var selected = false; if (type == current) selected = true; menu.AddItem( new GUIContent(type), selected, () => { ExistSelected(type); } ); } menu.ShowAsContext(); } public static void ShowFilterKeyTypeMenu (string current, Action<string> Selected) { var menu = new GenericMenu(); menu.AddDisabledItem(new GUIContent(current)); menu.AddSeparator(string.Empty); var guiNames = FilterTypeUtility.GetFilterGUINames (); for (var i = 0; i < guiNames.Count; i++) { var name = guiNames[i]; if (name == current) continue; menu.AddItem( new GUIContent(name), false, () => { Selected(name); } ); } menu.ShowAsContext(); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; using Gallio.Common; using Gallio.Common.Markup; using Gallio.Runner.Reports.Schema; using Gallio.Runtime.ProgressMonitoring; using Gallio.Model.Schema; namespace Gallio.Runner.Reports { /// <summary> /// Default implementation of a report writer. /// </summary> public class DefaultReportWriter : IReportWriter { private readonly Report report; private readonly IReportContainer reportContainer; private readonly List<string> reportDocumentPaths; private readonly AttachmentPathResolver attachmentPathResolver; private bool reportSaved; private bool reportAttachmentsSaved; /// <summary> /// Creates a report writer for the specified report. /// </summary> /// <param name="report">The report.</param> /// <param name="reportContainer">The report container.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/> or <paramref name="reportContainer"/> is null.</exception> public DefaultReportWriter(Report report, IReportContainer reportContainer) { if (report == null) throw new ArgumentNullException(@"report"); if (reportContainer == null) throw new ArgumentNullException(@"reportContainer"); this.report = report; this.reportContainer = reportContainer; reportDocumentPaths = new List<string>(); attachmentPathResolver = new AttachmentPathResolver(reportContainer); } /// <inheritdoc /> public Report Report { get { return report; } } /// <inheritdoc /> public IReportContainer ReportContainer { get { return reportContainer; } } /// <inheritdoc /> public IList<string> ReportDocumentPaths { get { return reportDocumentPaths.ToArray(); } } /// <inheritdoc /> public void AddReportDocumentPath(string path) { reportDocumentPaths.Add(path); } /// <inheritdoc /> public void SerializeReport(XmlWriter xmlWriter, AttachmentContentDisposition attachmentContentDisposition) { if (xmlWriter == null) throw new ArgumentNullException(@"xmlWriter"); var ignoreAttributes = new XmlAttributes(); ignoreAttributes.XmlIgnore = true; var overrides = new XmlAttributeOverrides(); // Prune unnecessary ids that can be determined implicitly from the report structure. overrides.Add(typeof(TestStepData), @"ParentId", ignoreAttributes); // Only include content path when linking. if (attachmentContentDisposition != AttachmentContentDisposition.Link) { overrides.Add(typeof(AttachmentData), @"ContentPath", ignoreAttributes); } // Only include content data when inline. if (attachmentContentDisposition != AttachmentContentDisposition.Inline) { overrides.Add(typeof(AttachmentData), @"SerializedContents", ignoreAttributes); } WithUpdatedContentPathsAndDisposition(attachmentContentDisposition, () => { // Serialize the report. var serializer = new XmlSerializer(typeof(Report), overrides); serializer.Serialize(xmlWriter, report); }); } /// <inheritdoc /> public void WithUpdatedContentPathsAndDisposition(AttachmentContentDisposition attachmentContentDisposition, Action action) { using (new UpdatedContentPathsAndDisposition(attachmentPathResolver, attachmentContentDisposition, report.TestPackageRun)) { action(); } } /// <inheritdoc /> public void SaveReport(AttachmentContentDisposition attachmentContentDisposition, IProgressMonitor progressMonitor) { if (progressMonitor == null) throw new ArgumentNullException(@"progressMonitor"); if (reportSaved) return; int attachmentCount = CountAttachments(report); using (progressMonitor.BeginTask("Saving report.", attachmentCount + 1)) { var encoding = new UTF8Encoding(false); var settings = new XmlWriterSettings(); settings.CheckCharacters = false; settings.Indent = true; settings.Encoding = encoding; settings.CloseOutput = true; string reportPath = reportContainer.ReportName + @".xml"; progressMonitor.ThrowIfCanceled(); progressMonitor.SetStatus(reportPath); using (XmlWriter writer = XmlWriter.Create(reportContainer.OpenWrite(reportPath, MimeTypes.Xml, settings.Encoding), settings)) { progressMonitor.ThrowIfCanceled(); SerializeReport(writer, attachmentContentDisposition); } progressMonitor.Worked(1); progressMonitor.SetStatus(@""); if (attachmentContentDisposition == AttachmentContentDisposition.Link && attachmentCount != 0) { progressMonitor.ThrowIfCanceled(); using (IProgressMonitor subProgressMonitor = progressMonitor.CreateSubProgressMonitor(attachmentCount)) SaveReportAttachments(subProgressMonitor); } AddReportDocumentPath(reportPath); reportSaved = true; } } /// <inheritdoc /> public void SaveReportAttachments(IProgressMonitor progressMonitor) { if (progressMonitor == null) throw new ArgumentNullException(@"progressMonitor"); if (reportAttachmentsSaved) return; int attachmentCount = CountAttachments(report); if (attachmentCount == 0) return; using (progressMonitor.BeginTask("Saving report attachments.", attachmentCount)) { foreach (TestStepRun testStepRun in report.TestPackageRun.AllTestStepRuns) { foreach (AttachmentData attachment in testStepRun.TestLog.Attachments) { string attachmentPath = attachmentPathResolver.GetAttachmentPath(testStepRun.Step.Id, attachment.Name, attachment.ContentType); progressMonitor.ThrowIfCanceled(); progressMonitor.SetStatus(attachmentPath); SaveAttachmentContents(attachment, attachmentPath); progressMonitor.Worked(1); } } reportAttachmentsSaved = true; } } private void SaveAttachmentContents(AttachmentData attachmentData, string attachmentPath) { var encoding = new UTF8Encoding(false); using (Stream attachmentStream = reportContainer.OpenWrite(attachmentPath, attachmentData.ContentType, encoding)) attachmentData.SaveContents(attachmentStream, encoding); } private static int CountAttachments(Report report) { int count = 0; if (report.TestPackageRun != null) { foreach (TestStepRun testStepRun in report.TestPackageRun.AllTestStepRuns) { count += testStepRun.TestLog.Attachments.Count; } } return count; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Transactions; using Abp.Dependency; using Abp.Domain.Uow; using Abp.EntityHistory.Extensions; using Abp.Events.Bus.Entities; using Abp.Extensions; using Abp.Json; using JetBrains.Annotations; namespace Abp.EntityHistory { public class EntityHistoryHelper : EntityHistoryHelperBase, IEntityHistoryHelper, ITransientDependency { public EntityHistoryHelper( IEntityHistoryConfiguration configuration, IUnitOfWorkManager unitOfWorkManager) : base(configuration, unitOfWorkManager) { } public virtual EntityChangeSet CreateEntityChangeSet(DbContext context) { var changeSet = new EntityChangeSet { Reason = EntityChangeSetReasonProvider.Reason.TruncateWithPostfix(EntityChangeSet.MaxReasonLength), // Fill "who did this change" BrowserInfo = ClientInfoProvider.BrowserInfo.TruncateWithPostfix(EntityChangeSet.MaxBrowserInfoLength), ClientIpAddress = ClientInfoProvider.ClientIpAddress.TruncateWithPostfix(EntityChangeSet.MaxClientIpAddressLength), ClientName = ClientInfoProvider.ComputerName.TruncateWithPostfix(EntityChangeSet.MaxClientNameLength), ImpersonatorTenantId = AbpSession.ImpersonatorTenantId, ImpersonatorUserId = AbpSession.ImpersonatorUserId, TenantId = AbpSession.TenantId, UserId = AbpSession.UserId }; if (!IsEntityHistoryEnabled) { return changeSet; } var objectContext = context.As<IObjectContextAdapter>().ObjectContext; var relationshipChanges = objectContext.ObjectStateManager .GetObjectStateEntries(EntityState.Added | EntityState.Deleted) .Where(state => state.IsRelationship) .ToList(); foreach (var entityEntry in context.ChangeTracker.Entries()) { var typeOfEntity = entityEntry.GetEntityBaseType(); var shouldTrackEntity = IsTypeOfTrackedEntity(typeOfEntity); if (shouldTrackEntity.HasValue && !shouldTrackEntity.Value) { continue; } if (!IsTypeOfEntity(typeOfEntity)) { continue; } var shouldAuditEntity = IsTypeOfAuditedEntity(typeOfEntity); if (shouldAuditEntity.HasValue && !shouldAuditEntity.Value) { continue; } var entityType = GetEntityType(objectContext, typeOfEntity); var entityChange = CreateEntityChange(entityEntry, entityType); if (entityChange == null) { continue; } var isAuditableEntity = shouldAuditEntity.HasValue && shouldAuditEntity.Value; var isTrackableEntity = shouldTrackEntity.HasValue && shouldTrackEntity.Value; var shouldSaveAuditedPropertiesOnly = !isAuditableEntity && !isTrackableEntity; var entitySet = GetEntitySet(objectContext, entityType); var propertyChanges = new List<EntityPropertyChange>(); propertyChanges.AddRange(GetPropertyChanges(entityEntry, entityType, entitySet, shouldSaveAuditedPropertiesOnly)); propertyChanges.AddRange(GetRelationshipChanges(entityEntry, entityType, entitySet, relationshipChanges, shouldSaveAuditedPropertiesOnly)); if (propertyChanges.Count == 0) { continue; } entityChange.PropertyChanges = propertyChanges; changeSet.EntityChanges.Add(entityChange); } return changeSet; } public virtual async Task SaveAsync(DbContext context, EntityChangeSet changeSet) { if (!IsEntityHistoryEnabled) { return; } UpdateChangeSet(context, changeSet); if (changeSet.EntityChanges.Count == 0) { return; } using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { await EntityHistoryStore.SaveAsync(changeSet); await uow.CompleteAsync(); } } public virtual void Save(DbContext context, EntityChangeSet changeSet) { if (!IsEntityHistoryEnabled) { return; } UpdateChangeSet(context, changeSet); if (changeSet.EntityChanges.Count == 0) { return; } using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { EntityHistoryStore.Save(changeSet); uow.Complete(); } } [CanBeNull] protected virtual string GetEntityId(DbEntityEntry entityEntry, EntityType entityType) { var primaryKey = entityType.KeyProperties.First(); var property = entityEntry.Property(primaryKey.Name); return (property.GetNewValue() ?? property.GetOriginalValue())?.ToJsonString(); } [CanBeNull] private EntityChange CreateEntityChange(DbEntityEntry entityEntry, EntityType entityType) { var entityId = GetEntityId(entityEntry, entityType); var entityTypeFullName = entityEntry.GetEntityBaseType().FullName; EntityChangeType changeType; switch (entityEntry.State) { case EntityState.Added: changeType = EntityChangeType.Created; break; case EntityState.Deleted: changeType = EntityChangeType.Deleted; break; case EntityState.Modified: changeType = entityEntry.IsDeleted() ? EntityChangeType.Deleted : EntityChangeType.Updated; break; case EntityState.Detached: case EntityState.Unchanged: return null; default: Logger.ErrorFormat("Unexpected {0} - {1}", nameof(entityEntry.State), entityEntry.State); return null; } if (entityId == null && changeType != EntityChangeType.Created) { Logger.ErrorFormat("EntityChangeType {0} must have non-empty entity id", changeType); return null; } return new EntityChange { ChangeType = changeType, EntityEntry = entityEntry, // [NotMapped] EntityId = entityId, EntityTypeFullName = entityTypeFullName, TenantId = AbpSession.TenantId }; } private EntityType GetEntityType(ObjectContext context, Type entityType, bool useClrType = true) { var metadataWorkspace = context.MetadataWorkspace; if (useClrType) { /* Get the mapping between Clr types in OSpace */ var objectItemCollection = ((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace)); return metadataWorkspace .GetItems<EntityType>(DataSpace.OSpace) .Single(e => objectItemCollection.GetClrType(e) == entityType); } else { return metadataWorkspace .GetItems<EntityType>(DataSpace.CSpace) .Single(e => e.Name == entityType.Name); } } private EntitySet GetEntitySet(ObjectContext context, EntityType entityType) { var metadataWorkspace = context.MetadataWorkspace; /* Get the mapping between entity set/type in CSpace */ return metadataWorkspace .GetItems<EntityContainer>(DataSpace.CSpace) .Single() .EntitySets .Single(e => e.ElementType.Name == entityType.Name || entityType.BaseType != null && IsBaseTypeHasElementTypeName(e.ElementType.Name, entityType.BaseType)); } private static bool IsBaseTypeHasElementTypeName(string elementTypeName, EdmType entityEdmType) { if (elementTypeName == entityEdmType.Name) { return true; } return entityEdmType.BaseType != null && IsBaseTypeHasElementTypeName(elementTypeName, entityEdmType.BaseType); } /// <summary> /// Gets the property changes for this entry. /// </summary> private ICollection<EntityPropertyChange> GetPropertyChanges(DbEntityEntry entityEntry, EntityType entityType, EntitySet entitySet, bool auditedPropertiesOnly) { var propertyChanges = new List<EntityPropertyChange>(); foreach (var property in entityType.Properties) { if (entityType.KeyProperties.Any(m => m.Name == property.Name)) { continue; } if (!(property.IsPrimitiveType || property.IsComplexType)) { // Skipping other types of properties // - Reference navigation properties (DbReferenceEntry) // - Collection navigation properties (DbCollectionEntry) continue; } var propertyEntry = entityEntry.Property(property.Name); var propertyInfo = propertyEntry.EntityEntry.GetPropertyInfo(propertyEntry.Name); var shouldSaveProperty = IsAuditedPropertyInfo(propertyInfo) ?? !auditedPropertiesOnly; if (shouldSaveProperty) { propertyChanges.Add( CreateEntityPropertyChange( propertyEntry.GetOriginalValue(), propertyEntry.GetNewValue(), propertyInfo ) ); } } return propertyChanges; } /// <summary> /// Gets the property changes for this entry. /// </summary> private ICollection<EntityPropertyChange> GetRelationshipChanges(DbEntityEntry entityEntry, EntityType entityType, EntitySet entitySet, ICollection<ObjectStateEntry> relationshipChanges, bool auditedPropertiesOnly) { var propertyChanges = new List<EntityPropertyChange>(); var navigationProperties = entityType.NavigationProperties; var isCreated = entityEntry.IsCreated(); var isDeleted = entityEntry.IsDeleted(); // Filter out relationship changes that are irrelevant to current entry var entityRelationshipChanges = relationshipChanges .Where(change => change.EntitySet is AssociationSet) .Where(change => change.EntitySet.As<AssociationSet>() .AssociationSetEnds .Select(set => set.EntitySet.ElementType.FullName).Contains(entitySet.ElementType.FullName) ) .ToList(); var relationshipGroups = entityRelationshipChanges .SelectMany(change => { var values = change.State == EntityState.Added ? change.CurrentValues : change.OriginalValues; var valuesChangeSet = new object[values.FieldCount]; values.GetValues(valuesChangeSet); return valuesChangeSet .Select(value => value.As<EntityKey>()) .Where(value => value.EntitySetName != entitySet.Name) .Select(value => new Tuple<string, EntityState, EntityKey>(change.EntitySet.Name, change.State, value)); }) .GroupBy(t => t.Item1); foreach (var relationship in relationshipGroups) { var relationshipName = relationship.Key; var navigationProperty = navigationProperties .Where(p => p.RelationshipType.Name == relationshipName) .FirstOrDefault(); if (navigationProperty == null) { Logger.ErrorFormat("Unable to find navigation property for relationship {0} in entity {1}", relationshipName, entityType.Name); continue; } var propertyInfo = entityEntry.GetPropertyInfo(navigationProperty.Name); var shouldSaveProperty = IsAuditedPropertyInfo(propertyInfo) ?? !auditedPropertiesOnly; if (shouldSaveProperty) { var addedRelationship = relationship.FirstOrDefault(p => p.Item2 == EntityState.Added); var deletedRelationship = relationship.FirstOrDefault(p => p.Item2 == EntityState.Deleted); var newValue = addedRelationship?.Item3.EntityKeyValues.ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value); var oldValue = deletedRelationship?.Item3.EntityKeyValues.ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value); propertyChanges.Add(CreateEntityPropertyChange(oldValue, newValue, propertyInfo)); } } return propertyChanges; } /// <summary> /// Updates change time, entity id, Adds foreign keys, Removes/Updates property changes after SaveChanges is called. /// </summary> private void UpdateChangeSet(DbContext context, EntityChangeSet changeSet) { var entityChangesToRemove = new List<EntityChange>(); foreach (var entityChange in changeSet.EntityChanges) { var objectContext = context.As<IObjectContextAdapter>().ObjectContext; var entityEntry = entityChange.EntityEntry.As<DbEntityEntry>(); var typeOfEntity = entityEntry.GetEntityBaseType(); var isAuditedEntity = IsTypeOfAuditedEntity(typeOfEntity) == true; /* Update change time */ entityChange.ChangeTime = GetChangeTime(entityChange.ChangeType, entityEntry.Entity); /* Update entity id */ var entityType = GetEntityType(objectContext, typeOfEntity, useClrType: false); entityChange.EntityId = GetEntityId(entityEntry, entityType); /* Update property changes */ var trackedPropertyNames = entityChange.PropertyChanges.Select(pc => pc.PropertyName); var trackedNavigationProperties = entityType.NavigationProperties .Where(np => trackedPropertyNames.Contains(np.Name)) .ToList(); var additionalForeignKeys = trackedNavigationProperties .SelectMany(p => p.GetDependentProperties()) .Where(p => !trackedPropertyNames.Contains(p.Name)) .Distinct() .ToList(); /* Add additional foreign keys from navigation properties */ foreach (var foreignKey in additionalForeignKeys) { var propertyEntry = entityEntry.Property(foreignKey.Name); var propertyInfo = entityEntry.GetPropertyInfo(foreignKey.Name); var shouldSaveProperty = IsAuditedPropertyInfo(propertyInfo); if (shouldSaveProperty.HasValue && !shouldSaveProperty.Value) { continue; } // TODO: fix new value comparison before truncation var newValue = propertyEntry.GetNewValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength); var oldValue = propertyEntry.GetOriginalValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength); // Add foreign key entityChange.PropertyChanges.Add(CreateEntityPropertyChange(oldValue, newValue, propertyInfo)); } /* Update/Remove property changes */ var propertyChangesToRemove = new List<EntityPropertyChange>(); foreach (var propertyChange in entityChange.PropertyChanges) { var memberEntry = entityEntry.Member(propertyChange.PropertyName); if (!(memberEntry is DbPropertyEntry)) { // Skipping other types of properties // - Reference navigation properties (DbReferenceEntry) // - Collection navigation properties (DbCollectionEntry) continue; } var propertyEntry = memberEntry.As<DbPropertyEntry>(); var propertyInfo = entityEntry.GetPropertyInfo(propertyChange.PropertyName); var isAuditedProperty = IsAuditedPropertyInfo(propertyInfo) == true; // TODO: fix new value comparison before truncation propertyChange.NewValue = propertyEntry.GetNewValue()?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength); if (!isAuditedProperty && propertyChange.OriginalValue == propertyChange.NewValue) { // No change propertyChangesToRemove.Add(propertyChange); } } foreach (var propertyChange in propertyChangesToRemove) { entityChange.PropertyChanges.Remove(propertyChange); } if (!isAuditedEntity && entityChange.PropertyChanges.Count == 0) { entityChangesToRemove.Add(entityChange); } } foreach (var entityChange in entityChangesToRemove) { changeSet.EntityChanges.Remove(entityChange); } } private EntityPropertyChange CreateEntityPropertyChange(object oldValue, object newValue, PropertyInfo propertyInfo) { return new EntityPropertyChange() { OriginalValue = oldValue?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength), NewValue = newValue?.ToJsonString().TruncateWithPostfix(EntityPropertyChange.MaxValueLength), PropertyName = propertyInfo.Name.TruncateWithPostfix(EntityPropertyChange.MaxPropertyNameLength), PropertyTypeFullName = propertyInfo.PropertyType.FullName.TruncateWithPostfix(EntityPropertyChange.MaxPropertyTypeFullNameLength), TenantId = AbpSession.TenantId }; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="GeoTargetConstantServiceClient"/> instances.</summary> public sealed partial class GeoTargetConstantServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="GeoTargetConstantServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="GeoTargetConstantServiceSettings"/>.</returns> public static GeoTargetConstantServiceSettings GetDefault() => new GeoTargetConstantServiceSettings(); /// <summary> /// Constructs a new <see cref="GeoTargetConstantServiceSettings"/> object with default settings. /// </summary> public GeoTargetConstantServiceSettings() { } private GeoTargetConstantServiceSettings(GeoTargetConstantServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); SuggestGeoTargetConstantsSettings = existing.SuggestGeoTargetConstantsSettings; OnCopy(existing); } partial void OnCopy(GeoTargetConstantServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>GeoTargetConstantServiceClient.SuggestGeoTargetConstants</c> and /// <c>GeoTargetConstantServiceClient.SuggestGeoTargetConstantsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SuggestGeoTargetConstantsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="GeoTargetConstantServiceSettings"/> object.</returns> public GeoTargetConstantServiceSettings Clone() => new GeoTargetConstantServiceSettings(this); } /// <summary> /// Builder class for <see cref="GeoTargetConstantServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class GeoTargetConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<GeoTargetConstantServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public GeoTargetConstantServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public GeoTargetConstantServiceClientBuilder() { UseJwtAccessWithScopes = GeoTargetConstantServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref GeoTargetConstantServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GeoTargetConstantServiceClient> task); /// <summary>Builds the resulting client.</summary> public override GeoTargetConstantServiceClient Build() { GeoTargetConstantServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<GeoTargetConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<GeoTargetConstantServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private GeoTargetConstantServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return GeoTargetConstantServiceClient.Create(callInvoker, Settings); } private async stt::Task<GeoTargetConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return GeoTargetConstantServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => GeoTargetConstantServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => GeoTargetConstantServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => GeoTargetConstantServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>GeoTargetConstantService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch geo target constants. /// </remarks> public abstract partial class GeoTargetConstantServiceClient { /// <summary> /// The default endpoint for the GeoTargetConstantService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default GeoTargetConstantService scopes.</summary> /// <remarks> /// The default GeoTargetConstantService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="GeoTargetConstantServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="GeoTargetConstantServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="GeoTargetConstantServiceClient"/>.</returns> public static stt::Task<GeoTargetConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new GeoTargetConstantServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="GeoTargetConstantServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="GeoTargetConstantServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="GeoTargetConstantServiceClient"/>.</returns> public static GeoTargetConstantServiceClient Create() => new GeoTargetConstantServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="GeoTargetConstantServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="GeoTargetConstantServiceSettings"/>.</param> /// <returns>The created <see cref="GeoTargetConstantServiceClient"/>.</returns> internal static GeoTargetConstantServiceClient Create(grpccore::CallInvoker callInvoker, GeoTargetConstantServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } GeoTargetConstantService.GeoTargetConstantServiceClient grpcClient = new GeoTargetConstantService.GeoTargetConstantServiceClient(callInvoker); return new GeoTargetConstantServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC GeoTargetConstantService client</summary> public virtual GeoTargetConstantService.GeoTargetConstantServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns GeoTargetConstant suggestions by location name or by resource name. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [GeoTargetConstantSuggestionError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual SuggestGeoTargetConstantsResponse SuggestGeoTargetConstants(SuggestGeoTargetConstantsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns GeoTargetConstant suggestions by location name or by resource name. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [GeoTargetConstantSuggestionError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestGeoTargetConstantsResponse> SuggestGeoTargetConstantsAsync(SuggestGeoTargetConstantsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns GeoTargetConstant suggestions by location name or by resource name. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [GeoTargetConstantSuggestionError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestGeoTargetConstantsResponse> SuggestGeoTargetConstantsAsync(SuggestGeoTargetConstantsRequest request, st::CancellationToken cancellationToken) => SuggestGeoTargetConstantsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>GeoTargetConstantService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch geo target constants. /// </remarks> public sealed partial class GeoTargetConstantServiceClientImpl : GeoTargetConstantServiceClient { private readonly gaxgrpc::ApiCall<SuggestGeoTargetConstantsRequest, SuggestGeoTargetConstantsResponse> _callSuggestGeoTargetConstants; /// <summary> /// Constructs a client wrapper for the GeoTargetConstantService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="GeoTargetConstantServiceSettings"/> used within this client. /// </param> public GeoTargetConstantServiceClientImpl(GeoTargetConstantService.GeoTargetConstantServiceClient grpcClient, GeoTargetConstantServiceSettings settings) { GrpcClient = grpcClient; GeoTargetConstantServiceSettings effectiveSettings = settings ?? GeoTargetConstantServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callSuggestGeoTargetConstants = clientHelper.BuildApiCall<SuggestGeoTargetConstantsRequest, SuggestGeoTargetConstantsResponse>(grpcClient.SuggestGeoTargetConstantsAsync, grpcClient.SuggestGeoTargetConstants, effectiveSettings.SuggestGeoTargetConstantsSettings); Modify_ApiCall(ref _callSuggestGeoTargetConstants); Modify_SuggestGeoTargetConstantsApiCall(ref _callSuggestGeoTargetConstants); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_SuggestGeoTargetConstantsApiCall(ref gaxgrpc::ApiCall<SuggestGeoTargetConstantsRequest, SuggestGeoTargetConstantsResponse> call); partial void OnConstruction(GeoTargetConstantService.GeoTargetConstantServiceClient grpcClient, GeoTargetConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC GeoTargetConstantService client</summary> public override GeoTargetConstantService.GeoTargetConstantServiceClient GrpcClient { get; } partial void Modify_SuggestGeoTargetConstantsRequest(ref SuggestGeoTargetConstantsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns GeoTargetConstant suggestions by location name or by resource name. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [GeoTargetConstantSuggestionError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override SuggestGeoTargetConstantsResponse SuggestGeoTargetConstants(SuggestGeoTargetConstantsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestGeoTargetConstantsRequest(ref request, ref callSettings); return _callSuggestGeoTargetConstants.Sync(request, callSettings); } /// <summary> /// Returns GeoTargetConstant suggestions by location name or by resource name. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [GeoTargetConstantSuggestionError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<SuggestGeoTargetConstantsResponse> SuggestGeoTargetConstantsAsync(SuggestGeoTargetConstantsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestGeoTargetConstantsRequest(ref request, ref callSettings); return _callSuggestGeoTargetConstants.Async(request, callSettings); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Banshee.Base.Winforms.Controls { public partial class SearchEntry : UserControl { private ArrayList searchFields; public event EventHandler Changed; public event EventHandler EnterPress; public ArrayList SearchFields { get { return searchFields; } set { searchFields = value; } } public SearchEntry() { SetStyle(ControlStyles.OptimizedDoubleBuffer| ControlStyles.AllPaintingInWmPaint, true); InitializeComponent(); this.Width = 200; } void BuildMenu() { foreach (string menuLabel in searchFields) { ToolStripItem item = null; if (menuLabel.Equals("-")) { filter_menu.Items.Add(new ToolStripSeparator()); } else { item = new ToolStripMenuItem(menuLabel); item.Click += new EventHandler(item_Click); filter_menu.Items.Add(item); } } } ToolStripMenuItem activeItem; void item_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (activeItem == item) { item.Checked = true; } else { activeItem = item; } foreach (ToolStripItem iterItem in filter_menu.Items) { if (!(iterItem is ToolStripMenuItem)) { continue; } ToolStripMenuItem checkItem = iterItem as ToolStripMenuItem; if (checkItem != activeItem) { checkItem.Checked = false; } } activeItem.Checked = true; search_text.SelectAll(); OnChanged(this, new EventArgs()); } protected virtual void OnChanged(object o, EventArgs args) { if (Ready) { EventHandler handler = Changed; if (handler != null) { handler(o, args); } } } private void OnEntryActivated(object o, EventArgs args) { EventHandler handler = EnterPress; if (handler != null) { handler(this, new EventArgs()); } } public string Query { get { return search_text.Text.Trim(); } set { search_text.Text = value; } } public string Field { get { string field = string.Empty; for (int i = 0; i < filter_menu.Items.Count; i++) { if (filter_menu.Items[i].GetType() != typeof(ToolStripSeparator)) { ToolStripMenuItem item = (ToolStripMenuItem)filter_menu.Items[i]; if (item.Checked) field = item.Text; } } return field; } set { for (int i = 0; i < filter_menu.Items.Count; i++) { if (filter_menu.Items[i].GetType() != typeof(ToolStripSeparator)) { ToolStripMenuItem item = (ToolStripMenuItem)filter_menu.Items[i]; if (item.Text == value) item.Checked = true; else item.Checked = false; } } } } public void FocusSearch() { search_text.Focus(); } public bool HasFocus { get { return search_text.Focused; } } public bool IsQueryAvailable { get { return Query != null && Query != String.Empty; } } private bool ready; public bool Ready { get { return ready; } set { ready = value; } } private void search_text_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; e.Handled = true; OnChanged(sender, null); } } private void pictureBox1_Click(object sender, EventArgs e) { filter_menu.Show(search_text, new Point(0, search_text.Height)); } public void CancelSearch() { ToolStripMenuItem first = filter_menu.Items[0] as ToolStripMenuItem; if (!first.Checked) first.Checked = true; search_text.Text = string.Empty; } private void pictureBox2_Click(object sender, EventArgs e) { CancelSearch(); } private void SearchEntry_Load(object sender, EventArgs e) { ArrayList fields = new ArrayList(); fields.Add("All"); fields.Add("-"); fields.Add("Song Name"); fields.Add("Artist Name"); fields.Add("Album Title"); fields.Add("Genre"); fields.Add("Year"); searchFields = fields; BuildMenu(); activeItem = filter_menu.Items[0] as ToolStripMenuItem; } } }
using System; using System.Diagnostics; using System.Linq; using NUnit.Framework; using StructureMap.Testing.Configuration.DSL; using StructureMap.Testing.GenericWidgets; using StructureMap.Testing.Graph; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget2; namespace StructureMap.Testing.Query { [TestFixture] public class ModelIntegrationTester { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(x => { x.For(typeof (IService<>)).Add(typeof (Service<>)); x.For(typeof (IService<>)).Add(typeof (Service2<>)); x.For<IWidget>().Singleton().Use<AWidget>(); x.For<Rule>().AddInstances(o => { o.OfConcreteType<DefaultRule>(); o.OfConcreteType<ARule>(); o.OfConcreteType<ColorRule>().WithCtorArg("color").EqualTo("red"); }); x.For<IEngine>().Use<PushrodEngine>(); x.For<Startable1>().Singleton().Use<Startable1>(); x.For<Startable2>().Use<Startable2>(); x.For<Startable3>().Use<Startable3>(); }); } #endregion private Container container; [Test] public void can_iterate_through_families_including_both_generics_and_normal() { // +1 for "IContainer" itself + Func container.Model.PluginTypes.Count().ShouldEqual(9); container.Model.PluginTypes.Each(x => Debug.WriteLine(x.PluginType.FullName)); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_from_model() { container.Model.InstancesOf<Rule>().Count().ShouldEqual(3); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_that_is_not_registered() { container.Model.InstancesOf<IServiceProvider>().Count().ShouldEqual(0); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_generics() { container.Model.For(typeof (IService<>)).Instances.Count().ShouldEqual(2); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_generics_from_model() { container.Model.InstancesOf(typeof (IService<>)).Count().ShouldEqual(2); } [Test] public void default_type_for_from_the_top() { container.Model.DefaultTypeFor<IWidget>().ShouldEqual(typeof (AWidget)); container.Model.DefaultTypeFor<Rule>().ShouldBeNull(); } [Test] public void get_all_instances_from_the_top() { container.Model.AllInstances.Count().ShouldEqual(12); } [Test] public void get_all_possibles() { // Startable1 is a singleton var startable1 = container.GetInstance<Startable1>(); startable1.WasStarted.ShouldBeFalse(); container.Model.GetAllPossible<IStartable>() .ToArray() .Each(x => x.Start()) .Each(x => x.WasStarted.ShouldBeTrue()); startable1.WasStarted.ShouldBeTrue(); } [Test] public void has_default_implementation_from_the_top() { container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue(); container.Model.HasDefaultImplementationFor<Rule>().ShouldBeFalse(); container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse(); } [Test] public void has_implementation_from_the_top() { container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse(); container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue(); } [Test] public void has_implementations_should_be_false_for_a_type_that_is_not_registered() { container.Model.For<ISomething>().HasImplementations().ShouldBeFalse(); } [Test] public void remove_an_entire_closed_type() { container.Model.EjectAndRemove(typeof (Rule)); container.Model.HasImplementationsFor<Rule>().ShouldBeFalse(); container.TryGetInstance<Rule>().ShouldBeNull(); container.GetAllInstances<Rule>().Count.ShouldEqual(0); } [Test] public void remove_an_entire_closed_type_with_the_filter() { container.Model.EjectAndRemovePluginTypes(t => t == typeof (Rule) || t == typeof (IWidget)); container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse(); container.Model.HasImplementationsFor<Rule>().ShouldBeFalse(); container.Model.HasImplementationsFor<IEngine>().ShouldBeTrue(); } [Test] public void remove_an_open_type() { container.Model.EjectAndRemove(typeof (IService<>)); container.Model.HasImplementationsFor(typeof (IService<>)); container.TryGetInstance<IService<string>>().ShouldBeNull(); } [Test] public void remove_an_open_type_with_a_filter() { container.Model.EjectAndRemovePluginTypes(t => t == typeof (IService<>)); container.Model.HasImplementationsFor(typeof (IService<>)); container.TryGetInstance<IService<string>>().ShouldBeNull(); } [Test] public void remove_types_based_on_a_filter() { container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeTrue(); container.Model.HasImplementationsFor<IWidget>().ShouldBeTrue(); container.Model.EjectAndRemoveTypes(t => t == typeof (IWidget) || t == typeof (ARule)); container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeFalse(); container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse(); } } public interface IStartable { bool WasStarted { get; } void Start(); } public class Startable : IStartable { public void Start() { WasStarted = true; } public bool WasStarted { get; private set; } } public class Startable1 : Startable { } public class Startable2 : Startable { } public class Startable3 : Startable { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract001.abstract001 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public abstract class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract002.abstract002 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public abstract class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract003.abstract003 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public interface IFoo { void Foo(); } public abstract class Base { public abstract int Foo(dynamic o); } public class Derived : Base, IFoo { void IFoo.Foo() { Test.Status = 2; } public override int Foo(object o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); IFoo x = d as IFoo; d.Foo(2); if (Test.Status != 1) return 1; x.Foo(); if (Test.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract004.abstract004 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public abstract class Base { public abstract int Foo(object o); } public class Derived : Base { public override int Foo(dynamic o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract005.abstract005 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public abstract class Base { public abstract int Foo(dynamic o); } public class Derived : Base { public override int Foo(dynamic o) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(2); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual001.virtual001 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(object o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual002.virtual002 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(object d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual003.virtual003 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 2; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual004.virtual004 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(object o) { Test.Status = 3; return 1; } } public class Derived : Base { public override int Foo(dynamic d) { Test.Status = 2; return 1; } } public class FurtherDerived : Derived { public override int Foo(object d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { FurtherDerived d = new FurtherDerived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual005.virtual005 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int Foo(dynamic o) { Test.Status = 3; return 1; } } public class Derived : Base { public override int Foo(object d) { Test.Status = 2; return 1; } } public class FurtherDerived : Derived { public override int Foo(dynamic d) { Test.Status = 1; return 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { FurtherDerived d = new FurtherDerived(); d.Foo(3); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual006.virtual006 { // <Title>Classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public virtual int this[object o] { get { Test.Status = 2; return 2; } } } public class Derived : Base { public override int this[dynamic d] { get { Test.Status = 1; return 1; } } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Derived d = new Derived(); int x = d[3]; if (Test.Status != 1 || x != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename001.simplename001 { // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> ICE </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { public class C { public static int Bar(C t) { return 1; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic v2 = new C(); return (1 == Bar(v2)) ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename003.simplename003 { // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { public abstract class Base { protected static int result = 0; public static bool Bar(object o) { result = 1; return false; } public abstract int Foo(dynamic o); public virtual int Hoo(object o) { return 0; } public virtual int Poo(int n, dynamic o) { return 0; } } public class Derived : Base { public override int Foo(object o) { result = 2; return 0; } public new int Hoo(dynamic o) { result = 3; return 0; } public sealed override int Poo(int n, dynamic o) { result = 4; return 0; } public bool RunTest() { bool ret = true; dynamic d = new Derived(); Bar(d); ret &= (1 == result); Foo(d); ret &= (2 == result); Hoo(d); ret &= (3 == result); dynamic x = 100; Poo(x, d); ret &= (4 == result); return ret; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var v = new Derived(); return v.RunTest() ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename004.simplename004 { // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS { public struct MyType { public static int Bar<T>(object o) { return 1; } public int Foo<U>(object p1, object p2) { return 2; } public int Har<V>(object o, params int[] ary) { return 3; } public int Poo<W>(object p1, ref object p2, out dynamic p3) { p3 = default(dynamic); return 4; } public int Dar<Y>(object p1, int p2 = 100, long p3 = 200) { return 5; } public bool RunTest() { bool ret = true; dynamic d = null; ret &= (1 == Bar<string>(d)); ret &= (2 == Foo<double>(d, d)); d = new MyType(); dynamic d1 = 999; ret &= (1 == Bar<float>(d)); ret &= (2 == Foo<ulong>(d, d1)); ret &= (3 == Har<long>(d)); ret &= (4 == Poo<short>(d, ref d1, out d1)); ret &= (3 == Har<long>(d, d1)); ret &= (5 == Dar<char>(d)); ret &= (5 == Dar<char>(d, p2: 100)); ret &= (5 == Dar<char>(d, p3: 99, p2: 88)); return ret; } } public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var v = new MyType(); return v.RunTest() ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename005.simplename005 { // <Title>Classes - Simple Name (Method) Calling</Title> // <Description> ICE </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> namespace NS1 { public delegate void MyDel01(object p1); public delegate void MyDel02(string p1); public delegate bool MyDel03(object p1, string p2); public delegate bool MyDel04(string p1, string p2); public delegate void MyDel05(string p1, out int p2, ref long p3); public delegate void MyDel06(object p1, out int p2, ref long p3); public delegate int MyDel07(int p1, int p2 = -1, int p3 = -2); public delegate int MyDel08(object p1, byte p2 = 101); public delegate int MyDel09(object p1, int p2 = 1, long p3 = 2); public class Test { private static int s_result = -1; public void MyMtd01(object p1) { s_result = 1; } public void MyMtd02(string p1) { s_result = 2; } public bool MyMtd03(object p1, string p2) { s_result = 3; return true; } public bool MyMtd04(string p1, string p2) { s_result = 4; return false; } public void MyMtd05(string p1, out int p2, ref long p3) { s_result = 5; p2 = -30; } public void MyMtd06(object p1, out int p2, ref long p3) { s_result = 6; p2 = -40; } public int MyMtd07(int p1, int p2 = -10, int p3 = -20) { s_result = 7; return p3; } public int MyMtd08(object p1, byte p2 = 99) { s_result = 8; return 1; } public int MyMtd09(object p1, int p2 = 10, long p3 = 20) { s_result = 9; return p2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var t = new Test(); return (t.RunTest()) ? 0 : 1; } public bool RunTest() { dynamic v1 = new MyDel01(MyMtd01); dynamic d = null; dynamic d1 = "12345"; v1(d); bool ret = (1 == s_result); v1 = new MyDel02(MyMtd02); v1(d); ret &= (2 == s_result); v1 = new MyDel03(MyMtd03); v1(d, d1); ret &= (3 == s_result); v1 = new MyDel04(MyMtd04); v1(d, d1); ret &= (4 == s_result); d = 12345; v1 = new MyDel05(MyMtd05); //v1(d1, out d, ref d); // by design //ret &= (5 == result); v1 = new MyDel06(MyMtd06); //v1(d1, out d, ref d); //ret &= (6 == result); v1 = new MyDel07(MyMtd07); v1(d); ret &= (7 == s_result); s_result = -1; v1(d, p3: 100); ret &= (7 == s_result); s_result = -1; v1(d, p3: 100, p2: 200); ret &= (7 == s_result); d = null; v1 = new MyDel08(MyMtd08); v1(d); // ret &= (8 == s_result); v1 = new MyDel09(MyMtd09); v1(d); // ret &= (9 == s_result); return ret; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.memberaccess002.memberaccess002 { // <Title> Operator -.is, as</Title> // <Description>(By Design)</Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class A { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = DayOfWeek.Monday; try { var y = x.value__; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) // Should not EX { System.Console.WriteLine(e); return 1; } return 0; } } //</Code> }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.IO; using System.Reflection; namespace System.Diagnostics { // There is no good reason for the methods of this class to be virtual. public class StackFrame { private MethodBase method; private int offset; private int ILOffset; private String strFileName; private int iLineNumber; private int iColumnNumber; [System.Runtime.Serialization.OptionalField] private bool fIsLastFrameFromForeignExceptionStackTrace; internal void InitMembers() { method = null; offset = OFFSET_UNKNOWN; ILOffset = OFFSET_UNKNOWN; strFileName = null; iLineNumber = 0; iColumnNumber = 0; fIsLastFrameFromForeignExceptionStackTrace = false; } // Constructs a StackFrame corresponding to the active stack frame. public StackFrame() { InitMembers(); BuildStackFrame(0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0 } // Constructs a StackFrame corresponding to the active stack frame. public StackFrame(bool fNeedFileInfo) { InitMembers(); BuildStackFrame(0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0 } // Constructs a StackFrame corresponding to a calling stack frame. // public StackFrame(int skipFrames) { InitMembers(); BuildStackFrame(skipFrames + StackTrace.METHODS_TO_SKIP, false); } // Constructs a StackFrame corresponding to a calling stack frame. // public StackFrame(int skipFrames, bool fNeedFileInfo) { InitMembers(); BuildStackFrame(skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo); } // Called from the class "StackTrace" // internal StackFrame(bool DummyFlag1, bool DummyFlag2) { InitMembers(); } // Constructs a "fake" stack frame, just containing the given file // name and line number. Use when you don't want to use the // debugger's line mapping logic. // public StackFrame(String fileName, int lineNumber) { InitMembers(); BuildStackFrame(StackTrace.METHODS_TO_SKIP, false); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = 0; } // Constructs a "fake" stack frame, just containing the given file // name, line number and column number. Use when you don't want to // use the debugger's line mapping logic. // public StackFrame(String fileName, int lineNumber, int colNumber) { InitMembers(); BuildStackFrame(StackTrace.METHODS_TO_SKIP, false); strFileName = fileName; iLineNumber = lineNumber; iColumnNumber = colNumber; } // Constant returned when the native or IL offset is unknown public const int OFFSET_UNKNOWN = -1; internal virtual void SetMethodBase(MethodBase mb) { method = mb; } internal virtual void SetOffset(int iOffset) { offset = iOffset; } internal virtual void SetILOffset(int iOffset) { ILOffset = iOffset; } internal virtual void SetFileName(String strFName) { strFileName = strFName; } internal virtual void SetLineNumber(int iLine) { iLineNumber = iLine; } internal virtual void SetColumnNumber(int iCol) { iColumnNumber = iCol; } internal virtual void SetIsLastFrameFromForeignExceptionStackTrace(bool fIsLastFrame) { fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame; } internal virtual bool GetIsLastFrameFromForeignExceptionStackTrace() { return fIsLastFrameFromForeignExceptionStackTrace; } // Returns the method the frame is executing // public virtual MethodBase GetMethod() { return method; } // Returns the offset from the start of the native (jitted) code for the // method being executed // public virtual int GetNativeOffset() { return offset; } // Returns the offset from the start of the IL code for the // method being executed. This offset may be approximate depending // on whether the jitter is generating debuggable code or not. // public virtual int GetILOffset() { return ILOffset; } // Returns the file name containing the code being executed. This // information is normally extracted from the debugging symbols // for the executable. // public virtual String GetFileName() { return strFileName; } // Returns the line number in the file containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileLineNumber() { return iLineNumber; } // Returns the column number in the line containing the code being executed. // This information is normally extracted from the debugging symbols // for the executable. // public virtual int GetFileColumnNumber() { return iColumnNumber; } // Builds a readable representation of the stack frame // public override String ToString() { StringBuilder sb = new StringBuilder(255); if (method != null) { sb.Append(method.Name); // deal with the generic portion of the method if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod) { Type[] typars = ((MethodInfo)method).GetGenericArguments(); sb.Append('<'); int k = 0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(','); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append('>'); } sb.Append(" at offset "); if (offset == OFFSET_UNKNOWN) sb.Append("<offset unknown>"); else sb.Append(offset); sb.Append(" in file:line:column "); bool useFileName = (strFileName != null); if (!useFileName) sb.Append("<filename unknown>"); else sb.Append(strFileName); sb.Append(':'); sb.Append(iLineNumber); sb.Append(':'); sb.Append(iColumnNumber); } else { sb.Append("<null>"); } sb.Append(Environment.NewLine); return sb.ToString(); } private void BuildStackFrame(int skipFrames, bool fNeedFileInfo) { using (StackFrameHelper StackF = new StackFrameHelper(null)) { StackF.InitializeSourceInfo(0, fNeedFileInfo, null); int iNumOfFrames = StackF.GetNumberOfFrames(); skipFrames += StackTrace.CalculateFramesToSkip(StackF, iNumOfFrames); if ((iNumOfFrames - skipFrames) > 0) { method = StackF.GetMethodBase(skipFrames); offset = StackF.GetOffset(skipFrames); ILOffset = StackF.GetILOffset(skipFrames); if (fNeedFileInfo) { strFileName = StackF.GetFilename(skipFrames); iLineNumber = StackF.GetLineNumber(skipFrames); iColumnNumber = StackF.GetColumnNumber(skipFrames); } } } } } }
using System; using i64 = System.Int64; using u32 = System.UInt32; using u8 = System.Byte; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement a pseudo-random number ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* All threads share a single random number generator. ** This structure is the current state of the generator. */ public class sqlite3PrngType { public bool isInit; /* True if initialized */ public int i; public int j; /* State variables */ public u8[] s = new u8[256]; /* State variables */ public sqlite3PrngType Copy() { sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone(); cp.s = new u8[s.Length]; Array.Copy(s, cp.s, s.Length); return cp; } } public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType(); /* ** Get a single 8-bit random value from the RC4 PRNG. The Mutex ** must be held while executing this routine. ** ** Why not just use a library random generator like lrand48() for this? ** Because the OP_NewRowid opcode in the VDBE depends on having a very ** good source of random numbers. The lrand48() library function may ** well be good enough. But maybe not. Or maybe lrand48() has some ** subtle problems on some systems that could cause problems. It is hard ** to know. To minimize the risk of problems due to bad lrand48() ** implementations, SQLite uses this random number generator based ** on RC4, which we know works very well. ** ** (Later): Actually, OP_NewRowid does not depend on a good source of ** randomness any more. But we will leave this code in all the same. */ private static u8 randomu8() { u8 t; /* The "wsdPrng" macro will resolve to the pseudo-random number generator ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly ** to the "sqlite3Prng" state vector declared above. */ #if SQLITE_OMIT_WSD struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); //# define wsdPrng p[0] #else //# define wsdPrng sqlite3Prng sqlite3PrngType wsdPrng = sqlite3Prng; #endif /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ if (!wsdPrng.isInit) { int i; u8[] k = new u8[256]; wsdPrng.j = 0; wsdPrng.i = 0; sqlite3OsRandomness(sqlite3_vfs_find(""), 256, k); for (i = 0; i < 255; i++) { wsdPrng.s[i] = (u8)i; } for (i = 0; i < 255; i++) { wsdPrng.j = (u8)(wsdPrng.j + wsdPrng.s[i] + k[i]); t = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; wsdPrng.s[i] = t; } wsdPrng.isInit = true; } /* Generate and return single random u8 */ wsdPrng.i++; t = wsdPrng.s[(u8)wsdPrng.i]; wsdPrng.j = (u8)(wsdPrng.j + t); wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = t; t += wsdPrng.s[(u8)wsdPrng.i]; return wsdPrng.s[t]; } /* ** Return N random u8s. */ private static void sqlite3_randomness(int N, ref i64 pBuf) { //u8[] zBuf = new u8[N]; pBuf = 0; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif sqlite3_mutex_enter(mutex); while (N-- > 0) { pBuf = (u32)((pBuf << 8) + randomu8());// zBuf[N] = randomu8(); } sqlite3_mutex_leave(mutex); } private static void sqlite3_randomness(byte[] pBuf, int Offset, int N) { i64 iBuf = System.DateTime.Now.Ticks; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif sqlite3_mutex_enter(mutex); while (N-- > 0) { iBuf = (u32)((iBuf << 8) + randomu8());// zBuf[N] = randomu8(); pBuf[Offset++] = (byte)iBuf; } sqlite3_mutex_leave(mutex); } #if !SQLITE_OMIT_BUILTIN_TEST /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** ** The sqlite3_test_control() interface calls these routines to ** control the PRNG. */ private static sqlite3PrngType sqlite3SavedPrng = null; private static void sqlite3PrngSaveState() { sqlite3SavedPrng = sqlite3Prng.Copy(); // memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // sizeof(sqlite3Prng) //); } private static void sqlite3PrngRestoreState() { sqlite3Prng = sqlite3SavedPrng.Copy(); //memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // sizeof(sqlite3Prng) //); } private static void sqlite3PrngResetState() { sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } }
namespace KabMan.Client { partial class frmServerListe { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmServerListe)); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.btnNeu = new DevExpress.XtraBars.BarButtonItem(); this.btnDetail = new DevExpress.XtraBars.BarButtonItem(); this.btnLoeschen = new DevExpress.XtraBars.BarButtonItem(); this.btnListe = new DevExpress.XtraBars.BarButtonItem(); this.btnErstellen = new DevExpress.XtraBars.BarButtonItem(); this.barSubItem1 = new DevExpress.XtraBars.BarSubItem(); this.barCheckItem1 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem2 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem3 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem4 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem5 = new DevExpress.XtraBars.BarCheckItem(); this.btnSchliessen = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem3 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem4 = new DevExpress.XtraBars.BarButtonItem(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.ServerId = new DevExpress.XtraGrid.Columns.GridColumn(); this.ServerName = new DevExpress.XtraGrid.Columns.GridColumn(); this.OPSys = new DevExpress.XtraGrid.Columns.GridColumn(); this.LocationName = new DevExpress.XtraGrid.Columns.GridColumn(); this.Standort = new DevExpress.XtraGrid.Columns.GridColumn(); this.Size = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.popupMenu1 = new DevExpress.XtraBars.PopupMenu(this.components); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.AllowCustomization = false; this.barManager1.AllowQuickCustomization = false; this.barManager1.AllowShowToolbarsPopup = false; this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.btnNeu, this.btnDetail, this.btnLoeschen, this.btnSchliessen, this.barButtonItem1, this.barButtonItem2, this.barButtonItem3, this.barButtonItem4, this.btnListe, this.btnErstellen, this.barSubItem1, this.barCheckItem1, this.barCheckItem2, this.barCheckItem3, this.barCheckItem4, this.barCheckItem5}); this.barManager1.MaxItemId = 16; // // bar1 // this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnNeu), new DevExpress.XtraBars.LinkPersistInfo(this.btnDetail), new DevExpress.XtraBars.LinkPersistInfo(this.btnLoeschen), new DevExpress.XtraBars.LinkPersistInfo(this.btnListe, true), new DevExpress.XtraBars.LinkPersistInfo(this.btnErstellen, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem1, true), new DevExpress.XtraBars.LinkPersistInfo(this.btnSchliessen, true)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; resources.ApplyResources(this.bar1, "bar1"); // // btnNeu // resources.ApplyResources(this.btnNeu, "btnNeu"); this.btnNeu.Glyph = global::KabMan.Client.Properties.Resources.neu; this.btnNeu.Id = 0; this.btnNeu.Name = "btnNeu"; this.btnNeu.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnNeu_ItemClick); // // btnDetail // resources.ApplyResources(this.btnDetail, "btnDetail"); this.btnDetail.Glyph = global::KabMan.Client.Properties.Resources.detail; this.btnDetail.Id = 1; this.btnDetail.Name = "btnDetail"; this.btnDetail.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnDetail_ItemClick); // // btnLoeschen // resources.ApplyResources(this.btnLoeschen, "btnLoeschen"); this.btnLoeschen.Glyph = global::KabMan.Client.Properties.Resources.loeschen; this.btnLoeschen.Id = 2; this.btnLoeschen.Name = "btnLoeschen"; this.btnLoeschen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnLoeschen_ItemClick); // // btnListe // resources.ApplyResources(this.btnListe, "btnListe"); this.btnListe.Glyph = global::KabMan.Client.Properties.Resources.form_green; this.btnListe.Id = 8; this.btnListe.Name = "btnListe"; this.btnListe.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; this.btnListe.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnListe_ItemClick); // // btnErstellen // resources.ApplyResources(this.btnErstellen, "btnErstellen"); this.btnErstellen.Id = 9; this.btnErstellen.Name = "btnErstellen"; this.btnErstellen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnErstellen_ItemClick); // // barSubItem1 // resources.ApplyResources(this.barSubItem1, "barSubItem1"); this.barSubItem1.Id = 10; this.barSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem4), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem5)}); this.barSubItem1.Name = "barSubItem1"; // // barCheckItem1 // resources.ApplyResources(this.barCheckItem1, "barCheckItem1"); this.barCheckItem1.Checked = true; this.barCheckItem1.Id = 11; this.barCheckItem1.Name = "barCheckItem1"; this.barCheckItem1.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem1_CheckedChanged); // // barCheckItem2 // resources.ApplyResources(this.barCheckItem2, "barCheckItem2"); this.barCheckItem2.Checked = true; this.barCheckItem2.Id = 12; this.barCheckItem2.Name = "barCheckItem2"; this.barCheckItem2.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem2_CheckedChanged); // // barCheckItem3 // resources.ApplyResources(this.barCheckItem3, "barCheckItem3"); this.barCheckItem3.Checked = true; this.barCheckItem3.Id = 13; this.barCheckItem3.Name = "barCheckItem3"; this.barCheckItem3.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem3_CheckedChanged); // // barCheckItem4 // resources.ApplyResources(this.barCheckItem4, "barCheckItem4"); this.barCheckItem4.Checked = true; this.barCheckItem4.Id = 14; this.barCheckItem4.Name = "barCheckItem4"; this.barCheckItem4.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem4_CheckedChanged); // // barCheckItem5 // resources.ApplyResources(this.barCheckItem5, "barCheckItem5"); this.barCheckItem5.Checked = true; this.barCheckItem5.Id = 15; this.barCheckItem5.Name = "barCheckItem5"; this.barCheckItem5.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem5_CheckedChanged); // // btnSchliessen // resources.ApplyResources(this.btnSchliessen, "btnSchliessen"); this.btnSchliessen.Glyph = global::KabMan.Client.Properties.Resources.exit; this.btnSchliessen.Id = 3; this.btnSchliessen.Name = "btnSchliessen"; this.btnSchliessen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnSchliessen_ItemClick); // // barButtonItem1 // resources.ApplyResources(this.barButtonItem1, "barButtonItem1"); this.barButtonItem1.Id = 4; this.barButtonItem1.Name = "barButtonItem1"; // // barButtonItem2 // resources.ApplyResources(this.barButtonItem2, "barButtonItem2"); this.barButtonItem2.Id = 5; this.barButtonItem2.Name = "barButtonItem2"; // // barButtonItem3 // resources.ApplyResources(this.barButtonItem3, "barButtonItem3"); this.barButtonItem3.Id = 6; this.barButtonItem3.Name = "barButtonItem3"; // // barButtonItem4 // resources.ApplyResources(this.barButtonItem4, "barButtonItem4"); this.barButtonItem4.Id = 7; this.barButtonItem4.Name = "barButtonItem4"; // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Controls.Add(this.gridControl1); resources.ApplyResources(this.layoutControl1, "layoutControl1"); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; // // gridControl1 // this.gridControl1.EmbeddedNavigator.Name = ""; resources.ApplyResources(this.gridControl1, "gridControl1"); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); this.gridControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.gridControl1_MouseDoubleClick); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.ServerId, this.ServerName, this.OPSys, this.LocationName, this.Standort, this.Size}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // ServerId // resources.ApplyResources(this.ServerId, "ServerId"); this.ServerId.FieldName = "ServerId"; this.ServerId.Name = "ServerId"; // // ServerName // resources.ApplyResources(this.ServerName, "ServerName"); this.ServerName.FieldName = "ServerName"; this.ServerName.Name = "ServerName"; // // OPSys // resources.ApplyResources(this.OPSys, "OPSys"); this.OPSys.FieldName = "OPSys"; this.OPSys.Name = "OPSys"; // // LocationName // resources.ApplyResources(this.LocationName, "LocationName"); this.LocationName.FieldName = "LocationName"; this.LocationName.Name = "LocationName"; // // Standort // resources.ApplyResources(this.Standort, "Standort"); this.Standort.FieldName = "Standort"; this.Standort.Name = "Standort"; // // Size // resources.ApplyResources(this.Size, "Size"); this.Size.FieldName = "Size"; this.Size.Name = "Size"; // // layoutControlGroup1 // resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1"); this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(540, 318); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1"); this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(538, 316); this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // popupMenu1 // this.popupMenu1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem4, true)}); this.popupMenu1.Manager = this.barManager1; this.popupMenu1.Name = "popupMenu1"; // // frmServerListe // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "frmServerListe"; this.Load += new System.EventHandler(this.frmServerListe_Load); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraBars.BarButtonItem btnNeu; private DevExpress.XtraBars.BarButtonItem btnDetail; private DevExpress.XtraBars.BarButtonItem btnLoeschen; private DevExpress.XtraBars.BarButtonItem btnSchliessen; private DevExpress.XtraGrid.Columns.GridColumn ServerId; private DevExpress.XtraGrid.Columns.GridColumn ServerName; private DevExpress.XtraGrid.Columns.GridColumn OPSys; private DevExpress.XtraBars.PopupMenu popupMenu1; private DevExpress.XtraBars.BarButtonItem barButtonItem1; private DevExpress.XtraBars.BarButtonItem barButtonItem2; private DevExpress.XtraBars.BarButtonItem barButtonItem3; private DevExpress.XtraBars.BarButtonItem barButtonItem4; private DevExpress.XtraGrid.Columns.GridColumn LocationName; private DevExpress.XtraBars.BarButtonItem btnListe; private DevExpress.XtraGrid.Columns.GridColumn Standort; private DevExpress.XtraGrid.Columns.GridColumn Size; private DevExpress.XtraBars.BarButtonItem btnErstellen; private DevExpress.XtraBars.BarSubItem barSubItem1; private DevExpress.XtraBars.BarCheckItem barCheckItem1; private DevExpress.XtraBars.BarCheckItem barCheckItem2; private DevExpress.XtraBars.BarCheckItem barCheckItem3; private DevExpress.XtraBars.BarCheckItem barCheckItem4; private DevExpress.XtraBars.BarCheckItem barCheckItem5; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Collections.Generic; using Xunit; namespace System.Reflection.Tests { public static partial class ModuleTests { [Fact] public static void LoadMultiModuleFromDisk_GetModule() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("Bob.netmodule"); Assert.Equal(a, m.Assembly); Assert.Equal(bobNetModulePath, m.FullyQualifiedName); Assert.Equal(Path.GetFileName(bobNetModulePath), m.Name); Assert.Equal(TestData.s_JoeScopeName, m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleCaseInsensitive() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("bOB.nEtmODule"); Assert.Equal(a, m.Assembly); Assert.Equal(bobNetModulePath, m.FullyQualifiedName); Assert.Equal(Path.GetFileName(bobNetModulePath), m.Name); Assert.Equal(TestData.s_JoeScopeName, m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNameNotInManifest() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("NotThere.netmodule"); Assert.Null(m); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNameNotThere() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Assert.Throws<FileNotFoundException>(() => a.GetModule("Bob.netmodule")); } } } [Fact] public static void LoadMultiModuleFromDisk_Twice() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m1 = a.GetModule("Bob.netmodule"); Module m2 = a.GetModule("bob.netmodule"); Assert.Equal(m1, m2); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleManifest() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("Main.dll"); Assert.Equal(a.ManifestModule, m); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNull() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Assert.Throws<ArgumentNullException>(() => a.GetModule(null)); } } } [Fact] public static void LoadMultiModuleFromByteArray_GetModule() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<FileNotFoundException>(() => a.GetModule("Bob.netmodule")); } } [Theory] [InlineData(new object[] { false })] [InlineData(new object[] { true })] public static void MultiModule_GetModules(bool getResourceModules) { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module[] ms = a.GetModules(getResourceModules: getResourceModules); Assert.Equal(2, ms.Length); Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Assert.Contains<Module>(a.ManifestModule, ms); Assert.Contains<Module>(bob, ms); } } } [Fact] public static void LoadModule_Null() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentNullException>(() => a.LoadModule(null, TestData.s_JoeNetModuleImage)); Assert.Throws<ArgumentNullException>(() => a.LoadModule("Bob.netmodule", null)); } } [Fact] public static void LoadModule_CannotLoadModuleManifestModule() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentException>(() => a.LoadModule("Main.dll", TestData.s_JoeNetModuleImage)); } } [Fact] public static void LoadModule_CannotLoadModuleNotInManifest() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentException>(() => a.LoadModule("NotInManifest.dll", TestData.s_JoeNetModuleImage)); } } [Theory] [InlineData("Bob.netmodule")] [InlineData("bOB.NETMODULE")] public static void LoadModule(string moduleName) { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m = a.LoadModule(moduleName, TestData.s_JoeNetModuleImage); Module m1 = a.GetModule(moduleName); Assert.NotNull(m); Assert.Equal(m, m1); Assert.Equal(a, m.Assembly); Assert.Equal("<unknown>", m.FullyQualifiedName); Assert.Equal("<unknown>", m.Name); Assert.Equal("Joe.netmodule", m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } [Fact] public static void LoadModuleTwiceQuirk() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); Module m2 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); Module winner = a.GetModule("Bob.netmodule"); Assert.NotNull(winner); Assert.Equal(winner, m1); // Compat quirk: Why does the second Assembly.LoadModule() call not return the module that actually won the race // like the LoadAssemblyFrom() apis do? Assert.NotEqual(m1, m2); } } [Fact] public static void ModuleResolveEvent() { using (TypeLoader tl = new TypeLoader()) { Module moduleReturnedFromEventHandler = null; Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); a.ModuleResolve += delegate (object sender, ResolveEventArgs e) { Assert.Same(a, sender); Assert.Null(moduleReturnedFromEventHandler); // We're not doing anything to cause this to trigger twice! Assert.Equal("Bob.netmodule", e.Name); moduleReturnedFromEventHandler = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); return moduleReturnedFromEventHandler; }; Module m = a.GetModule("Bob.netmodule"); Assert.NotNull(m); Assert.Equal(moduleReturnedFromEventHandler, m); // Make sure the event doesn't get raised twice. For a single-threaded case like this, that's a reasonable assumption. Module m1 = a.GetModule("Bob.netmodule"); } } [Fact] public static void MultiModule_AssemblyGetTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Type[] types = a.GetTypes(); AssertContentsOfMultiModule(types, a); } } } [Fact] public static void MultiModule_AssemblyDefinedTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Type[] types = a.DefinedTypes.ToArray(); AssertContentsOfMultiModule(types, a); } } } [Fact] public static void MultiModule_AssemblyGetTypes_ReturnsDifferentObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetTypes()); } } } [Fact] public static void MultiModule_AssemblyDefinedTypes_ReturnsDifferentObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.DefinedTypes); } } } [Fact] public static void ModuleGetTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Type[] types = a.ManifestModule.GetTypes(); Assert.Equal(2, types.Length); AssertMainModuleTypesFound(types, a); Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Type[] bobTypes = bob.GetTypes(); Assert.Equal(2, bobTypes.Length); AssertBobModuleTypesFound(bobTypes, a); } } } [Fact] public static void ModuleGetTypesReturnsNewObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.ManifestModule.GetTypes()); } } } [Fact] public static void CrossModuleTypeRefResolution() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module bob = a.GetModule("Bob.netmodule"); Type mainType1 = a.ManifestModule.GetType("MainType1", throwOnError: true, ignoreCase: false); Type baseType = mainType1.BaseType; Assert.Equal("JoeType1", baseType.FullName); Assert.Equal(bob, baseType.Module); } } } private static void AssertContentsOfMultiModule(Type[] types, Assembly a) { Assert.Equal(4, types.Length); AssertMainModuleTypesFound(types, a); AssertBobModuleTypesFound(types, a); } private static void AssertMainModuleTypesFound(Type[] types, Assembly a) { Assert.Contains(types, (t) => t.Module == a.ManifestModule && t.FullName == "MainType1"); Assert.Contains(types, (t) => t.Module == a.ManifestModule && t.FullName == "MainType2"); } private static void AssertBobModuleTypesFound(Type[] types, Assembly a) { Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Assert.Contains(types, (t) => t.Module == bob && t.FullName == "JoeType1"); Assert.Contains(types, (t) => t.Module == bob && t.FullName == "JoeType2"); } [Fact] public static void ResourceOnlyModules() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string myRes1Path = Path.Combine(td.Path, "MyRes1"); string myRes2Path = Path.Combine(td.Path, "MyRes2"); string myRes3Path = Path.Combine(td.Path, "MyRes3"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInManifestFilesImage); File.WriteAllBytes(myRes1Path, TestData.s_MyRes1); File.WriteAllBytes(myRes2Path, TestData.s_MyRes2); File.WriteAllBytes(myRes3Path, TestData.s_MyRes3); using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module[] modules1 = a.GetModules(getResourceModules: false); Assert.Equal<Module>(new Module[] { a.ManifestModule }, modules1); Module[] modules2 = a.GetModules(getResourceModules: true); Assert.Equal(4, modules2.Length); Module m = a.GetModule("MyRes2"); Assert.NotNull(m); Assert.True(m.IsResource()); Assert.Throws<InvalidOperationException>(() => m.ModuleVersionId); Assert.Equal(0, m.MetadataToken); Assert.Equal("MyRes2", m.ScopeName); Assert.Equal("MyRes2", m.Name); Assert.Equal(myRes2Path, m.FullyQualifiedName); m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine); Assert.Equal(PortableExecutableKinds.NotAPortableExecutableImage, peKind); Assert.Equal(default(ImageFileMachine), machine); Assert.True(!m.GetCustomAttributesData().Any()); const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; Assert.Null(m.GetField("ANY", bf)); Assert.Null(m.GetMethod("ANY")); Assert.True(!m.GetFields(bf).Any()); Assert.True(!m.GetMethods(bf).Any()); Assert.True(!m.GetTypes().Any()); } } } [Fact] public static void GetLoadModules1() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); { Module[] loadedModules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(1, loadedModules.Length); Assert.Equal(a.ManifestModule, loadedModules[0]); } { Module[] loadedModules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(1, loadedModules.Length); Assert.Equal(a.ManifestModule, loadedModules[0]); } Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); { Module[] loadedModules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(2, loadedModules.Length); Assert.Contains<Module>(a.ManifestModule, loadedModules); Assert.Contains<Module>(m1, loadedModules); } { Module[] loadedModules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(2, loadedModules.Length); Assert.Contains<Module>(a.ManifestModule, loadedModules); Assert.Contains<Module>(m1, loadedModules); } } } [Fact] public static void GetLoadModules2() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string myRes1Path = Path.Combine(td.Path, "MyRes1"); string myRes2Path = Path.Combine(td.Path, "MyRes2"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInManifestFilesImage); File.WriteAllBytes(myRes1Path, TestData.s_MyRes1); File.WriteAllBytes(myRes2Path, TestData.s_MyRes2); using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromAssemblyPath(assemblyPath); Module res1 = a.GetModule("MyRes1"); Module res2 = a.GetModule("MyRes2"); { Module[] modules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(3, modules.Length); Assert.Contains<Module>(a.ManifestModule, modules); Assert.Contains<Module>(res1, modules); Assert.Contains<Module>(res2, modules); } { Module[] modules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(1, modules.Length); Assert.Equal(a.ManifestModule, modules[0]); } } } } [Fact] public static void GetLoadModulesReturnsUniqueArrays() { using (TypeLoader tl = new TypeLoader()) { Assembly a = tl.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetLoadedModules(getResourceModules: true)); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetLoadedModules(getResourceModules: 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 ArrayArrayLengthTests { #region Boolean tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckBoolArrayArrayLengthTest(bool useInterpreter) { CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(0), useInterpreter); CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(1), useInterpreter); CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionBoolArrayArrayLengthTest(bool useInterpreter) { CheckExceptionBoolArrayArrayLength(null, useInterpreter); } #endregion #region Byte tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckByteArrayArrayLengthTest(bool useInterpreter) { CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(0), useInterpreter); CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(1), useInterpreter); CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionByteArrayArrayLengthTest(bool useInterpreter) { CheckExceptionByteArrayArrayLength(null, useInterpreter); } #endregion #region Custom tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckCustomArrayArrayLengthTest(bool useInterpreter) { CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(0), useInterpreter); CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(1), useInterpreter); CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionCustomArrayArrayLengthTest(bool useInterpreter) { CheckExceptionCustomArrayArrayLength(null, useInterpreter); } #endregion #region Char tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckCharArrayArrayLengthTest(bool useInterpreter) { CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(0), useInterpreter); CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(1), useInterpreter); CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionCharArrayArrayLengthTest(bool useInterpreter) { CheckExceptionCharArrayArrayLength(null, useInterpreter); } #endregion #region Custom2 tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckCustom2ArrayArrayLengthTest(bool useInterpreter) { CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(0), useInterpreter); CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(1), useInterpreter); CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionCustom2ArrayArrayLengthTest(bool useInterpreter) { CheckExceptionCustom2ArrayArrayLength(null, useInterpreter); } #endregion #region Decimal tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckDecimalArrayArrayLengthTest(bool useInterpreter) { CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(0), useInterpreter); CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(1), useInterpreter); CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionDecimalArrayArrayLengthTest(bool useInterpreter) { CheckExceptionDecimalArrayArrayLength(null, useInterpreter); } #endregion #region Delegate tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckDelegateArrayArrayLengthTest(bool useInterpreter) { CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(0), useInterpreter); CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(1), useInterpreter); CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionDelegateArrayArrayLengthTest(bool useInterpreter) { CheckExceptionDelegateArrayArrayLength(null, useInterpreter); } #endregion #region Double tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckDoubleArrayArrayLengthTest(bool useInterpreter) { CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(0), useInterpreter); CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(1), useInterpreter); CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionDoubleArrayArrayLengthTest(bool useInterpreter) { CheckExceptionDoubleArrayArrayLength(null, useInterpreter); } #endregion #region Enum tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckEnumArrayArrayLengthTest(bool useInterpreter) { CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(0), useInterpreter); CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(1), useInterpreter); CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionEnumArrayArrayLengthTest(bool useInterpreter) { CheckExceptionEnumArrayArrayLength(null, useInterpreter); } #endregion #region EnumLong tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckEnumLongArrayArrayLengthTest(bool useInterpreter) { CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(0), useInterpreter); CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(1), useInterpreter); CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionEnumLongArrayArrayLengthTest(bool useInterpreter) { CheckExceptionEnumLongArrayArrayLength(null, useInterpreter); } #endregion #region Float tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckFloatArrayArrayLengthTest(bool useInterpreter) { CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(0), useInterpreter); CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(1), useInterpreter); CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionFloatArrayArrayLengthTest(bool useInterpreter) { CheckExceptionFloatArrayArrayLength(null, useInterpreter); } #endregion #region Func tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckFuncArrayArrayLengthTest(bool useInterpreter) { CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(0), useInterpreter); CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(1), useInterpreter); CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionFuncArrayArrayLengthTest(bool useInterpreter) { CheckExceptionFuncArrayArrayLength(null, useInterpreter); } #endregion #region Interface tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckInterfaceArrayArrayLengthTest(bool useInterpreter) { CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(0), useInterpreter); CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(1), useInterpreter); CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionInterfaceArrayArrayLengthTest(bool useInterpreter) { CheckExceptionInterfaceArrayArrayLength(null, useInterpreter); } #endregion #region IEquatableCustom tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckIEquatableCustomArrayArrayLengthTest(bool useInterpreter) { CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(0), useInterpreter); CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(1), useInterpreter); CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionIEquatableCustomArrayArrayLengthTest(bool useInterpreter) { CheckExceptionIEquatableCustomArrayArrayLength(null, useInterpreter); } #endregion #region IEquatableCustom2 tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter) { CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(0), useInterpreter); CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(1), useInterpreter); CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter) { CheckExceptionIEquatableCustom2ArrayArrayLength(null, useInterpreter); } #endregion #region Int tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckIntArrayArrayLengthTest(bool useInterpreter) { CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(0), useInterpreter); CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(1), useInterpreter); CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionIntArrayArrayLengthTest(bool useInterpreter) { CheckExceptionIntArrayArrayLength(null, useInterpreter); } #endregion #region Long tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckLongArrayArrayLengthTest(bool useInterpreter) { CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(0), useInterpreter); CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(1), useInterpreter); CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionLongArrayArrayLengthTest(bool useInterpreter) { CheckExceptionLongArrayArrayLength(null, useInterpreter); } #endregion #region Object tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckObjectArrayArrayLengthTest(bool useInterpreter) { CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(0), useInterpreter); CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(1), useInterpreter); CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionObjectArrayArrayLengthTest(bool useInterpreter) { CheckExceptionObjectArrayArrayLength(null, useInterpreter); } #endregion #region Struct tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStructArrayArrayLengthTest(bool useInterpreter) { CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(0), useInterpreter); CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(1), useInterpreter); CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStructArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStructArrayArrayLength(null, useInterpreter); } #endregion #region SByte tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckSByteArrayArrayLengthTest(bool useInterpreter) { CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(0), useInterpreter); CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(1), useInterpreter); CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionSByteArrayArrayLengthTest(bool useInterpreter) { CheckExceptionSByteArrayArrayLength(null, useInterpreter); } #endregion #region StructWithString tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStructWithStringArrayArrayLengthTest(bool useInterpreter) { CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(0), useInterpreter); CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(1), useInterpreter); CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStructWithStringArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStructWithStringArrayArrayLength(null, useInterpreter); } #endregion #region StructWithStringAndValue tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter) { CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(0), useInterpreter); CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(1), useInterpreter); CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStructWithStringAndValueArrayArrayLength(null, useInterpreter); } #endregion #region Short tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckShortArrayArrayLengthTest(bool useInterpreter) { CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(0), useInterpreter); CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(1), useInterpreter); CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionShortArrayArrayLengthTest(bool useInterpreter) { CheckExceptionShortArrayArrayLength(null, useInterpreter); } #endregion #region StructWithTwoValues tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter) { CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(0), useInterpreter); CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(1), useInterpreter); CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStructWithTwoValuesArrayArrayLength(null, useInterpreter); } #endregion #region StructWithValue tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStructWithValueArrayArrayLengthTest(bool useInterpreter) { CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(0), useInterpreter); CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(1), useInterpreter); CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStructWithValueArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStructWithValueArrayArrayLength(null, useInterpreter); } #endregion #region String tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckStringArrayArrayLengthTest(bool useInterpreter) { CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(0), useInterpreter); CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(1), useInterpreter); CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionStringArrayArrayLengthTest(bool useInterpreter) { CheckExceptionStringArrayArrayLength(null, useInterpreter); } #endregion #region UInt tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckUIntArrayArrayLengthTest(bool useInterpreter) { CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(0), useInterpreter); CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(1), useInterpreter); CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionUIntArrayArrayLengthTest(bool useInterpreter) { CheckExceptionUIntArrayArrayLength(null, useInterpreter); } #endregion #region ULong tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckULongArrayArrayLengthTest(bool useInterpreter) { CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(0), useInterpreter); CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(1), useInterpreter); CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionULongArrayArrayLengthTest(bool useInterpreter) { CheckExceptionULongArrayArrayLength(null, useInterpreter); } #endregion #region UShort tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckUShortArrayArrayLengthTest(bool useInterpreter) { CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(0), useInterpreter); CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(1), useInterpreter); CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(5), useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionUShortArrayArrayLengthTest(bool useInterpreter) { CheckExceptionUShortArrayArrayLength(null, useInterpreter); } #endregion #region Generic tests [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericCustomArrayArrayLengthTest(bool useInterpreter) { CheckGenericArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericCustomArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericEnumArrayArrayLengthTest(bool useInterpreter) { CheckGenericArrayArrayLengthTestHelper<E>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericEnumArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericArrayArrayLengthTestHelper<E>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericObjectArrayArrayLengthTest(bool useInterpreter) { CheckGenericArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericObjectArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericStructArrayArrayLengthTest(bool useInterpreter) { CheckGenericArrayArrayLengthTestHelper<S>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericStructArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericArrayArrayLengthTestHelper<S>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter) { CheckGenericArrayArrayLengthTestHelper<Scs>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericArrayArrayLengthTestHelper<Scs>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckExceptionGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter) { CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter); } #endregion #region Generic helpers public static void CheckGenericArrayArrayLengthTestHelper<T>(bool useInterpreter) { CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(0), useInterpreter); CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(1), useInterpreter); CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(5), useInterpreter); } public static void CheckExceptionGenericArrayArrayLengthTestHelper<T>(bool useInterpreter) { CheckExceptionGenericArrayArrayLength<T>(null, useInterpreter); } public static void CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class { CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(0), useInterpreter); CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(1), useInterpreter); CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(5), useInterpreter); } public static void CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class { CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(null, useInterpreter); } public static void CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C { CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(0), useInterpreter); CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(1), useInterpreter); CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(5), useInterpreter); } public static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C { CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(null, useInterpreter); } public static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new() { CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(0), useInterpreter); CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(1), useInterpreter); CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(5), useInterpreter); } public static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new() { CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(null, useInterpreter); } public static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new() { CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(0), useInterpreter); CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(1), useInterpreter); CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(5), useInterpreter); } public static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new() { CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(null, useInterpreter); } public static void CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct { CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(0), useInterpreter); CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(1), useInterpreter); CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(5), useInterpreter); } public static void CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct { CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(null, useInterpreter); } #endregion #region Generate array private static bool[][] GenerateBoolArrayArray(int size) { bool[][] array = new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] }; bool[][] result = new bool[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static byte[][] GenerateByteArrayArray(int size) { byte[][] array = new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] }; byte[][] result = new byte[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static C[][] GenerateCustomArrayArray(int size) { C[][] array = new C[][] { null, new C[0], new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[100] }; C[][] result = new C[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static char[][] GenerateCharArrayArray(int size) { char[][] array = new char[][] { null, new char[0], new char[] { '\0', '\b', 'A', '\uffff' }, new char[100] }; char[][] result = new char[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static D[][] GenerateCustom2ArrayArray(int size) { D[][] array = new D[][] { null, new D[0], new D[] { null, new D(), new D(0), new D(5) }, new D[100] }; D[][] result = new D[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static decimal[][] GenerateDecimalArrayArray(int size) { decimal[][] array = new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] }; decimal[][] result = new decimal[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Delegate[][] GenerateDelegateArrayArray(int size) { Delegate[][] array = new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, new Delegate[100] }; Delegate[][] result = new Delegate[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static double[][] GenerateDoubleArrayArray(int size) { double[][] array = new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] }; double[][] result = new double[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static E[][] GenerateEnumArrayArray(int size) { E[][] array = new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] }; E[][] result = new E[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static El[][] GenerateEnumLongArrayArray(int size) { El[][] array = new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] }; El[][] result = new El[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static float[][] GenerateFloatArrayArray(int size) { float[][] array = new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] }; float[][] result = new float[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Func<object>[][] GenerateFuncArrayArray(int size) { Func<object>[][] array = new Func<object>[][] { null, new Func<object>[0], new Func<object>[] { null, (Func<object>)delegate () { return null; } }, new Func<object>[100] }; Func<object>[][] result = new Func<object>[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static I[][] GenerateInterfaceArrayArray(int size) { I[][] array = new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] }; I[][] result = new I[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static IEquatable<C>[][] GenerateIEquatableCustomArrayArray(int size) { IEquatable<C>[][] array = new IEquatable<C>[][] { null, new IEquatable<C>[0], new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable<C>[100] }; IEquatable<C>[][] result = new IEquatable<C>[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static IEquatable<D>[][] GenerateIEquatableCustom2ArrayArray(int size) { IEquatable<D>[][] array = new IEquatable<D>[][] { null, new IEquatable<D>[0], new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, new IEquatable<D>[100] }; IEquatable<D>[][] result = new IEquatable<D>[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static int[][] GenerateIntArrayArray(int size) { int[][] array = new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] }; int[][] result = new int[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static long[][] GenerateLongArrayArray(int size) { long[][] array = new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] }; long[][] result = new long[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static object[][] GenerateObjectArrayArray(int size) { object[][] array = new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] }; object[][] result = new object[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static S[][] GenerateStructArrayArray(int size) { S[][] array = new S[][] { null, new S[0], new S[] { default(S), new S() }, new S[100] }; S[][] result = new S[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static sbyte[][] GenerateSByteArrayArray(int size) { sbyte[][] array = new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] }; sbyte[][] result = new sbyte[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Sc[][] GenerateStructWithStringArrayArray(int size) { Sc[][] array = new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] }; Sc[][] result = new Sc[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Scs[][] GenerateStructWithStringAndValueArrayArray(int size) { Scs[][] array = new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] }; Scs[][] result = new Scs[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static short[][] GenerateShortArrayArray(int size) { short[][] array = new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] }; short[][] result = new short[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Sp[][] GenerateStructWithTwoValuesArrayArray(int size) { Sp[][] array = new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] }; Sp[][] result = new Sp[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Ss[][] GenerateStructWithValueArrayArray(int size) { Ss[][] array = new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] }; Ss[][] result = new Ss[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static string[][] GenerateStringArrayArray(int size) { string[][] array = new string[][] { null, new string[0], new string[] { null, "", "a", "foo" }, new string[100] }; string[][] result = new string[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static uint[][] GenerateUIntArrayArray(int size) { uint[][] array = new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] }; uint[][] result = new uint[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static ulong[][] GenerateULongArrayArray(int size) { ulong[][] array = new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] }; ulong[][] result = new ulong[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static ushort[][] GenerateUShortArrayArray(int size) { ushort[][] array = new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] }; ushort[][] result = new ushort[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static T[][] GenerateGenericArrayArray<T>(int size) { T[][] array = new T[][] { null, new T[0], new T[] { default(T) }, new T[100] }; T[][] result = new T[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Tc[][] GenerateGenericWithClassRestrictionArrayArray<Tc>(int size) where Tc : class { Tc[][] array = new Tc[][] { null, new Tc[0], new Tc[] { null, default(Tc) }, new Tc[100] }; Tc[][] result = new Tc[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static TC[][] GenerateGenericWithSubClassRestrictionArrayArray<TC>(int size) where TC : C { TC[][] array = new TC[][] { null, new TC[0], new TC[] { null, default(TC), (TC)new C() }, new TC[100] }; TC[][] result = new TC[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Tcn[][] GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(int size) where Tcn : class, new() { Tcn[][] array = new Tcn[][] { null, new Tcn[0], new Tcn[] { null, default(Tcn), new Tcn() }, new Tcn[100] }; Tcn[][] result = new Tcn[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static TCn[][] GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(int size) where TCn : C, new() { TCn[][] array = new TCn[][] { null, new TCn[0], new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }, new TCn[100] }; TCn[][] result = new TCn[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Ts[][] GenerateGenericWithStructRestrictionArrayArray<Ts>(int size) where Ts : struct { Ts[][] array = new Ts[][] { null, new Ts[0], new Ts[] { default(Ts), new Ts() }, new Ts[100] }; Ts[][] result = new Ts[size][]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } #endregion #region Check length expression private static void CheckBoolArrayArrayLengthExpression(bool[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(bool[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckByteArrayArrayLengthExpression(byte[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(byte[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckCustomArrayArrayLengthExpression(C[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(C[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckCharArrayArrayLengthExpression(char[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(char[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckCustom2ArrayArrayLengthExpression(D[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(D[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckDecimalArrayArrayLengthExpression(decimal[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(decimal[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckDelegateArrayArrayLengthExpression(Delegate[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Delegate[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckDoubleArrayArrayLengthExpression(double[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(double[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckEnumArrayArrayLengthExpression(E[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(E[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckEnumLongArrayArrayLengthExpression(El[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(El[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckFloatArrayArrayLengthExpression(float[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(float[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckFuncArrayArrayLengthExpression(Func<object>[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Func<object>[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckInterfaceArrayArrayLengthExpression(I[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(I[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckIEquatableCustomArrayArrayLengthExpression(IEquatable<C>[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<C>[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckIEquatableCustom2ArrayArrayLengthExpression(IEquatable<D>[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<D>[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckIntArrayArrayLengthExpression(int[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(int[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckLongArrayArrayLengthExpression(long[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(long[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckObjectArrayArrayLengthExpression(object[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(object[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStructArrayArrayLengthExpression(S[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(S[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckSByteArrayArrayLengthExpression(sbyte[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(sbyte[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStructWithStringArrayArrayLengthExpression(Sc[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Sc[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStructWithStringAndValueArrayArrayLengthExpression(Scs[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Scs[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckShortArrayArrayLengthExpression(short[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(short[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStructWithTwoValuesArrayArrayLengthExpression(Sp[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Sp[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStructWithValueArrayArrayLengthExpression(Ss[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Ss[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckStringArrayArrayLengthExpression(string[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(string[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckUIntArrayArrayLengthExpression(uint[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(uint[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckULongArrayArrayLengthExpression(ulong[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(ulong[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckUShortArrayArrayLengthExpression(ushort[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(ushort[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericArrayArrayLengthExpression<T>(T[][] array, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(T[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(Tc[][] array, bool useInterpreter) where Tc : class { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Tc[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(TC[][] array, bool useInterpreter) where TC : C { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(TC[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Tcn[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new() { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(TCn[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } private static void CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ArrayLength(Expression.Constant(array, typeof(Ts[][]))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(array.Length, f()); } #endregion #region Check exception array length private static void CheckExceptionBoolArrayArrayLength(bool[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionByteArrayArrayLength(byte[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionCustomArrayArrayLength(C[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionCharArrayArrayLength(char[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionCustom2ArrayArrayLength(D[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionDecimalArrayArrayLength(decimal[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionDelegateArrayArrayLength(Delegate[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionDoubleArrayArrayLength(double[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionEnumArrayArrayLength(E[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionEnumLongArrayArrayLength(El[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionFloatArrayArrayLength(float[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionFuncArrayArrayLength(Func<object>[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionInterfaceArrayArrayLength(I[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionIEquatableCustomArrayArrayLength(IEquatable<C>[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionIEquatableCustom2ArrayArrayLength(IEquatable<D>[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionIntArrayArrayLength(int[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionLongArrayArrayLength(long[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionObjectArrayArrayLength(object[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStructArrayArrayLength(S[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionSByteArrayArrayLength(sbyte[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStructWithStringArrayArrayLength(Sc[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStructWithStringAndValueArrayArrayLength(Scs[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionShortArrayArrayLength(short[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStructWithTwoValuesArrayArrayLength(Sp[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStructWithValueArrayArrayLength(Ss[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionStringArrayArrayLength(string[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionUIntArrayArrayLength(uint[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionULongArrayArrayLength(ulong[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionUShortArrayArrayLength(ushort[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericArrayArrayLength<T>(T[][] array, bool useInterpreter) { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(Tc[][] array, bool useInterpreter) where Tc : class { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(TC[][] array, bool useInterpreter) where TC : C { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new() { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new() { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter)); } private static void CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct { if (array == null) Assert.Throws<NullReferenceException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter)); else Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter)); } #endregion #region Regression tests [Fact] public static void ArrayLength_MultiDimensionalOf1() { foreach (var e in new Expression[] { Expression.Parameter(typeof(int).MakeArrayType(1)), Expression.Constant(new int[2, 2]) }) { Assert.Throws<ArgumentException>("array", () => Expression.ArrayLength(e)); } } #endregion } }
using System; using System.Data; using ByteFX.Data.MySqlClient; namespace ByteFX.Data.MySqlClient { /// <summary> /// Helper class that makes it easier to work with the provider. /// </summary> public sealed class MySqlHelper { // this class provides only static methods private MySqlHelper() { } #region ExecuteNonQuery /// <summary> /// Executes a single command against a MySQL database. The <see cref="MySqlConnection"/> is assumed to be /// open when the method is called and remains open after the method completes. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use</param> /// <param name="commandText">SQL command to be executed</param> /// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command.</param> /// <returns></returns> public static int ExecuteNonQuery( MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters ) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); int result = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return result; } /// <summary> /// Executes a single command against a MySQL database. A new <see cref="MySqlConnection"/> is created /// using the <see cref="MySqlConnection.ConnectionString"/> given. /// </summary> /// <param name="connectionString"><see cref="MySqlConnection.ConnectionString"/> to use</param> /// <param name="commandText">SQL command to be executed</param> /// <param name="parms">Array of <see cref="MySqlParameter"/> objects to use with the command.</param> /// <returns></returns> public static int ExecuteNonQuery( string connectionString, string commandText, params MySqlParameter[] parms ) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteNonQuery(cn, commandText, parms ); } } #endregion #region ExecuteDataSet /// <summary> /// Executes a single SQL command and returns the first row of the resultset. A new MySqlConnection object /// is created, opened, and closed during this method. /// </summary> /// <param name="connectionString">Settings to be used for the connection</param> /// <param name="commandText">Command to execute</param> /// <param name="parms">Parameters to use for the command</param> /// <returns>DataRow containing the first row of the resultset</returns> public static DataRow ExecuteDatarow( string connectionString, string commandText, params MySqlParameter[] parms ) { DataSet ds = ExecuteDataset( connectionString, commandText, parms ); if (ds == null) return null; if (ds.Tables.Count == 0) return null; if (ds.Tables[0].Rows.Count == 0) return null; return ds.Tables[0].Rows[0]; } /// <summary> /// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>. /// A new MySqlConnection object is created, opened, and closed during this method. /// </summary> /// <param name="connectionString">Settings to be used for the connection</param> /// <param name="commandText">Command to execute</param> /// <returns><see cref="DataSet"/> containing the resultset</returns> public static DataSet ExecuteDataset(string connectionString, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteDataset(connectionString, commandText, (MySqlParameter[])null); } /// <summary> /// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>. /// A new MySqlConnection object is created, opened, and closed during this method. /// </summary> /// <param name="connectionString">Settings to be used for the connection</param> /// <param name="commandText">Command to execute</param> /// <param name="commandParameters">Parameters to use for the command</param> /// <returns><see cref="DataSet"/> containing the resultset</returns> public static DataSet ExecuteDataset(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteDataset(cn, commandText, commandParameters); } } /// <summary> /// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>. /// The state of the <see cref="MySqlConnection"/> object remains unchanged after execution /// of this method. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use</param> /// <param name="commandText">Command to execute</param> /// <returns><see cref="DataSet"/> containing the resultset</returns> public static DataSet ExecuteDataset(MySqlConnection connection, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteDataset(connection, commandText, (MySqlParameter[])null); } /// <summary> /// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>. /// The state of the <see cref="MySqlConnection"/> object remains unchanged after execution /// of this method. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use</param> /// <param name="commandText">Command to execute</param> /// <param name="commandParameters">Parameters to use for the command</param> /// <returns><see cref="DataSet"/> containing the resultset</returns> public static DataSet ExecuteDataset(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //create the DataAdapter & DataSet MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc. da.Fill(ds); // detach the MySqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); //return the dataset return ds; } /// <summary> /// Updates the given table with data from the given <see cref="DataSet"/> /// </summary> /// <param name="connectionString">Settings to use for the update</param> /// <param name="commandText">Command text to use for the update</param> /// <param name="ds"><see cref="DataSet"/> containing the new data to use in the update</param> /// <param name="tablename">Tablename in the dataset to update</param> public static void UpdateDataSet( string connectionString, string commandText, DataSet ds, string tablename ) { MySqlConnection cn = new MySqlConnection( connectionString ); cn.Open(); MySqlDataAdapter da = new MySqlDataAdapter( commandText, cn ); MySqlCommandBuilder cb = new MySqlCommandBuilder( da ); da.Update( ds, tablename ); cn.Close(); } #endregion #region ExecuteDataReader /// <summary> /// Executes a single command against a MySQL database, possibly inside an existing transaction. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use for the command</param> /// <param name="transaction"><see cref="MySqlTransaction"/> object to use for the command</param> /// <param name="commandText">Command text to use</param> /// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command</param> /// <param name="ExternalConn">True if the connection should be preserved, false if not</param> /// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns> private static MySqlDataReader ExecuteReader(MySqlConnection connection, MySqlTransaction transaction, string commandText, MySqlParameter[] commandParameters, bool ExternalConn ) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.Transaction = transaction; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //create a reader MySqlDataReader dr; // call ExecuteReader with the appropriate CommandBehavior if (ExternalConn) { dr = cmd.ExecuteReader(); } else { dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); } // detach the SqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return dr; } /// <summary> /// Executes a single command against a MySQL database. /// </summary> /// <param name="connectionString">Settings to use for this command</param> /// <param name="commandText">Command text to use</param> /// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns> public static MySqlDataReader ExecuteReader(string connectionString, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteReader(connectionString, commandText, (MySqlParameter[])null); } /// <summary> /// Executes a single command against a MySQL database. /// </summary> /// <param name="connectionString">Settings to use for this command</param> /// <param name="commandText">Command text to use</param> /// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command</param> /// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns> public static MySqlDataReader ExecuteReader(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection MySqlConnection cn = new MySqlConnection(connectionString); cn.Open(); try { //call the private overload that takes an internally owned connection in place of the connection string return ExecuteReader(cn, null, commandText, commandParameters, false ); } catch { //if we fail to return the SqlDatReader, we need to close the connection ourselves cn.Close(); throw; } } #endregion #region ExecuteScalar /// <summary> /// Execute a single command against a MySQL database. /// </summary> /// <param name="connectionString">Settings to use for the update</param> /// <param name="commandText">Command text to use for the update</param> /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> public static object ExecuteScalar(string connectionString, string commandText) { //pass through the call providing null for the set of MySqlParameters return ExecuteScalar(connectionString, commandText, (MySqlParameter[])null); } /// <summary> /// Execute a single command against a MySQL database. /// </summary> /// <param name="connectionString">Settings to use for the command</param> /// <param name="commandText">Command text to use for the command</param> /// <param name="commandParameters">Parameters to use for the command</param> /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> public static object ExecuteScalar(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteScalar(cn, commandText, commandParameters); } } /// <summary> /// Execute a single command against a MySQL database. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use</param> /// <param name="commandText">Command text to use for the command</param> /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> public static object ExecuteScalar(MySqlConnection connection, string commandText) { //pass through the call providing null for the set of MySqlParameters return ExecuteScalar(connection, commandText, (MySqlParameter[])null); } /// <summary> /// Execute a single command against a MySQL database. /// </summary> /// <param name="connection"><see cref="MySqlConnection"/> object to use</param> /// <param name="commandText">Command text to use for the command</param> /// <param name="commandParameters">Parameters to use for the command</param> /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> public static object ExecuteScalar(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //execute the command & return the results object retval = cmd.ExecuteScalar(); // detach the SqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; using System; using System.Diagnostics; using System.IO; using System.Management; // Reference C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Management.dll using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using System.Text.RegularExpressions; using System.Collections.Generic; namespace MinionConfigurationExtension { public class Session { public void Log(String msg) { Console.WriteLine(msg); } } class ActionResult{ public static ActionResult Success; } class Program { private static void write_master_and_id_to_file_DECAC(Session session, String configfile, string csv_multimasters, String id) { /* How to * read line * if line master, read multimaster, replace * if line id, replace * copy through line */ char[] separators = new char[] { ',', ' ' }; string[] multimasters = csv_multimasters.Split(separators, StringSplitOptions.RemoveEmptyEntries); session.Log("...want to write master and id to " + configfile); bool configExists = File.Exists(configfile); session.Log("......file exists " + configExists); string[] configLinesINPUT = new List<string>().ToArray(); List<string> configLinesOUTPUT = new List<string>(); if (configExists) { configLinesINPUT = File.ReadAllLines(configfile); } session.Log("...found config lines count " + configLinesINPUT.Length); session.Log("...got master count " + multimasters.Length); session.Log("...got id " + id); Regex line_contains_key = new Regex(@"^([a-zA-Z_]+):"); Regex line_contains_one_multimaster = new Regex(@"^\s*-\s*([0-9a-zA-Z_.-]+)\s*$"); bool master_emitted = false; bool id_emitted = false; bool look_for_multimasters = false; foreach (string line in configLinesINPUT) { // search master and id if (line_contains_key.IsMatch(line)) { Match m = line_contains_key.Match(line); string key = m.Groups[1].ToString(); if (key == "master") { look_for_multimasters = true; continue; // next line } else if (key == "id") { // emit id configLinesOUTPUT.Add("id: " + id); id_emitted = true; continue; // next line } else { if (!look_for_multimasters) { configLinesOUTPUT.Add(line); // copy through continue; // next line } } } else { if (!look_for_multimasters) { configLinesOUTPUT.Add(line); // copy through continue; // next line } } if (look_for_multimasters) { // consume multimasters if (line_contains_one_multimaster.IsMatch(line)) { // consume another multimaster } else { look_for_multimasters = false; // First emit master if (multimasters.Length == 1) { configLinesOUTPUT.Add("master: " + multimasters[0]); master_emitted = true; } if (multimasters.Length > 1) { configLinesOUTPUT.Add("master:"); foreach (string onemultimaster in multimasters) { configLinesOUTPUT.Add("- " + onemultimaster); } master_emitted = true; } configLinesOUTPUT.Add(line); // Then copy through whatever is not one multimaster } } } // input is read if (!master_emitted) { // put master after hash master Regex line_contains_hash_master = new Regex(@"^# master:"); List<string> configLinesOUTPUT_hash_master = new List<string>(); foreach (string output_line in configLinesOUTPUT) { configLinesOUTPUT_hash_master.Add(output_line); if(line_contains_hash_master.IsMatch(output_line)) { if (multimasters.Length == 1) { configLinesOUTPUT_hash_master.Add("master: " + multimasters[0]); master_emitted = true; } if (multimasters.Length > 1) { configLinesOUTPUT_hash_master.Add("master:"); foreach (string onemultimaster in multimasters) { configLinesOUTPUT_hash_master.Add("- " + onemultimaster); } master_emitted = true; } } } configLinesOUTPUT = configLinesOUTPUT_hash_master; } if (!master_emitted) { // put master at end if (multimasters.Length == 1) { configLinesOUTPUT.Add("master: " + multimasters[0]); } if (multimasters.Length > 1) { configLinesOUTPUT.Add("master:"); foreach (string onemultimaster in multimasters) { configLinesOUTPUT.Add("- " + onemultimaster); } } } if (!id_emitted) { // put after hash Regex line_contains_hash_id = new Regex(@"^# id:"); List<string> configLinesOUTPUT_hash_id = new List<string>(); foreach (string output_line in configLinesOUTPUT) { configLinesOUTPUT_hash_id.Add(output_line); if (line_contains_hash_id.IsMatch(output_line)) { configLinesOUTPUT_hash_id.Add("id: " + id); id_emitted = true; } } configLinesOUTPUT = configLinesOUTPUT_hash_id; } if (!id_emitted) { // put at end configLinesOUTPUT.Add("id: " + id); } session.Log("...writing to " + configfile); string output = string.Join("\r\n", configLinesOUTPUT.ToArray()) + "\r\n"; File.WriteAllText(configfile, output); } private static void read_master_and_id_from_file_IMCAC(Session session, String configfile, ref String ref_master, ref String ref_id) { /* How to match multimasters * match `master: `MASTER*: if MASTER: master = MASTER else, a list of masters may follow: while match `- ` MASTER: master += MASTER */ session.Log("...searching master and id in " + configfile); bool configExists = File.Exists(configfile); session.Log("......file exists " + configExists); if (!configExists) { return; } string[] configLines = File.ReadAllLines(configfile); Regex line_key_maybe_value = new Regex(@"^([a-zA-Z_]+):\s*([0-9a-zA-Z_.-]*)\s*$"); Regex line_listvalue = new Regex(@"^\s*-\s*([0-9a-zA-Z_.-]+)\s*$"); bool look_for_keys_otherwise_look_for_multimasters = true; List<string> multimasters = new List<string>(); foreach (string line in configLines) { if (look_for_keys_otherwise_look_for_multimasters && line_key_maybe_value.IsMatch(line)) { Match m = line_key_maybe_value.Match(line); string key = m.Groups[1].ToString(); string maybe_value = m.Groups[2].ToString(); //session.Log("...ANY KEY " + key + " " + maybe_value); if (key == "master") { if (maybe_value.Length > 0) { ref_master = maybe_value; session.Log("......master " + ref_master); } else { session.Log("...... now searching multimasters"); look_for_keys_otherwise_look_for_multimasters = false; } } if (key == "id" && maybe_value.Length > 0) { ref_id = maybe_value; session.Log("......id " + ref_id); } } else if (line_listvalue.IsMatch(line)) { Match m = line_listvalue.Match(line); multimasters.Add(m.Groups[1].ToString()); } else { look_for_keys_otherwise_look_for_multimasters = true; } } if (multimasters.Count > 0) { ref_master = string.Join(",", multimasters.ToArray()); session.Log("......master " + ref_master); } } public static ActionResult kill_python_exe(Session session) { // because a running process can prevent removal of files // Get full path and command line from running process session.Log("...BEGIN kill_python_exe"); using (var wmi_searcher = new ManagementObjectSearcher ("SELECT ProcessID, ExecutablePath, CommandLine FROM Win32_Process WHERE Name = 'python.exe'")) { foreach (ManagementObject wmi_obj in wmi_searcher.Get()) { try { String ProcessID = wmi_obj["ProcessID"].ToString(); Int32 pid = Int32.Parse(ProcessID); String ExecutablePath = wmi_obj["ExecutablePath"].ToString(); String CommandLine = wmi_obj["CommandLine"].ToString(); if (CommandLine.ToLower().Contains("salt") || ExecutablePath.ToLower().Contains("salt")) { session.Log("...kill_python_exe " + ExecutablePath + " " + CommandLine); Process proc11 = Process.GetProcessById(pid); proc11.Kill(); } } catch (Exception) { // ignore wmiresults without these properties } } } session.Log("...END kill_python_exe"); return ActionResult.Success; } public static ActionResult del_NSIS_DECAC(Session session) { // Leaves the Config /* * If NSIS is installed: * remove salt-minion service, * remove registry * remove files, except /salt/conf and /salt/var * * The msi cannot use uninst.exe because the service would no longer start. */ session.Log("...BEGIN del_NSIS_DECAC"); RegistryKey HKLM = Registry.LocalMachine; string ARPstring = @"Microsoft\Windows\CurrentVersion\Uninstall\Salt Minion"; RegistryKey ARPreg = cutil.get_registry_SOFTWARE_key(session, ARPstring); string uninstexe = ""; if (ARPreg != null) uninstexe = ARPreg.GetValue("UninstallString").ToString(); session.Log("from REGISTRY uninstexe = " + uninstexe); string SOFTWAREstring = @"Salt Project\Salt"; RegistryKey SOFTWAREreg = cutil.get_registry_SOFTWARE_key(session, SOFTWAREstring); var bin_dir = ""; if (SOFTWAREreg != null) bin_dir = SOFTWAREreg.GetValue("bin_dir").ToString(); session.Log("from REGISTRY bin_dir = " + bin_dir); if (bin_dir == "") bin_dir = @"C:\salt\bin"; session.Log("bin_dir = " + bin_dir); session.Log("Going to kill ..."); kill_python_exe(session); session.Log("Going to stop service salt-minion ..."); cutil.shellout(session, "sc stop salt-minion"); session.Log("Going to delete service salt-minion ..."); cutil.shellout(session, "sc delete salt-minion"); session.Log("Going to delete ARP registry entry ..."); cutil.del_registry_SOFTWARE_key(session, ARPstring); session.Log("Going to delete SOFTWARE registry entry ..."); cutil.del_registry_SOFTWARE_key(session, SOFTWAREstring); session.Log("Going to delete bindir ... " + bin_dir); cutil.del_dir(session, bin_dir); session.Log("Going to delete uninst.exe ..."); cutil.del_file(session, uninstexe); var bindirparent = Path.GetDirectoryName(bin_dir); session.Log(@"Going to delete bindir\..\salt\*.* ... " + bindirparent); if (Directory.Exists(bindirparent)) { try { foreach (FileInfo fi in new DirectoryInfo(bindirparent).GetFiles("salt*.*")) { fi.Delete(); } } catch (Exception) {; } } session.Log("...END del_NSIS_DECAC"); return ActionResult.Success; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- static void Main(string[] args) { Console.WriteLine("DebugMe!"); Session the_session = new Session(); //del_NSIS_DECAC(the_session); String the_master= ""; String the_id = "bob"; string the_multimasters = "anna1,anna2"; //read_master_and_id_from_file_IMCAC(the_session, @"c:\temp\testme.txt", ref the_master, ref the_id); write_master_and_id_to_file_DECAC(the_session, @"c:\temp\testme.txt", the_multimasters, the_id); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Insights.Models; namespace Microsoft.Azure.Insights.Models { /// <summary> /// The Azure event log entries are of type EventData /// </summary> public partial class EventData { private SenderAuthorization _authorization; /// <summary> /// Optional. Gets or sets the authorization.This is the authorization /// used by the user who has performed the operation that led to this /// event. /// </summary> public SenderAuthorization Authorization { get { return this._authorization; } set { this._authorization = value; } } private string _caller; /// <summary> /// Optional. Gets or sets the caller /// </summary> public string Caller { get { return this._caller; } set { this._caller = value; } } private IDictionary<string, string> _claims; /// <summary> /// Optional. Gets or sets the claims /// </summary> public IDictionary<string, string> Claims { get { return this._claims; } set { this._claims = value; } } private string _correlationId; /// <summary> /// Optional. Gets or sets the correlation Id.The correlation Id is /// shared among the events that belong to the same deployment. /// </summary> public string CorrelationId { get { return this._correlationId; } set { this._correlationId = value; } } private string _description; /// <summary> /// Optional. Gets or sets the description of the event. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private EventChannels _eventChannels; /// <summary> /// Optional. Gets or sets the event channels.The regular event logs, /// that you see in the Azure Management Portals, flow through the /// 'Operation' channel. /// </summary> public EventChannels EventChannels { get { return this._eventChannels; } set { this._eventChannels = value; } } private string _eventDataId; /// <summary> /// Optional. Gets or sets the event data Id.This is a unique /// identifier for an event. /// </summary> public string EventDataId { get { return this._eventDataId; } set { this._eventDataId = value; } } private LocalizableString _eventName; /// <summary> /// Optional. Gets or sets the event name.This value should not be /// confused with OperationName.For practical purposes, OperationName /// might be more appealing to end users. /// </summary> public LocalizableString EventName { get { return this._eventName; } set { this._eventName = value; } } private LocalizableString _eventSource; /// <summary> /// Optional. Gets or sets the event source.This value indicates the /// source that generated the event. /// </summary> public LocalizableString EventSource { get { return this._eventSource; } set { this._eventSource = value; } } private DateTime _eventTimestamp; /// <summary> /// Optional. Gets or sets the occurrence time of event /// </summary> public DateTime EventTimestamp { get { return this._eventTimestamp; } set { this._eventTimestamp = value; } } private HttpRequestInfo _httpRequest; /// <summary> /// Optional. Gets or sets the HTTP request info.The client IP address /// of the user who initiated the event is captured as part of the /// HTTP request info. /// </summary> public HttpRequestInfo HttpRequest { get { return this._httpRequest; } set { this._httpRequest = value; } } private string _id; /// <summary> /// Optional. Gets or sets the Id /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private EventLevel _level; /// <summary> /// Optional. Gets or sets the event level /// </summary> public EventLevel Level { get { return this._level; } set { this._level = value; } } private string _operationId; /// <summary> /// Optional. Gets or sets the operation idThis value should not be /// confused with EventName. /// </summary> public string OperationId { get { return this._operationId; } set { this._operationId = value; } } private LocalizableString _operationName; /// <summary> /// Optional. Gets or sets the operation name. /// </summary> public LocalizableString OperationName { get { return this._operationName; } set { this._operationName = value; } } private IDictionary<string, string> _properties; /// <summary> /// Optional. Gets or sets the property bag /// </summary> public IDictionary<string, string> Properties { get { return this._properties; } set { this._properties = value; } } private string _resourceGroupName; /// <summary> /// Optional. Gets or sets the resource group name. (see /// http://msdn.microsoft.com/en-us/library/azure/dn790546.aspx for /// more information) /// </summary> public string ResourceGroupName { get { return this._resourceGroupName; } set { this._resourceGroupName = value; } } private LocalizableString _resourceProviderName; /// <summary> /// Optional. Gets or sets the resource provider name. (see /// http://msdn.microsoft.com/en-us/library/azure/dn790572.aspx for /// more information) /// </summary> public LocalizableString ResourceProviderName { get { return this._resourceProviderName; } set { this._resourceProviderName = value; } } private string _resourceUri; /// <summary> /// Optional. Gets or sets the resource uri (see /// http://msdn.microsoft.com/en-us/library/azure/dn790569.aspx for /// more information) /// </summary> public string ResourceUri { get { return this._resourceUri; } set { this._resourceUri = value; } } private LocalizableString _status; /// <summary> /// Optional. Gets or sets the event status.Some typical values are: /// Started, Succeeded, Failed /// </summary> public LocalizableString Status { get { return this._status; } set { this._status = value; } } private DateTime _submissionTimestamp; /// <summary> /// Optional. Gets or sets the event submission time.This value should /// not be confused eventTimestamp. As there might be a delay between /// the occurence time of the event, and the time that the event is /// submitted to the Azure logging infrastructure. /// </summary> public DateTime SubmissionTimestamp { get { return this._submissionTimestamp; } set { this._submissionTimestamp = value; } } private string _subscriptionId; /// <summary> /// Optional. Gets or sets the Azure subscription Id /// </summary> public string SubscriptionId { get { return this._subscriptionId; } set { this._subscriptionId = value; } } private LocalizableString _subStatus; /// <summary> /// Optional. Gets or sets the event sub status.Most of the time, when /// included, this captures the HTTP status code. /// </summary> public LocalizableString SubStatus { get { return this._subStatus; } set { this._subStatus = value; } } /// <summary> /// Initializes a new instance of the EventData class. /// </summary> public EventData() { this.Claims = new LazyDictionary<string, string>(); this.Properties = new LazyDictionary<string, string>(); } } }
// 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 gcgv = Google.Cloud.Gaming.V1; using sys = System; namespace Google.Cloud.Gaming.V1 { /// <summary>Resource name for the <c>GameServerConfig</c> resource.</summary> public sealed partial class GameServerConfigName : gax::IResourceName, sys::IEquatable<GameServerConfigName> { /// <summary>The possible contents of <see cref="GameServerConfigName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</c>. /// </summary> ProjectLocationDeploymentConfig = 1, } private static gax::PathTemplate s_projectLocationDeploymentConfig = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}"); /// <summary>Creates a <see cref="GameServerConfigName"/> 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="GameServerConfigName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static GameServerConfigName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new GameServerConfigName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="GameServerConfigName"/> with the pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</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="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="configId">The <c>Config</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="GameServerConfigName"/> constructed from the provided ids.</returns> public static GameServerConfigName FromProjectLocationDeploymentConfig(string projectId, string locationId, string deploymentId, string configId) => new GameServerConfigName(ResourceNameType.ProjectLocationDeploymentConfig, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)), configId: gax::GaxPreconditions.CheckNotNullOrEmpty(configId, nameof(configId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerConfigName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</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="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="configId">The <c>Config</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerConfigName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</c>. /// </returns> public static string Format(string projectId, string locationId, string deploymentId, string configId) => FormatProjectLocationDeploymentConfig(projectId, locationId, deploymentId, configId); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerConfigName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</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="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="configId">The <c>Config</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerConfigName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</c>. /// </returns> public static string FormatProjectLocationDeploymentConfig(string projectId, string locationId, string deploymentId, string configId) => s_projectLocationDeploymentConfig.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(configId, nameof(configId))); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerConfigName"/> 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}/gameServerDeployments/{deployment}/configs/{config}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerConfigName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="GameServerConfigName"/> if successful.</returns> public static GameServerConfigName Parse(string gameServerConfigName) => Parse(gameServerConfigName, false); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerConfigName"/> 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}/gameServerDeployments/{deployment}/configs/{config}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerConfigName">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="GameServerConfigName"/> if successful.</returns> public static GameServerConfigName Parse(string gameServerConfigName, bool allowUnparsed) => TryParse(gameServerConfigName, allowUnparsed, out GameServerConfigName 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="GameServerConfigName"/> 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}/gameServerDeployments/{deployment}/configs/{config}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerConfigName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="GameServerConfigName"/>, 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 gameServerConfigName, out GameServerConfigName result) => TryParse(gameServerConfigName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="GameServerConfigName"/> 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}/gameServerDeployments/{deployment}/configs/{config}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerConfigName">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="GameServerConfigName"/>, 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 gameServerConfigName, bool allowUnparsed, out GameServerConfigName result) { gax::GaxPreconditions.CheckNotNull(gameServerConfigName, nameof(gameServerConfigName)); gax::TemplatedResourceName resourceName; if (s_projectLocationDeploymentConfig.TryParseName(gameServerConfigName, out resourceName)) { result = FromProjectLocationDeploymentConfig(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(gameServerConfigName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private GameServerConfigName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string configId = null, string deploymentId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConfigId = configId; DeploymentId = deploymentId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="GameServerConfigName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}</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="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="configId">The <c>Config</c> ID. Must not be <c>null</c> or empty.</param> public GameServerConfigName(string projectId, string locationId, string deploymentId, string configId) : this(ResourceNameType.ProjectLocationDeploymentConfig, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId)), configId: gax::GaxPreconditions.CheckNotNullOrEmpty(configId, nameof(configId))) { } /// <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>Config</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ConfigId { get; } /// <summary> /// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DeploymentId { 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>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.ProjectLocationDeploymentConfig: return s_projectLocationDeploymentConfig.Expand(ProjectId, LocationId, DeploymentId, ConfigId); 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 GameServerConfigName); /// <inheritdoc/> public bool Equals(GameServerConfigName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(GameServerConfigName a, GameServerConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(GameServerConfigName a, GameServerConfigName b) => !(a == b); } public partial class ListGameServerConfigsRequest { /// <summary> /// <see cref="GameServerDeploymentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public GameServerDeploymentName ParentAsGameServerDeploymentName { get => string.IsNullOrEmpty(Parent) ? null : GameServerDeploymentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetGameServerConfigRequest { /// <summary> /// <see cref="gcgv::GameServerConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerConfigName GameServerConfigName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateGameServerConfigRequest { /// <summary> /// <see cref="GameServerDeploymentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public GameServerDeploymentName ParentAsGameServerDeploymentName { get => string.IsNullOrEmpty(Parent) ? null : GameServerDeploymentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteGameServerConfigRequest { /// <summary> /// <see cref="gcgv::GameServerConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerConfigName GameServerConfigName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GameServerConfig { /// <summary> /// <see cref="gcgv::GameServerConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerConfigName GameServerConfigName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.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.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Text.Encodings.Web; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class DictionaryTests { [Fact] public static void DictionaryOfString() { const string JsonString = @"{""Hello"":""World"",""Hello2"":""World2""}"; const string ReorderedJsonString = @"{""Hello2"":""World2"",""Hello"":""World""}"; { IDictionary obj = JsonSerializer.Deserialize<IDictionary>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { Dictionary<string, string> obj = JsonSerializer.Deserialize<Dictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { SortedDictionary<string, string> obj = JsonSerializer.Deserialize<SortedDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { IDictionary<string, string> obj = JsonSerializer.Deserialize<IDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { IReadOnlyDictionary<string, string> obj = JsonSerializer.Deserialize<IReadOnlyDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { ImmutableDictionary<string, string> obj = JsonSerializer.Deserialize<ImmutableDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json || ReorderedJsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json || ReorderedJsonString == json); } { IImmutableDictionary<string, string> obj = JsonSerializer.Deserialize<IImmutableDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json || ReorderedJsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json || ReorderedJsonString == json); } { ImmutableSortedDictionary<string, string> obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, string>>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json); } { Hashtable obj = JsonSerializer.Deserialize<Hashtable>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json || ReorderedJsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json || ReorderedJsonString == json); } { SortedList obj = JsonSerializer.Deserialize<SortedList>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } } [Fact] public static void ImplementsDictionary_DictionaryOfString() { const string JsonString = @"{""Hello"":""World"",""Hello2"":""World2""}"; const string ReorderedJsonString = @"{""Hello2"":""World2"",""Hello"":""World""}"; { WrapperForIDictionary obj = JsonSerializer.Deserialize<WrapperForIDictionary>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { StringToStringDictionaryWrapper obj = JsonSerializer.Deserialize<StringToStringDictionaryWrapper>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { StringToStringSortedDictionaryWrapper obj = JsonSerializer.Deserialize<StringToStringSortedDictionaryWrapper>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { StringToStringIDictionaryWrapper obj = JsonSerializer.Deserialize<StringToStringIDictionaryWrapper>(JsonString); Assert.Equal("World", obj["Hello"]); Assert.Equal("World2", obj["Hello2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<StringToStringIReadOnlyDictionaryWrapper>(JsonString)); StringToStringIReadOnlyDictionaryWrapper obj = new StringToStringIReadOnlyDictionaryWrapper(new Dictionary<string, string>() { { "Hello", "World" }, { "Hello2", "World2" }, }); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<StringToStringIImmutableDictionaryWrapper>(JsonString)); StringToStringIImmutableDictionaryWrapper obj = new StringToStringIImmutableDictionaryWrapper(new Dictionary<string, string>() { { "Hello", "World" }, { "Hello2", "World2" }, }); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json || ReorderedJsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json || ReorderedJsonString == json); } { HashtableWrapper obj = JsonSerializer.Deserialize<HashtableWrapper>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.True(JsonString == json || ReorderedJsonString == json); json = JsonSerializer.Serialize<object>(obj); Assert.True(JsonString == json || ReorderedJsonString == json); } { SortedListWrapper obj = JsonSerializer.Deserialize<SortedListWrapper>(JsonString); Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString()); Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString()); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } } [Fact] public static void DictionaryOfObject() { { Dictionary<string, object> obj = JsonSerializer.Deserialize<Dictionary<string, object>>(@"{""Key1"":1}"); Assert.Equal(1, obj.Count); JsonElement element = (JsonElement)obj["Key1"]; Assert.Equal(JsonValueKind.Number, element.ValueKind); Assert.Equal(1, element.GetInt32()); string json = JsonSerializer.Serialize(obj); Assert.Equal(@"{""Key1"":1}", json); } { IDictionary<string, object> obj = JsonSerializer.Deserialize<IDictionary<string, object>>(@"{""Key1"":1}"); Assert.Equal(1, obj.Count); JsonElement element = (JsonElement)obj["Key1"]; Assert.Equal(JsonValueKind.Number, element.ValueKind); Assert.Equal(1, element.GetInt32()); string json = JsonSerializer.Serialize(obj); Assert.Equal(@"{""Key1"":1}", json); } } [Fact] public static void ImplementsIDictionaryOfObject() { var input = new StringToObjectIDictionaryWrapper(new Dictionary<string, object> { { "Name", "David" }, { "Age", 32 } }); string json = JsonSerializer.Serialize(input, typeof(IDictionary<string, object>)); Assert.Equal(@"{""Name"":""David"",""Age"":32}", json); IDictionary<string, object> obj = JsonSerializer.Deserialize<IDictionary<string, object>>(json); Assert.Equal(2, obj.Count); Assert.Equal("David", ((JsonElement)obj["Name"]).GetString()); Assert.Equal(32, ((JsonElement)obj["Age"]).GetInt32()); } [Fact] public static void ImplementsIDictionaryOfString() { var input = new StringToStringIDictionaryWrapper(new Dictionary<string, string> { { "Name", "David" }, { "Job", "Software Architect" } }); string json = JsonSerializer.Serialize(input, typeof(IDictionary<string, string>)); Assert.Equal(@"{""Name"":""David"",""Job"":""Software Architect""}", json); IDictionary<string, string> obj = JsonSerializer.Deserialize<IDictionary<string, string>>(json); Assert.Equal(2, obj.Count); Assert.Equal("David", obj["Name"]); Assert.Equal("Software Architect", obj["Job"]); } [Theory] [InlineData(typeof(ImmutableDictionary<string, string>), "\"headers\"")] [InlineData(typeof(Dictionary<string, string>), "\"headers\"")] [InlineData(typeof(PocoDictionary), "\"headers\"")] public static void InvalidJsonForValueShouldFail(Type type, string json) { Assert.Throws<JsonException>(() => JsonSerializer.Deserialize(json, type)); } [Theory] [InlineData(typeof(int[]), @"""test""")] [InlineData(typeof(int[]), @"1")] [InlineData(typeof(int[]), @"false")] [InlineData(typeof(int[]), @"{}")] [InlineData(typeof(int[]), @"[""test""")] [InlineData(typeof(int[]), @"[true]")] [InlineData(typeof(int[]), @"[{}]")] [InlineData(typeof(int[]), @"[[]]")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": {}}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": ""test""}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": 1}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": true}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": [""test""]}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": [[]]}")] [InlineData(typeof(Dictionary<string, int[]>), @"{""test"": [{}]}")] public static void InvalidJsonForArrayShouldFail(Type type, string json) { Assert.Throws<JsonException>(() => JsonSerializer.Deserialize(json, type)); } [Fact] public static void InvalidEmptyDictionaryInput() { Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<string>("{}")); } [Fact] public static void PocoWithDictionaryObject() { PocoDictionary dict = JsonSerializer.Deserialize<PocoDictionary>("{\n\t\"key\" : {\"a\" : \"b\", \"c\" : \"d\"}}"); Assert.Equal("b", dict.key["a"]); Assert.Equal("d", dict.key["c"]); } public class PocoDictionary { public Dictionary<string, string> key { get; set; } } [Fact] public static void DictionaryOfObject_37569() { // https://github.com/dotnet/corefx/issues/37569 Dictionary<string, object> dictionary = new Dictionary<string, object> { ["key"] = new Poco { Id = 10 }, }; string json = JsonSerializer.Serialize(dictionary); Assert.Equal(@"{""key"":{""Id"":10}}", json); dictionary = JsonSerializer.Deserialize<Dictionary<string, object>>(json); Assert.Equal(1, dictionary.Count); JsonElement element = (JsonElement)dictionary["key"]; Assert.Equal(@"{""Id"":10}", element.ToString()); } public class Poco { public int Id { get; set; } } [Fact] public static void FirstGenericArgNotStringFail() { Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<Dictionary<int, int>>(@"{1:1}")); Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ImmutableDictionary<int, int>>(@"{1:1}")); } [Fact] public static void DictionaryOfList() { const string JsonString = @"{""Key1"":[1,2],""Key2"":[3,4]}"; { IDictionary obj = JsonSerializer.Deserialize<IDictionary>(JsonString); Assert.Equal(2, obj.Count); int expectedNumber = 1; JsonElement element = (JsonElement)obj["Key1"]; foreach (JsonElement value in element.EnumerateArray()) { Assert.Equal(expectedNumber++, value.GetInt32()); } element = (JsonElement)obj["Key2"]; foreach (JsonElement value in element.EnumerateArray()) { Assert.Equal(expectedNumber++, value.GetInt32()); } string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); } { IDictionary<string, List<int>> obj = JsonSerializer.Deserialize<IDictionary<string, List<int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(1, obj["Key1"][0]); Assert.Equal(2, obj["Key1"][1]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(3, obj["Key2"][0]); Assert.Equal(4, obj["Key2"][1]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); } { ImmutableDictionary<string, List<int>> obj = JsonSerializer.Deserialize<ImmutableDictionary<string, List<int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(1, obj["Key1"][0]); Assert.Equal(2, obj["Key1"][1]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(3, obj["Key2"][0]); Assert.Equal(4, obj["Key2"][1]); string json = JsonSerializer.Serialize(obj); const string ReorderedJsonString = @"{""Key2"":[3,4],""Key1"":[1,2]}"; Assert.True(JsonString == json || ReorderedJsonString == json); } { IImmutableDictionary<string, List<int>> obj = JsonSerializer.Deserialize<IImmutableDictionary<string, List<int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(1, obj["Key1"][0]); Assert.Equal(2, obj["Key1"][1]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(3, obj["Key2"][0]); Assert.Equal(4, obj["Key2"][1]); string json = JsonSerializer.Serialize(obj); const string ReorderedJsonString = @"{""Key2"":[3,4],""Key1"":[1,2]}"; Assert.True(JsonString == json || ReorderedJsonString == json); } } [Fact] public static void DictionaryOfArray() { const string JsonString = @"{""Key1"":[1,2],""Key2"":[3,4]}"; Dictionary<string, int[]> obj = JsonSerializer.Deserialize<Dictionary<string, int[]>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Length); Assert.Equal(1, obj["Key1"][0]); Assert.Equal(2, obj["Key1"][1]); Assert.Equal(2, obj["Key2"].Length); Assert.Equal(3, obj["Key2"][0]); Assert.Equal(4, obj["Key2"][1]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); } [Fact] public static void ListOfDictionary() { const string JsonString = @"[{""Key1"":1,""Key2"":2},{""Key1"":3,""Key2"":4}]"; { List<Dictionary<string, int>> obj = JsonSerializer.Deserialize<List<Dictionary<string, int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj[0].Count); Assert.Equal(1, obj[0]["Key1"]); Assert.Equal(2, obj[0]["Key2"]); Assert.Equal(2, obj[1].Count); Assert.Equal(3, obj[1]["Key1"]); Assert.Equal(4, obj[1]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { List<ImmutableSortedDictionary<string, int>> obj = JsonSerializer.Deserialize<List<ImmutableSortedDictionary<string, int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj[0].Count); Assert.Equal(1, obj[0]["Key1"]); Assert.Equal(2, obj[0]["Key2"]); Assert.Equal(2, obj[1].Count); Assert.Equal(3, obj[1]["Key1"]); Assert.Equal(4, obj[1]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } } [Fact] public static void ArrayOfDictionary() { const string JsonString = @"[{""Key1"":1,""Key2"":2},{""Key1"":3,""Key2"":4}]"; { Dictionary<string, int>[] obj = JsonSerializer.Deserialize<Dictionary<string, int>[]>(JsonString); Assert.Equal(2, obj.Length); Assert.Equal(2, obj[0].Count); Assert.Equal(1, obj[0]["Key1"]); Assert.Equal(2, obj[0]["Key2"]); Assert.Equal(2, obj[1].Count); Assert.Equal(3, obj[1]["Key1"]); Assert.Equal(4, obj[1]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { ImmutableSortedDictionary<string, int>[] obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, int>[]>(JsonString); Assert.Equal(2, obj.Length); Assert.Equal(2, obj[0].Count); Assert.Equal(1, obj[0]["Key1"]); Assert.Equal(2, obj[0]["Key2"]); Assert.Equal(2, obj[1].Count); Assert.Equal(3, obj[1]["Key1"]); Assert.Equal(4, obj[1]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } } [Fact] public static void DictionaryOfDictionary() { const string JsonString = @"{""Key1"":{""Key1a"":1,""Key1b"":2},""Key2"":{""Key2a"":3,""Key2b"":4}}"; { Dictionary<string, Dictionary<string, int>> obj = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(1, obj["Key1"]["Key1a"]); Assert.Equal(2, obj["Key1"]["Key1b"]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(3, obj["Key2"]["Key2a"]); Assert.Equal(4, obj["Key2"]["Key2b"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } { ImmutableSortedDictionary<string, ImmutableSortedDictionary<string, int>> obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, ImmutableSortedDictionary<string, int>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(1, obj["Key1"]["Key1a"]); Assert.Equal(2, obj["Key1"]["Key1b"]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(3, obj["Key2"]["Key2a"]); Assert.Equal(4, obj["Key2"]["Key2b"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } } [Fact] public static void DictionaryOfDictionaryOfDictionary() { const string JsonString = @"{""Key1"":{""Key1"":{""Key1"":1,""Key2"":2},""Key2"":{""Key1"":3,""Key2"":4}},""Key2"":{""Key1"":{""Key1"":5,""Key2"":6},""Key2"":{""Key1"":7,""Key2"":8}}}"; Dictionary<string, Dictionary<string, Dictionary<string, int>>> obj = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, int>>>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Count); Assert.Equal(2, obj["Key1"]["Key1"].Count); Assert.Equal(2, obj["Key1"]["Key2"].Count); Assert.Equal(1, obj["Key1"]["Key1"]["Key1"]); Assert.Equal(2, obj["Key1"]["Key1"]["Key2"]); Assert.Equal(3, obj["Key1"]["Key2"]["Key1"]); Assert.Equal(4, obj["Key1"]["Key2"]["Key2"]); Assert.Equal(2, obj["Key2"].Count); Assert.Equal(2, obj["Key2"]["Key1"].Count); Assert.Equal(2, obj["Key2"]["Key2"].Count); Assert.Equal(5, obj["Key2"]["Key1"]["Key1"]); Assert.Equal(6, obj["Key2"]["Key1"]["Key2"]); Assert.Equal(7, obj["Key2"]["Key2"]["Key1"]); Assert.Equal(8, obj["Key2"]["Key2"]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); // Verify that typeof(object) doesn't interfere. json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } [Fact] public static void DictionaryOfArrayOfDictionary() { const string JsonString = @"{""Key1"":[{""Key1"":1,""Key2"":2},{""Key1"":3,""Key2"":4}],""Key2"":[{""Key1"":5,""Key2"":6},{""Key1"":7,""Key2"":8}]}"; Dictionary<string, Dictionary<string, int>[]> obj = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>[]>>(JsonString); Assert.Equal(2, obj.Count); Assert.Equal(2, obj["Key1"].Length); Assert.Equal(2, obj["Key1"][0].Count); Assert.Equal(2, obj["Key1"][1].Count); Assert.Equal(1, obj["Key1"][0]["Key1"]); Assert.Equal(2, obj["Key1"][0]["Key2"]); Assert.Equal(3, obj["Key1"][1]["Key1"]); Assert.Equal(4, obj["Key1"][1]["Key2"]); Assert.Equal(2, obj["Key2"].Length); Assert.Equal(2, obj["Key2"][0].Count); Assert.Equal(2, obj["Key2"][1].Count); Assert.Equal(5, obj["Key2"][0]["Key1"]); Assert.Equal(6, obj["Key2"][0]["Key2"]); Assert.Equal(7, obj["Key2"][1]["Key1"]); Assert.Equal(8, obj["Key2"][1]["Key2"]); string json = JsonSerializer.Serialize(obj); Assert.Equal(JsonString, json); // Verify that typeof(object) doesn't interfere. json = JsonSerializer.Serialize<object>(obj); Assert.Equal(JsonString, json); } [Fact] public static void DictionaryOfClasses() { { IDictionary obj; { string json = @"{""Key1"":" + SimpleTestClass.s_json + @",""Key2"":" + SimpleTestClass.s_json + "}"; obj = JsonSerializer.Deserialize<IDictionary>(json); Assert.Equal(2, obj.Count); if (obj["Key1"] is JsonElement element) { SimpleTestClass result = JsonSerializer.Deserialize<SimpleTestClass>(element.GetRawText()); result.Verify(); } else { ((SimpleTestClass)obj["Key1"]).Verify(); ((SimpleTestClass)obj["Key2"]).Verify(); } } { // We can't compare against the json string above because property ordering is not deterministic (based on reflection order) // so just round-trip the json and compare. string json = JsonSerializer.Serialize(obj); obj = JsonSerializer.Deserialize<IDictionary>(json); Assert.Equal(2, obj.Count); if (obj["Key1"] is JsonElement element) { SimpleTestClass result = JsonSerializer.Deserialize<SimpleTestClass>(element.GetRawText()); result.Verify(); } else { ((SimpleTestClass)obj["Key1"]).Verify(); ((SimpleTestClass)obj["Key2"]).Verify(); } } { string json = JsonSerializer.Serialize<object>(obj); obj = JsonSerializer.Deserialize<IDictionary>(json); Assert.Equal(2, obj.Count); if (obj["Key1"] is JsonElement element) { SimpleTestClass result = JsonSerializer.Deserialize<SimpleTestClass>(element.GetRawText()); result.Verify(); } else { ((SimpleTestClass)obj["Key1"]).Verify(); ((SimpleTestClass)obj["Key2"]).Verify(); } } } { Dictionary<string, SimpleTestClass> obj; { string json = @"{""Key1"":" + SimpleTestClass.s_json + @",""Key2"":" + SimpleTestClass.s_json + "}"; obj = JsonSerializer.Deserialize<Dictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } { // We can't compare against the json string above because property ordering is not deterministic (based on reflection order) // so just round-trip the json and compare. string json = JsonSerializer.Serialize(obj); obj = JsonSerializer.Deserialize<Dictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } { string json = JsonSerializer.Serialize<object>(obj); obj = JsonSerializer.Deserialize<Dictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } } { ImmutableSortedDictionary<string, SimpleTestClass> obj; { string json = @"{""Key1"":" + SimpleTestClass.s_json + @",""Key2"":" + SimpleTestClass.s_json + "}"; obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } { // We can't compare against the json string above because property ordering is not deterministic (based on reflection order) // so just round-trip the json and compare. string json = JsonSerializer.Serialize(obj); obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } { string json = JsonSerializer.Serialize<object>(obj); obj = JsonSerializer.Deserialize<ImmutableSortedDictionary<string, SimpleTestClass>>(json); Assert.Equal(2, obj.Count); obj["Key1"].Verify(); obj["Key2"].Verify(); } } } [Fact] public static void UnicodePropertyNames() { var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; { Dictionary<string, int> obj; obj = JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""A\u0467"":1}"); Assert.Equal(1, obj["A\u0467"]); // Specifying encoder on options does not impact deserialize. obj = JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""A\u0467"":1}", options); Assert.Equal(1, obj["A\u0467"]); string json; // Verify the name is escaped after serialize. json = JsonSerializer.Serialize(obj); Assert.Equal(@"{""A\u0467"":1}", json); // Verify with encoder. json = JsonSerializer.Serialize(obj, options); Assert.Equal("{\"A\u0467\":1}", json); } { // We want to go over StackallocThreshold=256 to force a pooled allocation, so this property is 200 chars and 400 bytes. const int charsInProperty = 200; string longPropertyName = new string('\u0467', charsInProperty); Dictionary<string, int> obj = JsonSerializer.Deserialize<Dictionary<string, int>>($"{{\"{longPropertyName}\":1}}"); Assert.Equal(1, obj[longPropertyName]); // Verify the name is escaped after serialize. string json = JsonSerializer.Serialize(obj); // Duplicate the unicode character 'charsInProperty' times. string longPropertyNameEscaped = new StringBuilder().Insert(0, @"\u0467", charsInProperty).ToString(); string expectedJson = $"{{\"{longPropertyNameEscaped}\":1}}"; Assert.Equal(expectedJson, json); // Verify the name is unescaped after deserialize. obj = JsonSerializer.Deserialize<Dictionary<string, int>>(json); Assert.Equal(1, obj[longPropertyName]); } } [Fact] public static void CustomEscapingOnPropertyNameAndValue() { var dict = new Dictionary<string, string>(); dict.Add("A\u046701","Value\u0467"); // Baseline with no escaping. var json = JsonSerializer.Serialize(dict); Assert.Equal("{\"A\\u046701\":\"Value\\u0467\"}", json); // Enable escaping. var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; json = JsonSerializer.Serialize(dict, options); Assert.Equal("{\"A\u046701\":\"Value\u0467\"}", json); } [Fact] public static void ObjectToStringFail() { // Baseline string json = @"{""MyDictionary"":{""Key"":""Value""}}"; JsonSerializer.Deserialize<Dictionary<string, object>>(json); Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, string>>(json)); } [Fact, ActiveIssue("JsonElement fails since it is a struct.")] public static void ObjectToJsonElement() { string json = @"{""MyDictionary"":{""Key"":""Value""}}"; JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json); } [Fact] public static void HashtableFail() { { IDictionary ht = new Hashtable(); ht.Add("Key", "Value"); Assert.Equal(@"{""Key"":""Value""}", JsonSerializer.Serialize(ht)); } } [Fact] public static void DeserializeDictionaryWithDuplicateKeys() { // Non-generic IDictionary case. IDictionary iDictionary = JsonSerializer.Deserialize<IDictionary>(@"{""Hello"":""World"", ""Hello"":""NewValue""}"); Assert.Equal("NewValue", iDictionary["Hello"].ToString()); // Generic IDictionary case. IDictionary<string, string> iNonGenericDictionary = JsonSerializer.Deserialize<IDictionary<string, string>>(@"{""Hello"":""World"", ""Hello"":""NewValue""}"); Assert.Equal("NewValue", iNonGenericDictionary["Hello"]); IDictionary<string, object> iNonGenericObjectDictionary = JsonSerializer.Deserialize<IDictionary<string, object>>(@"{""Hello"":""World"", ""Hello"":""NewValue""}"); Assert.Equal("NewValue", iNonGenericObjectDictionary["Hello"].ToString()); // Strongly-typed IDictionary<,> case. Dictionary<string, string> dictionary = JsonSerializer.Deserialize<Dictionary<string, string>>(@"{""Hello"":""World"", ""Hello"":""NewValue""}"); Assert.Equal("NewValue", dictionary["Hello"]); dictionary = JsonSerializer.Deserialize<Dictionary<string, string>>(@"{""Hello"":""World"", ""myKey"" : ""myValue"", ""Hello"":""NewValue""}"); Assert.Equal("NewValue", dictionary["Hello"]); // Weakly-typed IDictionary case. Dictionary<string, object> dictionaryObject = JsonSerializer.Deserialize<Dictionary<string, object>>(@"{""Hello"":""World"", ""Hello"": null}"); Assert.Null(dictionaryObject["Hello"]); } [Fact] public static void DeserializeDictionaryWithDuplicateProperties() { PocoDuplicate foo = JsonSerializer.Deserialize<PocoDuplicate>(@"{""BoolProperty"": false, ""BoolProperty"": true}"); Assert.True(foo.BoolProperty); foo = JsonSerializer.Deserialize<PocoDuplicate>(@"{""BoolProperty"": false, ""IntProperty"" : 1, ""BoolProperty"": true , ""IntProperty"" : 2}"); Assert.True(foo.BoolProperty); Assert.Equal(2, foo.IntProperty); foo = JsonSerializer.Deserialize<PocoDuplicate>(@"{""DictProperty"" : {""a"" : ""b"", ""c"" : ""d""},""DictProperty"" : {""b"" : ""b"", ""c"" : ""e""}}"); Assert.Equal(2, foo.DictProperty.Count); // We don't concat. Assert.Equal("e", foo.DictProperty["c"]); } public class PocoDuplicate { public bool BoolProperty { get; set; } public int IntProperty { get; set; } public Dictionary<string, string> DictProperty { get; set; } } public class ClassWithPopulatedDictionaryAndNoSetter { public ClassWithPopulatedDictionaryAndNoSetter() { MyImmutableDictionary = MyImmutableDictionary.Add("Key", "Value"); } public Dictionary<string, string> MyDictionary { get; } = new Dictionary<string, string>() { { "Key", "Value" } }; public ImmutableDictionary<string, string> MyImmutableDictionary { get; } = ImmutableDictionary.Create<string, string>(); } [Fact] public static void ClassWithNoSetterAndDictionary() { // We don't attempt to deserialize into dictionaries without a setter. string json = @"{""MyDictionary"":{""Key1"":""Value1"", ""Key2"":""Value2""}}"; ClassWithPopulatedDictionaryAndNoSetter obj = JsonSerializer.Deserialize<ClassWithPopulatedDictionaryAndNoSetter>(json); Assert.Equal(1, obj.MyDictionary.Count); } [Fact] public static void ClassWithNoSetterAndImmutableDictionary() { // We don't attempt to deserialize into dictionaries without a setter. string json = @"{""MyImmutableDictionary"":{""Key1"":""Value1"", ""Key2"":""Value2""}}"; ClassWithPopulatedDictionaryAndNoSetter obj = JsonSerializer.Deserialize<ClassWithPopulatedDictionaryAndNoSetter>(json); Assert.Equal(1, obj.MyImmutableDictionary.Count); } public class ClassWithIgnoredDictionary1 { public Dictionary<string, int> Parsed1 { get; set; } public Dictionary<string, int> Parsed2 { get; set; } public Dictionary<string, int> Skipped3 { get; } } public class ClassWithIgnoredDictionary2 { public IDictionary<string, int> Parsed1 { get; set; } public IDictionary<string, int> Skipped2 { get; } public IDictionary<string, int> Parsed3 { get; set; } } public class ClassWithIgnoredDictionary3 { public Dictionary<string, int> Parsed1 { get; set; } public Dictionary<string, int> Skipped2 { get; } public Dictionary<string, int> Skipped3 { get; } } public class ClassWithIgnoredDictionary4 { public Dictionary<string, int> Skipped1 { get; } public Dictionary<string, int> Parsed2 { get; set; } public Dictionary<string, int> Parsed3 { get; set; } } public class ClassWithIgnoredDictionary5 { public Dictionary<string, int> Skipped1 { get; } public Dictionary<string, int> Parsed2 { get; set; } public Dictionary<string, int> Skipped3 { get; } } public class ClassWithIgnoredDictionary6 { public Dictionary<string, int> Skipped1 { get; } public Dictionary<string, int> Skipped2 { get; } public Dictionary<string, int> Parsed3 { get; set; } } public class ClassWithIgnoredDictionary7 { public Dictionary<string, int> Skipped1 { get; } public Dictionary<string, int> Skipped2 { get; } public Dictionary<string, int> Skipped3 { get; } } public class ClassWithIgnoredIDictionary { public IDictionary<string, int> Parsed1 { get; set; } public IDictionary<string, int> Skipped2 { get; } public IDictionary<string, int> Parsed3 { get; set; } } public class ClassWithIgnoreAttributeDictionary { public Dictionary<string, int> Parsed1 { get; set; } [JsonIgnore] public Dictionary<string, int> Skipped2 { get; set; } // Note this has a setter. public Dictionary<string, int> Parsed3 { get; set; } } public class ClassWithIgnoredImmutableDictionary { public ImmutableDictionary<string, int> Parsed1 { get; set; } public ImmutableDictionary<string, int> Skipped2 { get; } public ImmutableDictionary<string, int> Parsed3 { get; set; } } [Theory] [InlineData(@"{""Parsed1"":{""Key"":1},""Parsed3"":{""Key"":2}}")] // No value for skipped property [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":{}, ""Parsed3"":{""Key"":2}}")] // Empty object {} skipped [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":null, ""Parsed3"":{""Key"":2}}")] // null object skipped [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":{""Key"":9}, ""Parsed3"":{""Key"":2}}")] // Valid "int" values skipped // Invalid "int" values: [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":{""Key"":[1,2,3]}, ""Parsed3"":{""Key"":2}}")] [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":{""Key"":{}}, ""Parsed3"":{""Key"":2}}")] [InlineData(@"{""Parsed1"":{""Key"":1},""Skipped2"":{""Key"":null}, ""Parsed3"":{""Key"":2}}")] public static void IgnoreDictionaryProperty(string json) { // Verify deserialization ClassWithIgnoredDictionary2 obj = JsonSerializer.Deserialize<ClassWithIgnoredDictionary2>(json); Assert.Equal(1, obj.Parsed1.Count); Assert.Equal(1, obj.Parsed1["Key"]); Assert.Null(obj.Skipped2); Assert.Equal(1, obj.Parsed3.Count); Assert.Equal(2, obj.Parsed3["Key"]); // Round-trip and verify. string jsonRoundTripped = JsonSerializer.Serialize(obj); ClassWithIgnoredDictionary2 objRoundTripped = JsonSerializer.Deserialize<ClassWithIgnoredDictionary2>(jsonRoundTripped); Assert.Equal(1, objRoundTripped.Parsed1.Count); Assert.Equal(1, objRoundTripped.Parsed1["Key"]); Assert.Null(objRoundTripped.Skipped2); Assert.Equal(1, objRoundTripped.Parsed3.Count); Assert.Equal(2, objRoundTripped.Parsed3["Key"]); } [Fact] public static void IgnoreDictionaryPropertyWithDifferentOrdering() { // Verify all combinations of 3 properties with at least one ignore. VerifyIgnore<ClassWithIgnoredDictionary1>(false, false, true); VerifyIgnore<ClassWithIgnoredDictionary2>(false, true, false); VerifyIgnore<ClassWithIgnoredDictionary3>(false, true, true); VerifyIgnore<ClassWithIgnoredDictionary4>(true, false, false); VerifyIgnore<ClassWithIgnoredDictionary5>(true, false, true); VerifyIgnore<ClassWithIgnoredDictionary6>(true, true, false); VerifyIgnore<ClassWithIgnoredDictionary7>(true, true, true); // Verify single case for IDictionary, [Ignore] and ImmutableDictionary. // Also specify addMissing to add additional skipped JSON that does not have a corresponding property. VerifyIgnore<ClassWithIgnoredIDictionary>(false, true, false, addMissing: true); VerifyIgnore<ClassWithIgnoreAttributeDictionary>(false, true, false, addMissing: true); VerifyIgnore<ClassWithIgnoredImmutableDictionary>(false, true, false, addMissing: true); } private static void VerifyIgnore<T>(bool skip1, bool skip2, bool skip3, bool addMissing = false) { static IDictionary<string, int> GetProperty(T objectToVerify, string propertyName) { return (IDictionary<string, int>)objectToVerify.GetType().GetProperty(propertyName).GetValue(objectToVerify); } void Verify(T objectToVerify) { if (skip1) { Assert.Null(GetProperty(objectToVerify, "Skipped1")); } else { Assert.Equal(1, GetProperty(objectToVerify, "Parsed1")["Key"]); } if (skip2) { Assert.Null(GetProperty(objectToVerify, "Skipped2")); } else { Assert.Equal(2, GetProperty(objectToVerify, "Parsed2")["Key"]); } if (skip3) { Assert.Null(GetProperty(objectToVerify, "Skipped3")); } else { Assert.Equal(3, GetProperty(objectToVerify, "Parsed3")["Key"]); } } // Tests that the parser picks back up after skipping/draining ignored elements. StringBuilder json = new StringBuilder(@"{"); if (addMissing) { json.Append(@"""MissingProp1"": {},"); } if (skip1) { json.Append(@"""Skipped1"":{},"); } else { json.Append(@"""Parsed1"":{""Key"":1},"); } if (addMissing) { json.Append(@"""MissingProp2"": null,"); } if (skip2) { json.Append(@"""Skipped2"":{},"); } else { json.Append(@"""Parsed2"":{""Key"":2},"); } if (addMissing) { json.Append(@"""MissingProp3"": {""ABC"":{}},"); } if (skip3) { json.Append(@"""Skipped3"":{}}"); } else { json.Append(@"""Parsed3"":{""Key"":3}}"); } // Deserialize and verify. string jsonString = json.ToString(); T obj = JsonSerializer.Deserialize<T>(jsonString); Verify(obj); // Round-trip and verify. // Any skipped properties due to lack of a setter will now be "null" when serialized instead of "{}". string jsonStringRoundTripped = JsonSerializer.Serialize(obj); T objRoundTripped = JsonSerializer.Deserialize<T>(jsonStringRoundTripped); Verify(objRoundTripped); } public class ClassWithPopulatedDictionaryAndSetter { public ClassWithPopulatedDictionaryAndSetter() { MyImmutableDictionary = MyImmutableDictionary.Add("Key", "Value"); } public Dictionary<string, string> MyDictionary { get; set; } = new Dictionary<string, string>() { { "Key", "Value" } }; public ImmutableDictionary<string, string> MyImmutableDictionary { get; set; } = ImmutableDictionary.Create<string, string>(); } [Fact] public static void ClassWithPopulatedDictionary() { // We replace the contents. string json = @"{""MyDictionary"":{""Key1"":""Value1"", ""Key2"":""Value2""}}"; ClassWithPopulatedDictionaryAndSetter obj = JsonSerializer.Deserialize<ClassWithPopulatedDictionaryAndSetter>(json); Assert.Equal(2, obj.MyDictionary.Count); } [Fact] public static void ClassWithPopulatedImmutableDictionary() { // We replace the contents. string json = @"{""MyImmutableDictionary"":{""Key1"":""Value1"", ""Key2"":""Value2""}}"; ClassWithPopulatedDictionaryAndSetter obj = JsonSerializer.Deserialize<ClassWithPopulatedDictionaryAndSetter>(json); Assert.Equal(2, obj.MyImmutableDictionary.Count); } [Fact] public static void DictionaryNotSupported() { string json = @"{""MyDictionary"":{""Key"":""Value""}}"; try { JsonSerializer.Deserialize<ClassWithNotSupportedDictionary>(json); Assert.True(false, "Expected NotSupportedException to be thrown."); } catch (NotSupportedException e) { // The exception should contain className.propertyName and the invalid type. Assert.Contains("ClassWithNotSupportedDictionary.MyDictionary", e.Message); Assert.Contains("Dictionary`2[System.Int32,System.Int32]", e.Message); } } [Fact] public static void DictionaryNotSupportedButIgnored() { string json = @"{""MyDictionary"":{""Key"":1}}"; ClassWithNotSupportedDictionaryButIgnored obj = JsonSerializer.Deserialize<ClassWithNotSupportedDictionaryButIgnored>(json); Assert.Null(obj.MyDictionary); } [Fact] public static void Regression38643_Serialize() { // Arrange var value = new Regression38643_Parent() { Child = new Dictionary<string, Regression38643_Child>() { ["1"] = new Regression38643_Child() { A = "1", B = string.Empty, C = Array.Empty<string>(), D = Array.Empty<string>(), F = Array.Empty<string>(), K = Array.Empty<string>(), } } }; var actual = JsonSerializer.Serialize(value, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); // Assert Assert.NotNull(actual); Assert.NotEmpty(actual); } [Fact] public static void Regression38643_Deserialize() { // Arrange string json = "{\"child\":{\"1\":{\"a\":\"1\",\"b\":\"\",\"c\":[],\"d\":[],\"e\":null,\"f\":[],\"g\":null,\"h\":null,\"i\":null,\"j\":null,\"k\":[]}}}"; var actual = JsonSerializer.Deserialize<Regression38643_Parent>(json, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); // Assert Assert.NotNull(actual); Assert.NotNull(actual.Child); Assert.Equal(1, actual.Child.Count); Assert.True(actual.Child.ContainsKey("1")); Assert.Equal("1", actual.Child["1"].A); } [Fact] public static void Regression38565_Serialize() { var value = new Regression38565_Parent() { Test = "value1", Child = new Regression38565_Child() }; var actual = JsonSerializer.Serialize(value); Assert.Equal("{\"Test\":\"value1\",\"Dict\":null,\"Child\":{\"Test\":null,\"Dict\":null}}", actual); } [Fact] public static void Regression38565_Deserialize() { var json = "{\"Test\":\"value1\",\"Dict\":null,\"Child\":{\"Test\":null,\"Dict\":null}}"; Regression38565_Parent actual = JsonSerializer.Deserialize<Regression38565_Parent>(json); Assert.Equal("value1", actual.Test); Assert.Null(actual.Dict); Assert.NotNull(actual.Child); Assert.Null(actual.Child.Dict); Assert.Null(actual.Child.Test); } [Fact] public static void Regression38565_Serialize_IgnoreNullValues() { var value = new Regression38565_Parent() { Test = "value1", Child = new Regression38565_Child() }; var actual = JsonSerializer.Serialize(value, new JsonSerializerOptions { IgnoreNullValues = true }); Assert.Equal("{\"Test\":\"value1\",\"Child\":{}}", actual); } [Fact] public static void Regression38565_Deserialize_IgnoreNullValues() { var json = "{\"Test\":\"value1\",\"Child\":{}}"; Regression38565_Parent actual = JsonSerializer.Deserialize<Regression38565_Parent>(json); Assert.Equal("value1", actual.Test); Assert.Null(actual.Dict); Assert.NotNull(actual.Child); Assert.Null(actual.Child.Dict); Assert.Null(actual.Child.Test); } [Fact] public static void Regression38557_Serialize() { var dictionaryFirst = new Regression38557_DictionaryFirst() { Test = "value1" }; var actual = JsonSerializer.Serialize(dictionaryFirst); Assert.Equal("{\"Dict\":null,\"Test\":\"value1\"}", actual); var dictionaryLast = new Regression38557_DictionaryLast() { Test = "value1" }; actual = JsonSerializer.Serialize(dictionaryLast); Assert.Equal("{\"Test\":\"value1\",\"Dict\":null}", actual); } [Fact] public static void Regression38557_Deserialize() { var json = "{\"Dict\":null,\"Test\":\"value1\"}"; Regression38557_DictionaryFirst dictionaryFirst = JsonSerializer.Deserialize<Regression38557_DictionaryFirst>(json); Assert.Equal("value1", dictionaryFirst.Test); Assert.Null(dictionaryFirst.Dict); json = "{\"Test\":\"value1\",\"Dict\":null}"; Regression38557_DictionaryLast dictionaryLast = JsonSerializer.Deserialize<Regression38557_DictionaryLast>(json); Assert.Equal("value1", dictionaryLast.Test); Assert.Null(dictionaryLast.Dict); } [Fact] public static void Regression38557_Serialize_IgnoreNullValues() { var dictionaryFirst = new Regression38557_DictionaryFirst() { Test = "value1" }; var actual = JsonSerializer.Serialize(dictionaryFirst, new JsonSerializerOptions { IgnoreNullValues = true }); Assert.Equal("{\"Test\":\"value1\"}", actual); var dictionaryLast = new Regression38557_DictionaryLast() { Test = "value1" }; actual = JsonSerializer.Serialize(dictionaryLast, new JsonSerializerOptions { IgnoreNullValues = true }); Assert.Equal("{\"Test\":\"value1\"}", actual); } [Fact] public static void Regression38557_Deserialize_IgnoreNullValues() { var json = "{\"Test\":\"value1\"}"; Regression38557_DictionaryFirst dictionaryFirst = JsonSerializer.Deserialize<Regression38557_DictionaryFirst>(json); Assert.Equal("value1", dictionaryFirst.Test); Assert.Null(dictionaryFirst.Dict); json = "{\"Test\":\"value1\"}"; Regression38557_DictionaryLast dictionaryLast = JsonSerializer.Deserialize<Regression38557_DictionaryLast>(json); Assert.Equal("value1", dictionaryLast.Test); Assert.Null(dictionaryLast.Dict); } [Fact] public static void NullDictionaryValuesShouldDeserializeAsNull() { const string json = @"{" + @"""StringVals"":{" + @"""key"":null" + @"}," + @"""ObjectVals"":{" + @"""key"":null" + @"}," + @"""StringDictVals"":{" + @"""key"":null" + @"}," + @"""ObjectDictVals"":{" + @"""key"":null" + @"}," + @"""ClassVals"":{" + @"""key"":null" + @"}" + @"}"; SimpleClassWithDictionaries obj = JsonSerializer.Deserialize<SimpleClassWithDictionaries>(json); Assert.Null(obj.StringVals["key"]); Assert.Null(obj.ObjectVals["key"]); Assert.Null(obj.StringDictVals["key"]); Assert.Null(obj.ObjectDictVals["key"]); Assert.Null(obj.ClassVals["key"]); } public class ClassWithNotSupportedDictionary { public Dictionary<int, int> MyDictionary { get; set; } } public class ClassWithNotSupportedDictionaryButIgnored { [JsonIgnore] public Dictionary<int, int> MyDictionary { get; set; } } public class Regression38643_Parent { public IDictionary<string, Regression38643_Child> Child { get; set; } } public class Regression38643_Child { public string A { get; set; } public string B { get; set; } public string[] C { get; set; } public string[] D { get; set; } public bool? E { get; set; } public string[] F { get; set; } public DateTimeOffset? G { get; set; } public DateTimeOffset? H { get; set; } public int? I { get; set; } public int? J { get; set; } public string[] K { get; set; } } public class Regression38565_Parent { public string Test { get; set; } public Dictionary<string, string> Dict { get; set; } public Regression38565_Child Child { get; set; } } public class Regression38565_Child { public string Test { get; set; } public Dictionary<string, string> Dict { get; set; } } public class Regression38557_DictionaryLast { public string Test { get; set; } public Dictionary<string, string> Dict { get; set; } } public class Regression38557_DictionaryFirst { public Dictionary<string, string> Dict { get; set; } public string Test { get; set; } } public class SimpleClassWithDictionaries { public Dictionary<string, string> StringVals { get; set; } public Dictionary<string, object> ObjectVals { get; set; } public Dictionary<string, Dictionary<string, string>> StringDictVals { get; set; } public Dictionary<string, Dictionary<string, object>> ObjectDictVals { get; set; } public Dictionary<string, SimpleClassWithDictionaries> ClassVals { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public static class ParallelEnumerableTests { // // Null query // [Fact] public static void NullQuery() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).AsParallel()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable)null).AsParallel()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((Partitioner<int>)null).AsParallel()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((int[])null).AsParallel()); AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsOrdered((ParallelQuery<int>)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsOrdered((ParallelQuery)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ParallelEnumerable.AsUnordered<int>((ParallelQuery<int>)null)); } // // Range // public static IEnumerable<object[]> RangeData() { int[] datapoints = { 0, 1, 2, 16, }; foreach (int sign in new[] { -1, 1 }) { foreach (int start in datapoints) { foreach (int count in datapoints) { yield return new object[] { start * sign, count }; } } } yield return new object[] { int.MaxValue, 0 }; yield return new object[] { int.MaxValue, 1 }; yield return new object[] { int.MaxValue - 8, 8 + 1 }; yield return new object[] { int.MinValue, 0 }; yield return new object[] { int.MinValue, 1 }; } [Theory] [MemberData(nameof(RangeData))] public static void Range_UndefinedOrder(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(RangeData))] public static void Range_AsOrdered(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).AsOrdered(); int current = start; Assert.All(query, x => Assert.Equal(unchecked(current++), x)); Assert.Equal(count, unchecked(current - start)); } [Theory] [MemberData(nameof(RangeData))] public static void Range_AsSequential(int start, int count) { IEnumerable<int> query = ParallelEnumerable.Range(start, count).AsSequential(); int current = start; Assert.All(query, x => Assert.Equal(unchecked(current++), x)); Assert.Equal(count, unchecked(current - start)); } [Theory] [MemberData(nameof(RangeData))] public static void Range_First(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); if (count == 0) { Assert.Throws<InvalidOperationException>(() => query.First()); } else { Assert.Equal(start, query.First()); } } [Theory] [MemberData(nameof(RangeData))] public static void Range_FirstOrDefault(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); Assert.Equal(count == 0 ? 0 : start, query.FirstOrDefault()); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Last(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); if (count == 0) { Assert.Throws<InvalidOperationException>(() => query.Last()); } else { Assert.Equal(start + (count - 1), query.Last()); } } [Theory] [MemberData(nameof(RangeData))] public static void Range_LastOrDefault(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count); Assert.Equal(count == 0 ? 0 : start + (count - 1), query.LastOrDefault()); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Take(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Take(count / 2); // Elements are taken from the first half of the list, but order is indeterminate. IntegerRangeSet seen = new IntegerRangeSet(start, count / 2); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(RangeData))] public static void Range_Skip(int start, int count) { ParallelQuery<int> query = ParallelEnumerable.Range(start, count).Skip(count / 2); // Skips over the first half of the list, but order is indeterminate. IntegerRangeSet seen = new IntegerRangeSet(start + count / 2, (count + 1) / 2); Assert.All(query, x => seen.Add(x)); seen.AssertComplete(); Assert.Empty(ParallelEnumerable.Range(start, count).Skip(count + 1)); } [Fact] public static void Range_Exception() { Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(-8, -8)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Range(int.MaxValue, 2)); } // // Repeat // public static IEnumerable<object[]> RepeatData() { int[] datapoints = new[] { 0, 1, 2, 16, 128, 1024 }; foreach (int count in datapoints) { foreach (int element in datapoints) { yield return new object[] { element, count }; yield return new object[] { (long)element, count }; yield return new object[] { (double)element, count }; yield return new object[] { (decimal)element, count }; yield return new object[] { "" + element, count }; } yield return new object[] { (object)null, count }; yield return new object[] { (string)null, count }; } } [Theory] [MemberData(nameof(RepeatData))] public static void Repeat<T>(T element, int count) { ParallelQuery<T> query = ParallelEnumerable.Repeat(element, count); int counted = 0; Assert.All(query, e => { counted++; Assert.Equal(element, e); }); Assert.Equal(count, counted); } [Theory] [MemberData(nameof(RepeatData))] public static void Repeat_Select<T>(T element, int count) { ParallelQuery<T> query = ParallelEnumerable.Repeat(element, count).Select(i => i); int counted = 0; Assert.All(query, e => { counted++; Assert.Equal(element, e); }); Assert.Equal(count, counted); } [Fact] public static void Repeat_Exception() { Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(1, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((long)1024, -1024)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat(2.0, -2)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((decimal)8, -8)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat("fail", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ParallelEnumerable.Repeat((string)null, -1)); } [Fact] public static void Repeat_Reset() { const int Value = 42; const int Iterations = 3; ParallelQuery<int> q = ParallelEnumerable.Repeat(Value, Iterations); IEnumerator<int> e = q.GetEnumerator(); for (int i = 0; i < 2; i++) { int count = 0; while (e.MoveNext()) { Assert.Equal(Value, e.Current); count++; } Assert.False(e.MoveNext()); Assert.Equal(Iterations, count); e.Reset(); } } // // Empty // public static IEnumerable<object[]> EmptyData() { yield return new object[] { default(int) }; yield return new object[] { default(long) }; yield return new object[] { default(double) }; yield return new object[] { default(decimal) }; yield return new object[] { default(string) }; yield return new object[] { default(object) }; } [Theory] [MemberData(nameof(EmptyData))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "This causes assertion failure on UAPAoT")] public static void Empty<T>(T def) { Assert.Empty(ParallelEnumerable.Empty<T>()); Assert.False(ParallelEnumerable.Empty<T>().Any(x => true)); Assert.False(ParallelEnumerable.Empty<T>().Contains(default(T))); Assert.Equal(0, ParallelEnumerable.Empty<T>().Count()); Assert.Equal(0, ParallelEnumerable.Empty<T>().LongCount()); Assert.Equal(new T[0], ParallelEnumerable.Empty<T>().ToArray()); Assert.Equal(new Dictionary<T, T>(), ParallelEnumerable.Empty<T>().ToDictionary(x => x)); Assert.Equal(new List<T>(), ParallelEnumerable.Empty<T>().ToList()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().First()); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<T>().Last()); } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Scripting; using Axiom.Animating; namespace Axiom.Core { /// <summary> /// Abstract class definining a movable object in a scene. /// </summary> /// <remarks> /// Instances of this class are discrete, relatively small, movable objects /// which are attached to SceneNode objects to define their position. /// </remarks> public abstract class MovableObject : ShadowCaster, IAnimableObject { #region Fields /// <summary> /// Node that this node is attached to. /// </summary> protected Node parentNode; /// <summary> /// Is this object visible? /// </summary> protected bool isVisible; /// <summary> /// Name of this object. /// </summary> protected string name; /// <summary> /// The render queue to use when rendering this object. /// </summary> protected RenderQueueGroupID renderQueueID; protected bool renderQueueIDSet = false; /// <summary> /// Flags determining whether this object is included/excluded from scene queries. /// </summary> protected ulong queryFlags; /// <summary> /// Cached world bounding box of this object. /// </summary> protected AxisAlignedBox worldAABB; /// <summary> /// Cached world bounding spehere. /// </summary> protected Sphere worldBoundingSphere = new Sphere(); /// <summary> /// A link back to a GameObject (or subclass thereof) that may be associated with this SceneObject. /// </summary> protected object userData; /// <summary> /// Flag which indicates whether this objects parent is a <see cref="TagPoint"/>. /// </summary> protected bool parentIsTagPoint; /// <summary> /// World space AABB of this object's dark cap. /// </summary> protected AxisAlignedBox worldDarkCapBounds = AxisAlignedBox.Null; /// <summary> /// Does this object cast shadows? /// </summary> protected bool castShadows; protected ShadowRenderableList dummyList = new ShadowRenderableList(); #endregion Fields #region Constructors /// <summary> /// Default constructor. /// </summary> public MovableObject() { isVisible = true; // set default RenderQueueGroupID for this movable object renderQueueID = RenderQueueGroupID.Main; queryFlags = unchecked(0xffffffff); worldAABB = AxisAlignedBox.Null; castShadows = true; } public MovableObject(string name) { this.Name = name; isVisible = true; // set default RenderQueueGroupID for this movable object renderQueueID = RenderQueueGroupID.Main; queryFlags = unchecked(0xffffffff); worldAABB = AxisAlignedBox.Null; castShadows = true; } #endregion Constructors #region Properties /// <summary> /// An abstract method required by subclasses to return the bounding box of this object in local coordinates. /// </summary> public abstract AxisAlignedBox BoundingBox { get; } /// <summary> /// An abstract method required by subclasses to return the bounding box of this object in local coordinates. /// </summary> public abstract float BoundingRadius { get; } /// <summary> /// Get/Sets a link back to a GameObject (or subclass thereof, such as Entity) that may be associated with this SceneObject. /// </summary> public object UserData { get { return userData; } set { userData = value; } } /// <summary> /// Gets the parent node that this object is attached to. /// </summary> public Node ParentNode { get { return parentNode; } } /// <summary> /// See if this object is attached to another node. /// </summary> public bool IsAttached { get { return (parentNode != null); } } /// <summary> /// States whether or not this object should be visible. /// </summary> public virtual bool IsVisible { get { return isVisible; } set { isVisible = value; } } /// <summary> /// Name of this SceneObject. /// </summary> public virtual string Name { get { return name; } set { name = value; } } /// <summary> /// Returns the full transformation of the parent SceneNode or the attachingPoint node /// </summary> public virtual Matrix4 ParentFullTransform { get { if(parentNode != null) return parentNode.FullTransform; // identity if no parent return Matrix4.Identity; } } /// <summary> /// Gets the full transformation of the parent SceneNode or TagPoint. /// </summary> public virtual Matrix4 ParentNodeFullTransform { get { if(parentNode != null) { // object is attached to a node, so return the nodes transform return parentNode.FullTransform; } // fallback return Matrix4.Identity; } } /// <summary> /// Gets/Sets the query flags for this object. /// </summary> /// <remarks> /// When performing a scene query, this object will be included or excluded according /// to flags on the object and flags on the query. This is a bitwise value, so only when /// a bit on these flags is set, will it be included in a query asking for that flag. The /// meaning of the bits is application-specific. /// </remarks> public ulong QueryFlags { get { return queryFlags; } set { queryFlags = value; } } /// <summary> /// Allows showing the bounding box of an invidual SceneObject. /// </summary> /// <remarks> /// This shows the bounding box of the SceneNode that the SceneObject is currently attached to. /// </remarks> public bool ShowBoundingBox { get { return ((SceneNode)parentNode).ShowBoundingBox; } set { ((SceneNode)parentNode).ShowBoundingBox = value; } } /// <summary> /// Gets/Sets the render queue group this entity will be rendered through. /// </summary> /// <remarks> /// Render queues are grouped to allow you to more tightly control the ordering /// of rendered objects. If you do not call this method, all Entity objects default /// to <see cref="RenderQueueGroupID.Main"/> which is fine for most objects. You may want to alter this /// if you want this entity to always appear in front of other objects, e.g. for /// a 3D menu system or such. /// </remarks> public RenderQueueGroupID RenderQueueGroup { get { return renderQueueID; } set { renderQueueID = value; renderQueueIDSet = true; } } #endregion Properties #region Methods /// <summary> /// Appends the specified flags to the current flags for this object. /// </summary> /// <param name="flags"></param> public void AddQueryFlags(ulong flags) { queryFlags |= flags; } /// <summary> /// Retrieves the axis-aligned bounding box for this object in world coordinates. /// </summary> /// <returns></returns> public override AxisAlignedBox GetWorldBoundingBox(bool derive) { if(derive && this.BoundingBox != null) { worldAABB = this.BoundingBox; worldAABB.Transform(this.ParentFullTransform); ComputeContainedWorldAABBs(); } return worldAABB; } /// <summary> /// Provide a way for subclasses to recompute the world /// AABBs of contained entities, i.e., SubEntities. /// </summary> public virtual void ComputeContainedWorldAABBs() { } /// <summary> /// Overloaded method. Calls the overload with a default of not deriving the transform. /// </summary> /// <returns></returns> public Sphere GetWorldBoundingSphere() { return GetWorldBoundingSphere(false); } /// <summary> /// Retrieves the worldspace bounding sphere for this object. /// </summary> /// <param name="derive">Whether or not to derive from parent transforms.</param> /// <returns></returns> public virtual Sphere GetWorldBoundingSphere(bool derive) { if(derive) { worldBoundingSphere.Radius = this.BoundingRadius; worldBoundingSphere.Center = parentNode.DerivedPosition; } return worldBoundingSphere; } /// <summary> /// Removes the specified flags from the current flags for this object. /// </summary> /// <param name="flags"></param> public void RemoveQueryFlags(ulong flags) { queryFlags ^= flags; } #endregion Methods #region ShadowCaster Members /// <summary> /// Overridden. /// </summary> public override bool CastShadows { get { return castShadows; } set { castShadows = value; } } public override AxisAlignedBox GetLightCapBounds() { // same as original bounds return GetWorldBoundingBox(); } /// <summary> /// /// </summary> /// <param name="light"></param> /// <param name="extrusionDistance"></param> /// <returns></returns> public override AxisAlignedBox GetDarkCapBounds(Light light, float extrusionDistance) { // Extrude own light cap bounds // need a clone to avoid modifying the original bounding box worldDarkCapBounds = (AxisAlignedBox)GetLightCapBounds().Clone(); ExtrudeBounds(worldDarkCapBounds, light.GetAs4DVector(), extrusionDistance); return worldDarkCapBounds; } /// <summary> /// Overridden. Returns null by default. /// </summary> public override EdgeData GetEdgeList(int lodIndex) { return null; } public override IEnumerator GetShadowVolumeRenderableEnumerator(ShadowTechnique technique, Light light, HardwareIndexBuffer indexBuffer, bool extrudeVertices, float extrusionDistance, int flags) { return dummyList.GetEnumerator(); } public override IEnumerator GetLastShadowVolumeRenderableEnumerator() { return dummyList.GetEnumerator(); } /// <summary> /// Get the distance to extrude for a point/spot light /// </summary> /// <param name="light"></param> /// <returns></returns> public override float GetPointExtrusionDistance(Light light) { if (parentNode != null) { return GetExtrusionDistance(parentNode.DerivedPosition, light); } else { return 0; } } #endregion ShadowCaster Members #region IAnimable methods /// <summary> /// Part of the IAnimableObject interface. /// The implementation of this property just returns null; descendents /// are free to override this. /// </summary> public virtual string[] AnimableValueNames { get { return null; } } /// <summary> /// Part of the IAnimableObject interface. /// Create an AnimableValue for the attribute with the given name, or /// throws an exception if this object doesn't support creating them. /// </summary> public virtual AnimableValue CreateAnimableValue(string valueName) { throw new Exception("This object has no AnimableValue attributes"); } #endregion IAnimable methods #region Internal engine methods /// <summary> /// Internal method called to notify the object that it has been attached to a node. /// </summary> /// <param name="node">Scene node to notify.</param> internal virtual void NotifyAttached(Node node) { NotifyAttached(node, false); } /// <summary> /// Internal method called to notify the object that it has been attached to a node. /// </summary> /// <param name="node">Scene node to notify.</param> internal virtual void NotifyAttached(Node node, bool isTagPoint) { parentNode = node; parentIsTagPoint = isTagPoint; } /// <summary> /// Internal method to notify the object of the camera to be used for the next rendering operation. /// </summary> /// <remarks> /// Certain objects may want to do specific processing based on the camera position. This method notifies /// them incase they wish to do this. /// </remarks> /// <param name="camera">Reference to the Camera being used for the current rendering operation.</param> public abstract void NotifyCurrentCamera(Camera camera); /// <summary> /// An abstract method that causes the specified RenderQueue to update itself. /// </summary> /// <remarks>This is an internal method used by the engine assembly only.</remarks> /// <param name="queue">The render queue that this object should be updated in.</param> public abstract void UpdateRenderQueue(RenderQueue queue); #endregion Internal engine methods } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Store { /// <summary>Abstract base class for input from a file in a {@link Directory}. A /// random-access input stream. Used for all Lucene index input operations. /// </summary> /// <seealso cref="Directory"> /// </seealso> public abstract class IndexInput : System.ICloneable { private bool preUTF8Strings; // true if we are reading old (modified UTF8) string format /// <summary>Reads and returns a single byte.</summary> /// <seealso cref="IndexOutput.WriteByte(byte)"> /// </seealso> public abstract byte ReadByte(); /// <summary>Reads a specified number of bytes into an array at the specified offset.</summary> /// <param name="b">the array to read bytes into /// </param> /// <param name="offset">the offset in the array to start storing bytes /// </param> /// <param name="len">the number of bytes to read /// </param> /// <seealso cref="IndexOutput.WriteBytes(byte[],int)"> /// </seealso> public abstract void ReadBytes(byte[] b, int offset, int len); /// <summary>Reads a specified number of bytes into an array at the /// specified offset with control over whether the read /// should be buffered (callers who have their own buffer /// should pass in "false" for useBuffer). Currently only /// {@link BufferedIndexInput} respects this parameter. /// </summary> /// <param name="b">the array to read bytes into /// </param> /// <param name="offset">the offset in the array to start storing bytes /// </param> /// <param name="len">the number of bytes to read /// </param> /// <param name="useBuffer">set to false if the caller will handle /// buffering. /// </param> /// <seealso cref="IndexOutput.WriteBytes(byte[],int)"> /// </seealso> public virtual void ReadBytes(byte[] b, int offset, int len, bool useBuffer) { // Default to ignoring useBuffer entirely ReadBytes(b, offset, len); } /// <summary>Reads four bytes and returns an int.</summary> /// <seealso cref="IndexOutput.WriteInt(int)"> /// </seealso> public virtual int ReadInt() { return ((ReadByte() & 0xFF) << 24) | ((ReadByte() & 0xFF) << 16) | ((ReadByte() & 0xFF) << 8) | (ReadByte() & 0xFF); } /// <summary>Reads an int stored in variable-length format. Reads between one and /// five bytes. Smaller values take fewer bytes. Negative numbers are not /// supported. /// </summary> /// <seealso cref="IndexOutput.WriteVInt(int)"> /// </seealso> public virtual int ReadVInt() { byte b = ReadByte(); int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = ReadByte(); i |= (b & 0x7F) << shift; } return i; } /// <summary>Reads eight bytes and returns a long.</summary> /// <seealso cref="IndexOutput.WriteLong(long)"> /// </seealso> public virtual long ReadLong() { return (((long) ReadInt()) << 32) | (ReadInt() & 0xFFFFFFFFL); } /// <summary>Reads a long stored in variable-length format. Reads between one and /// nine bytes. Smaller values take fewer bytes. Negative numbers are not /// supported. /// </summary> public virtual long ReadVLong() { byte b = ReadByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = ReadByte(); i |= (b & 0x7FL) << shift; } return i; } /// <summary>Call this if readString should read characters stored /// in the old modified UTF8 format (length in java chars /// and java's modified UTF8 encoding). This is used for /// indices written pre-2.4 See LUCENE-510 for details. /// </summary> public virtual void SetModifiedUTF8StringsMode() { preUTF8Strings = true; } /// <summary>Reads a string.</summary> /// <seealso cref="IndexOutput.WriteString(String)"> /// </seealso> public virtual System.String ReadString() { if (preUTF8Strings) return ReadModifiedUTF8String(); int length = ReadVInt(); byte[] bytes = new byte[length]; ReadBytes(bytes, 0, length); return System.Text.Encoding.UTF8.GetString(bytes, 0, length); } private System.String ReadModifiedUTF8String() { int length = ReadVInt(); char[] chars = new char[length]; ReadChars(chars, 0, length); return new System.String(chars, 0, length); } /// <summary>Reads Lucene's old "modified UTF-8" encoded /// characters into an array. /// </summary> /// <param name="buffer">the array to read characters into /// </param> /// <param name="start">the offset in the array to start storing characters /// </param> /// <param name="length">the number of characters to read /// </param> /// <seealso cref="IndexOutput.WriteChars(String,int,int)"> /// </seealso> /// <deprecated> -- please use readString or readBytes /// instead, and construct the string /// from those utf8 bytes /// </deprecated> [Obsolete("-- please use ReadString or ReadBytes instead, and construct the string from those utf8 bytes")] public virtual void ReadChars(char[] buffer, int start, int length) { int end = start + length; for (int i = start; i < end; i++) { byte b = ReadByte(); if ((b & 0x80) == 0) buffer[i] = (char) (b & 0x7F); else if ((b & 0xE0) != 0xE0) { buffer[i] = (char) (((b & 0x1F) << 6) | (ReadByte() & 0x3F)); } else buffer[i] = (char) (((b & 0x0F) << 12) | ((ReadByte() & 0x3F) << 6) | (ReadByte() & 0x3F)); } } /// <summary> Expert /// /// Similar to {@link #ReadChars(char[], int, int)} but does not do any conversion operations on the bytes it is reading in. It still /// has to invoke {@link #ReadByte()} just as {@link #ReadChars(char[], int, int)} does, but it does not need a buffer to store anything /// and it does not have to do any of the bitwise operations, since we don't actually care what is in the byte except to determine /// how many more bytes to read /// </summary> /// <param name="length">The number of chars to read /// </param> /// <deprecated> this method operates on old "modified utf8" encoded /// strings /// </deprecated> [Obsolete("this method operates on old \"modified utf8\" encoded strings")] public virtual void SkipChars(int length) { for (int i = 0; i < length; i++) { byte b = ReadByte(); if ((b & 0x80) == 0) { //do nothing, we only need one byte } else if ((b & 0xE0) != 0xE0) { ReadByte(); //read an additional byte } else { //read two additional bytes. ReadByte(); ReadByte(); } } } /// <summary>Closes the stream to futher operations. </summary> public abstract void Close(); /// <summary>Returns the current position in this file, where the next read will /// occur. /// </summary> /// <seealso cref="Seek(long)"> /// </seealso> public abstract long GetFilePointer(); /// <summary>Sets current position in this file, where the next read will occur.</summary> /// <seealso cref="GetFilePointer()"> /// </seealso> public abstract void Seek(long pos); /// <summary>The number of bytes in the file. </summary> public abstract long Length(); /// <summary>Returns a clone of this stream. /// /// <p/>Clones of a stream access the same data, and are positioned at the same /// point as the stream they were cloned from. /// /// <p/>Expert: Subclasses must ensure that clones may be positioned at /// different points in the input from each other and from the stream they /// were cloned from. /// </summary> public virtual System.Object Clone() { IndexInput clone = null; try { clone = (IndexInput) base.MemberwiseClone(); } catch (System.Exception e) { } return clone; } // returns Map<String, String> public virtual System.Collections.Generic.IDictionary<string,string> ReadStringStringMap() { System.Collections.Generic.Dictionary<string, string> map = new System.Collections.Generic.Dictionary<string, string>(); int count = ReadInt(); for (int i = 0; i < count; i++) { System.String key = ReadString(); System.String val = ReadString(); map[key] = val; } return map; } } }
// 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. //--------------------------------------------------------------------------- // // Description: // Helper class to the MarkupCompiler class that extends the xaml parser by // overriding callbacks appropriately for compile mode. // //--------------------------------------------------------------------------- using System; using MS.Internal.Markup; using System.Xml; using System.IO; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.ComponentModel; using MS.Utility; // for SR namespace MS.Internal { #region ParserCallbacks internal class ParserExtension : XamlParser { #region Constructor internal ParserExtension(MarkupCompiler compiler, ParserContext parserContext, BamlRecordWriter bamlWriter, Stream xamlStream, bool pass2) : base(parserContext, bamlWriter, xamlStream, false) { _compiler = compiler; _pass2 = pass2; Debug.Assert(bamlWriter != null, "Need a BamlRecordWriter for compiling to Baml"); } #endregion Constructor #region Overrides public override void WriteElementStart(XamlElementStartNode xamlObjectNode) { string classFullName = null; classFullName = _compiler.StartElement(ref _class, _subClass, ref _classModifier, xamlObjectNode.ElementType, string.Empty); // If we have a serializer for this element's type, then use that // serializer rather than doing default serialization. // NOTE: We currently have faith that the serializer will return when // it is done with the subtree and leave everything in the correct // state. We may want to limit how much the called serializer can // read so that it is forced to return at the end of the subtree. if (xamlObjectNode.SerializerType != null) { XamlSerializer serializer; if (xamlObjectNode.SerializerType == typeof(XamlStyleSerializer)) { serializer = new XamlStyleSerializer(ParserHooks); } else if (xamlObjectNode.SerializerType == typeof(XamlTemplateSerializer)) { serializer = new XamlTemplateSerializer(ParserHooks); } else { serializer = Activator.CreateInstance( xamlObjectNode.SerializerType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null) as XamlSerializer; } if (serializer == null) { ThrowException(SRID.ParserNoSerializer, xamlObjectNode.TypeFullName, xamlObjectNode.LineNumber, xamlObjectNode.LinePosition); } else { serializer.ConvertXamlToBaml(TokenReader, ParserContext, xamlObjectNode, BamlRecordWriter); _compiler.EndElement(_pass2); } } else if (BamlRecordWriter != null) { if (classFullName != null) { bool isRootPublic = _pass2 ? !_isInternalRoot : _compiler.IsRootPublic; Type rootType = isRootPublic ? xamlObjectNode.ElementType : typeof(ParserExtension); XamlElementStartNode xamlRootObjectNode = new XamlElementStartNode( xamlObjectNode.LineNumber, xamlObjectNode.LinePosition, xamlObjectNode.Depth, _compiler.AssemblyName, classFullName, rootType, xamlObjectNode.SerializerType); base.WriteElementStart(xamlRootObjectNode); } else { base.WriteElementStart(xamlObjectNode); } } } private void WriteConnectionId() { if (!_isSameScope) { base.WriteConnectionId(++_connectionId); _isSameScope = true; } } public override void WriteProperty(XamlPropertyNode xamlPropertyNode) { MemberInfo memberInfo = xamlPropertyNode.PropInfo; if (xamlPropertyNode.AttributeUsage == BamlAttributeUsage.RuntimeName && memberInfo != null) { // NOTE: Error if local element has runtime Name specified. Change this to // a warning in the future when that feature is available. if (_compiler.LocalAssembly == memberInfo.ReflectedType.Assembly && !xamlPropertyNode.IsDefinitionName) { ThrowException(SRID.LocalNamePropertyNotAllowed, memberInfo.ReflectedType.Name, MarkupCompiler.DefinitionNSPrefix, xamlPropertyNode.LineNumber, xamlPropertyNode.LinePosition); } string attributeValue = xamlPropertyNode.Value; if (!_pass2) { Debug.Assert(_name == null && _nameField == null, "Name has already been set"); _nameField = _compiler.AddNameField(attributeValue, xamlPropertyNode.LineNumber, xamlPropertyNode.LinePosition); _name = attributeValue; } if (_nameField != null || _compiler.IsRootNameScope) { WriteConnectionId(); } } if (memberInfo != null && memberInfo.Name.Equals(STARTUPURI) && KnownTypes.Types[(int)KnownElements.Application].IsAssignableFrom(memberInfo.DeclaringType)) { // if Application.StartupUri property then don't bamlize, but gen code since // this is better for perf as Application is not a DO. if (!_pass2) { _compiler.AddApplicationProperty(memberInfo, xamlPropertyNode.Value, xamlPropertyNode.LineNumber); } } else { _compiler.IsBamlNeeded = true; base.WriteProperty(xamlPropertyNode); } } public override void WriteUnknownTagStart(XamlUnknownTagStartNode xamlUnknownTagStartNode) { string localElementFullName = string.Empty; NamespaceMapEntry[] namespaceMaps = XamlTypeMapper.GetNamespaceMapEntries(xamlUnknownTagStartNode.XmlNamespace); if (namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly) { string ns = namespaceMaps[0].ClrNamespace; if (!string.IsNullOrEmpty(ns)) { ns += MarkupCompiler.DOT; } localElementFullName = ns + xamlUnknownTagStartNode.Value; } if (localElementFullName.Length > 0 && !_pass2) { // if local complex property bail out now and handle in 2nd pass when TypInfo is available int lastIndex = xamlUnknownTagStartNode.Value.LastIndexOf(MarkupCompiler.DOTCHAR); if (-1 == lastIndex) { _compiler.StartElement(ref _class, _subClass, ref _classModifier, null, localElementFullName); } } else { base.WriteUnknownTagStart(xamlUnknownTagStartNode); } } public override void WriteUnknownTagEnd(XamlUnknownTagEndNode xamlUnknownTagEndNode) { NamespaceMapEntry[] namespaceMaps = XamlTypeMapper.GetNamespaceMapEntries(xamlUnknownTagEndNode.XmlNamespace); bool localTag = namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly; if (localTag && !_pass2) { // if local complex property bail out now and handle in 2nd pass when TypInfo is available int lastIndex = xamlUnknownTagEndNode.LocalName.LastIndexOf(MarkupCompiler.DOTCHAR); if (-1 == lastIndex) { _compiler.EndElement(_pass2); } } else { base.WriteUnknownTagEnd(xamlUnknownTagEndNode); } } public override void WriteUnknownAttribute(XamlUnknownAttributeNode xamlUnknownAttributeNode) { bool localAttrib = false; string localTagFullName = string.Empty; string localAttribName = xamlUnknownAttributeNode.Name; NamespaceMapEntry[] namespaceMaps = null; MemberInfo miKnownEvent = null; if (xamlUnknownAttributeNode.OwnerTypeFullName.Length > 0) { // These are attributes on a local tag ... localTagFullName = xamlUnknownAttributeNode.OwnerTypeFullName; localAttrib = true; } else { // These are attributes on a non-local tag ... namespaceMaps = XamlTypeMapper.GetNamespaceMapEntries(xamlUnknownAttributeNode.XmlNamespace); localAttrib = namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly; } if (localAttrib && !_pass2) { // ... and if there are any periods in the attribute name, then ... int lastIndex = localAttribName.LastIndexOf(MarkupCompiler.DOTCHAR); if (-1 != lastIndex) { // ... these might be attached props or events defined by a locally defined component, // but being set on this non-local tag. TypeAndSerializer typeAndSerializer = null; string ownerTagName = localAttribName.Substring(0, lastIndex); if (namespaceMaps != null) { if (namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly) { // local prop on a known tag localTagFullName = namespaceMaps[0].ClrNamespace + MarkupCompiler.DOT + ownerTagName; } } else { typeAndSerializer = XamlTypeMapper.GetTypeOnly(xamlUnknownAttributeNode.XmlNamespace, ownerTagName); if (typeAndSerializer != null) { // known local attribute on a local tag Type ownerTagType = typeAndSerializer.ObjectType; localTagFullName = ownerTagType.FullName; localAttribName = localAttribName.Substring(lastIndex + 1); // See if attached event first miKnownEvent = ownerTagType.GetMethod(MarkupCompiler.ADD + localAttribName + MarkupCompiler.HANDLER, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (miKnownEvent == null) { // Not an attached event, so try for a clr event. miKnownEvent = ownerTagType.GetEvent(localAttribName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); } if (miKnownEvent != null) { if (_events == null) _events = new ArrayList(); _events.Add(new MarkupCompiler.MarkupEventInfo(xamlUnknownAttributeNode.Value, localAttribName, miKnownEvent, xamlUnknownAttributeNode.LineNumber)); WriteConnectionId(); } } else { namespaceMaps = XamlTypeMapper.GetNamespaceMapEntries(xamlUnknownAttributeNode.XmlNamespace); if (namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly) { // local prop on local tag localTagFullName = namespaceMaps[0].ClrNamespace + MarkupCompiler.DOT + ownerTagName; } else { // unknown prop on local tag -- Error! localTagFullName = string.Empty; } } } if (typeAndSerializer == null) { localAttribName = localAttribName.Substring(lastIndex + 1); } } // else if it is an unknown non-attached prop on a non-local tag -- instant error! } if (localTagFullName.Length > 0 && !_pass2) { if (xamlUnknownAttributeNode.AttributeUsage == BamlAttributeUsage.RuntimeName) { string attributeValue = xamlUnknownAttributeNode.Value; Debug.Assert(_name == null && _nameField == null, "Name has already been set"); _nameField = _compiler.AddNameField(attributeValue, xamlUnknownAttributeNode.LineNumber, xamlUnknownAttributeNode.LinePosition); _name = attributeValue; if (_nameField != null) { WriteConnectionId(); } } else if (localAttribName.Equals(STARTUPURI) && _compiler.IsCompilingEntryPointClass) { // if Application.StartuoUri property then don't bamlize, but gen code since // this is better for perf as Application is not a DO. PropertyInfo pi = KnownTypes.Types[(int)KnownElements.Application].GetProperty(localAttribName); _compiler.AddApplicationProperty(pi, xamlUnknownAttributeNode.Value, xamlUnknownAttributeNode.LineNumber); return; } else if (miKnownEvent == null) { // This may or may not be a local event, but there is no way to know in Pass1. // So we prepare for the worst case sceanrio and assume it may be one so that // the Xaml compiler can generate the CreateDelegate code. _compiler.HasLocalEvent = true; } } else { base.WriteUnknownAttribute(xamlUnknownAttributeNode); } _compiler.IsBamlNeeded = true; } public override void WriteElementEnd(XamlElementEndNode xamlEndObjectNode) { _compiler.EndElement(_pass2); base.WriteElementEnd(xamlEndObjectNode); } /// <summary> /// override of GetElementType /// </summary> public override bool GetElementType( XmlReader xmlReader, string localName, string namespaceUri, ref string assemblyName, ref string typeFullName, ref Type baseType, ref Type serializerType) { if (!ProcessedRootElement && namespaceUri.Equals(XamlReaderHelper.DefinitionNamespaceURI) && (localName.Equals(XamlReaderHelper.DefinitionCodeTag) || localName.Equals(XamlReaderHelper.DefinitionXDataTag))) { MarkupCompiler.ThrowCompilerException(SRID.DefinitionTagNotAllowedAtRoot, xmlReader.Prefix, localName); } bool foundElement = base.GetElementType(xmlReader, localName, namespaceUri, ref assemblyName, ref typeFullName, ref baseType, ref serializerType); if (!ProcessedRootElement) { int count = xmlReader.AttributeCount; // save reader's position, to be restored later string attrName = (xmlReader.NodeType == XmlNodeType.Attribute) ? xmlReader.Name : null; _isRootTag = true; _class = string.Empty; _subClass = string.Empty; ProcessedRootElement = true; XamlTypeMapper.IsProtectedAttributeAllowed = false; xmlReader.MoveToFirstAttribute(); while (--count >= 0) { string attribNamespaceURI = xmlReader.LookupNamespace(xmlReader.Prefix); if (attribNamespaceURI != null && attribNamespaceURI.Equals(XamlReaderHelper.DefinitionNamespaceURI)) { MarkupCompiler.DefinitionNSPrefix = xmlReader.Prefix; if (xmlReader.LocalName == CLASS) { _class = xmlReader.Value.Trim(); if (_class == string.Empty) { // flag an error for processing later in WriteDefAttribute _class = MarkupCompiler.DOT; } else { // flag this so that the Type Mapper can allow protected // attributes on the markup sub-classed root element only. XamlTypeMapper.IsProtectedAttributeAllowed = true; } } else if (xmlReader.LocalName == XamlReaderHelper.DefinitionTypeArgs) { string genericName = _compiler.GetGenericTypeName(localName, xmlReader.Value); foundElement = base.GetElementType(xmlReader, genericName, namespaceUri, ref assemblyName, ref typeFullName, ref baseType, ref serializerType); if (!foundElement) { NamespaceMapEntry[] namespaceMaps = XamlTypeMapper.GetNamespaceMapEntries(namespaceUri); bool isLocal = namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly; if (!isLocal) { MarkupCompiler.ThrowCompilerException(SRID.UnknownGenericType, MarkupCompiler.DefinitionNSPrefix, xmlReader.Value, localName); } } } else if (xmlReader.LocalName == SUBCLASS) { _subClass = xmlReader.Value.Trim(); if (_subClass == string.Empty) { // flag an error for processing later in WriteDefAttribute _subClass = MarkupCompiler.DOT; } else { _compiler.ValidateFullSubClassName(ref _subClass); } } else if (xmlReader.LocalName == CLASSMODIFIER) { if (!_pass2) { _classModifier = xmlReader.Value.Trim(); if (_classModifier == string.Empty) { // flag an error for processing later in WriteDefAttribute _classModifier = MarkupCompiler.DOT; } } else { // This direct comparison is ok to do in pass2 as it has already been validated in pass1. // This is to avoid a costly instantiation of the CodeDomProvider in pass2. _isInternalRoot = string.Compare("public", xmlReader.Value.Trim(), StringComparison.OrdinalIgnoreCase) != 0; } } } xmlReader.MoveToNextAttribute(); } if (namespaceUri.Equals(XamlReaderHelper.DefinitionNamespaceURI)) { xmlReader.MoveToElement(); } else { if (attrName == null) xmlReader.MoveToFirstAttribute(); else xmlReader.MoveToAttribute(attrName); } } else if (!_compiler.IsBamlNeeded && !_compiler.ProcessingRootContext && _compiler.IsCompilingEntryPointClass && xmlReader.Depth > 0) { if ((!localName.Equals(MarkupCompiler.CODETAG) && !localName.Equals(MarkupCompiler.CODETAG + "Extension")) || !namespaceUri.Equals(XamlReaderHelper.DefinitionNamespaceURI)) { _compiler.IsBamlNeeded = true; } } return foundElement; } /// <summary> /// override of WriteDynamicEvent /// </summary> public override void WriteClrEvent(XamlClrEventNode xamlClrEventNode) { bool isStyleEvent = (xamlClrEventNode.IsStyleSetterEvent || xamlClrEventNode.IsTemplateEvent); bool localEvent = _compiler.LocalAssembly == xamlClrEventNode.EventMember.ReflectedType.Assembly; if (isStyleEvent) { if (localEvent) { // validate the event handler name per CLS grammar for identifiers _compiler.ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value); xamlClrEventNode.LocalAssemblyName = _compiler.AssemblyName; // Pass2 should always be true here as otherwise localEvent will be false, but just being paranoid here. if (_pass2) { XamlTypeMapper.HasInternals = true; } } else { if (!xamlClrEventNode.IsSameScope) { _connectionId++; } xamlClrEventNode.ConnectionId = _connectionId; if (!_pass2) { _compiler.ConnectStyleEvent(xamlClrEventNode); } } return; } bool appEvent = KnownTypes.Types[(int)KnownElements.Application].IsAssignableFrom(xamlClrEventNode.EventMember.DeclaringType); if (!appEvent) { if (!_pass2) { // validate the event handler name per CLS grammar for identifiers _compiler.ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value); if (_events == null) _events = new ArrayList(); _events.Add(new MarkupCompiler.MarkupEventInfo(xamlClrEventNode.Value, xamlClrEventNode.EventName, xamlClrEventNode.EventMember, xamlClrEventNode.LineNumber)); } // if not local event ... if (!localEvent) { WriteConnectionId(); } } else if (!_pass2) { // Since Application is not an Element it doesn't implement IComponentConnector and // so needs to add events directly. MarkupCompiler.MarkupEventInfo mei = new MarkupCompiler.MarkupEventInfo(xamlClrEventNode.Value, xamlClrEventNode.EventName, xamlClrEventNode.EventMember, xamlClrEventNode.LineNumber); _compiler.AddApplicationEvent(mei); } if (_pass2) { // if local event, add Baml Attribute Record for local event if (localEvent) { // validate the event handler name per C# grammar for identifiers _compiler.ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value); XamlPropertyNode xamlPropertyNode = new XamlPropertyNode(xamlClrEventNode.LineNumber, xamlClrEventNode.LinePosition, xamlClrEventNode.Depth, xamlClrEventNode.EventMember, _compiler.AssemblyName, xamlClrEventNode.EventMember.ReflectedType.FullName, xamlClrEventNode.EventName, xamlClrEventNode.Value, BamlAttributeUsage.Default, false); XamlTypeMapper.HasInternals = true; base.WriteProperty(xamlPropertyNode); } } } /// <summary> /// override of WriteEndAttributes /// </summary> public override void WriteEndAttributes(XamlEndAttributesNode xamlEndAttributesNode) { if (xamlEndAttributesNode.IsCompact) return; if (_isRootTag) { _class = string.Empty; _classModifier = string.Empty; _subClass = string.Empty; XamlTypeMapper.IsProtectedAttributeAllowed = false; } _isRootTag = false; _isSameScope = false; if (!_pass2) { if (_nameField == null) { if (_isFieldModifierSet) { ThrowException(SRID.FieldModifierNotAllowed, MarkupCompiler.DefinitionNSPrefix, xamlEndAttributesNode.LineNumber, xamlEndAttributesNode.LinePosition); } } else if (_fieldModifier != MemberAttributes.Assembly) { if (MemberAttributes.Private != _fieldModifier && MemberAttributes.Assembly != _fieldModifier) { MarkupCompiler.GenerateXmlComments(_nameField, _nameField.Name + " Name Field"); } _nameField.Attributes = _fieldModifier; _fieldModifier = MemberAttributes.Assembly; } _nameField = null; _isFieldModifierSet = false; _compiler.ConnectNameAndEvents(_name, _events, _connectionId); _name = null; if (_events != null) { _events.Clear(); _events = null; } } else { _compiler.CheckForNestedNameScope(); } // Clear the compiler's generic type argument list // (Strange xaml compilation error MC6025 in unrelated class) // The bug arises because the markup compiler's _typeArgsList is set for any tag // that has an x:TypeArguments attribute. It should be cleared upon reaching the // end of the tag's attributes, but this only happens in the non-pass2 case. If the // tag needs pass2 processing, the list is set but not cleared, leading to a mysterious // exception in the next tag (<ResourceDictionary>, in the repro). _compiler.ClearGenericTypeArgs(); base.WriteEndAttributes(xamlEndAttributesNode); } /// <summary> /// override of WriteDefTag /// </summary> public override void WriteDefTag(XamlDefTagNode xamlDefTagNode) { if (!_pass2) { _compiler.ProcessDefinitionNamespace(xamlDefTagNode); } else { // loop through until after the end of the current definition tag is reached. while (!xamlDefTagNode.IsEmptyElement && xamlDefTagNode.XmlReader.NodeType != XmlNodeType.EndElement) { xamlDefTagNode.XmlReader.Read(); } xamlDefTagNode.XmlReader.Read(); } } /// <summary> /// override for handling a new xmlnamespace Uri /// </summary> public override void WriteNamespacePrefix(XamlXmlnsPropertyNode xamlXmlnsPropertyNode) { if (!_pass2) { List<ClrNamespaceAssemblyPair> cnap = XamlTypeMapper.GetClrNamespacePairFromCache(xamlXmlnsPropertyNode.XmlNamespace); if (cnap != null) { foreach (ClrNamespaceAssemblyPair u in cnap) { _compiler.AddUsing(u.ClrNamespace); } } } base.WriteNamespacePrefix(xamlXmlnsPropertyNode); } /// <summary> /// override for mapping instructions between clr and xml namespaces /// </summary> public override void WritePIMapping(XamlPIMappingNode xamlPIMappingNode) { if (!_pass2) { _compiler.AddUsing(xamlPIMappingNode.ClrNamespace); } // Local assembly! if ((xamlPIMappingNode.AssemblyName == null) || (xamlPIMappingNode.AssemblyName.Length == 0)) { xamlPIMappingNode.AssemblyName = _compiler.AssemblyName; bool addMapping = !XamlTypeMapper.PITable.Contains(xamlPIMappingNode.XmlNamespace) || ((ClrNamespaceAssemblyPair)XamlTypeMapper.PITable[xamlPIMappingNode.XmlNamespace]).LocalAssembly || string.IsNullOrEmpty(((ClrNamespaceAssemblyPair)XamlTypeMapper.PITable[xamlPIMappingNode.XmlNamespace]).AssemblyName); if (addMapping) { ClrNamespaceAssemblyPair namespaceMapping = new ClrNamespaceAssemblyPair(xamlPIMappingNode.ClrNamespace, xamlPIMappingNode.AssemblyName); namespaceMapping.LocalAssembly = true; XamlTypeMapper.PITable[xamlPIMappingNode.XmlNamespace] = namespaceMapping; XamlTypeMapper.InvalidateMappingCache(xamlPIMappingNode.XmlNamespace); if (!_pass2 && BamlRecordWriter != null) { BamlRecordWriter = null; } } } base.WritePIMapping(xamlPIMappingNode); } /// <summary> /// override of WriteDefAttribute /// </summary> public override void WriteDefAttribute(XamlDefAttributeNode xamlDefAttributeNode) { if (xamlDefAttributeNode.AttributeUsage == BamlAttributeUsage.RuntimeName) { string attributeValue = xamlDefAttributeNode.Value; if (!_pass2) { Debug.Assert(_name == null && _nameField == null, "Name definition has already been set"); _nameField = _compiler.AddNameField(attributeValue, xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition); _name = attributeValue; } if (_nameField != null || _compiler.IsRootNameScope) { WriteConnectionId(); // x:Name needs to be written out as a BAML record in order // to trigger the RegisterName code path in BamlRecordReader. // This code follows the code in WriteProperty for the RuntimeName property base.WriteDefAttribute(xamlDefAttributeNode); } } else if (xamlDefAttributeNode.Name == FIELDMODIFIER) { if (!_pass2) { _fieldModifier = _compiler.GetMemberAttributes(xamlDefAttributeNode.Value); _isFieldModifierSet = true; } } // Some x: attributes are processed by the compiler, but are unknown // to the base XamlParser. The compiler specific ones should not be passed // to XamlParser for processing, but the rest should be. else { bool isClass = xamlDefAttributeNode.Name == CLASS; bool isClassModifier = xamlDefAttributeNode.Name == CLASSMODIFIER; bool isTypeArgs = xamlDefAttributeNode.Name == XamlReaderHelper.DefinitionTypeArgs; bool isSubClass = xamlDefAttributeNode.Name == SUBCLASS; if (!isClass && !isClassModifier && !isTypeArgs && !isSubClass) { base.WriteDefAttribute(xamlDefAttributeNode); } else if (!_isRootTag) { ThrowException(SRID.DefinitionAttributeNotAllowed, MarkupCompiler.DefinitionNSPrefix, xamlDefAttributeNode.Name, xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition); } else if (isClass) { if (_class == MarkupCompiler.DOT) { int index = xamlDefAttributeNode.Value.LastIndexOf(MarkupCompiler.DOT, StringComparison.Ordinal); ThrowException(SRID.InvalidClassName, MarkupCompiler.DefinitionNSPrefix, CLASS, xamlDefAttributeNode.Value, index >= 0 ? "fully qualified " : string.Empty, xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition); } _class = string.Empty; } else if (isClassModifier) { if (_classModifier == MarkupCompiler.DOT) { ThrowException(SRID.UnknownClassModifier, MarkupCompiler.DefinitionNSPrefix, xamlDefAttributeNode.Value, _compiler.Language, xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition); } _classModifier = string.Empty; } else if (isSubClass) { if (_subClass == MarkupCompiler.DOT) { int index = xamlDefAttributeNode.Value.LastIndexOf(MarkupCompiler.DOT, StringComparison.Ordinal); ThrowException(SRID.InvalidClassName, MarkupCompiler.DefinitionNSPrefix, SUBCLASS, xamlDefAttributeNode.Value, index >= 0 ? "fully qualified " : string.Empty, xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition); } _subClass = string.Empty; } else if (isTypeArgs) { _compiler.AddGenericArguments(ParserContext, xamlDefAttributeNode.Value); } } } /* // NOTE: Enable when Parser is ready to handle multiple errors w/o bailing out. internal override SerializationErrorAction ParseError(XamlParseException e) { _compiler.OnError(e); return SerializationErrorAction.Ignore; } */ /// <summary> /// override of Write End Document /// </summary> public override void WriteDocumentEnd(XamlDocumentEndNode xamlEndDocumentNode) { if (BamlRecordWriter != null) { MemoryStream bamlMemStream = BamlRecordWriter.BamlStream as MemoryStream; Debug.Assert(bamlMemStream != null); base.WriteDocumentEnd(xamlEndDocumentNode); _compiler.GenerateBamlFile(bamlMemStream); } } internal override bool CanResolveLocalAssemblies() { return _pass2; } bool ProcessedRootElement { get { return _processedRootElement; } set { _processedRootElement = value; } } #endregion Overrides #region Data private MarkupCompiler _compiler; private string _name = null; private string _class = string.Empty; private string _subClass = string.Empty; private int _connectionId = 0; private bool _pass2 = false; private bool _isRootTag = false; private bool _processedRootElement = false; private bool _isSameScope = false; private bool _isInternalRoot = false; private ArrayList _events = null; private bool _isFieldModifierSet = false; private CodeMemberField _nameField = null; private string _classModifier = string.Empty; private MemberAttributes _fieldModifier = MemberAttributes.Assembly; private const string CLASS = "Class"; private const string SUBCLASS = "Subclass"; private const string CLASSMODIFIER = "ClassModifier"; private const string FIELDMODIFIER = "FieldModifier"; private const string STARTUPURI = "StartupUri"; #endregion Data } #endregion ParserCallbacks }
// Copyright (c) Duende Software. All rights reserved. // See LICENSE in the project root for license information. using IdentityModel; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Duende.IdentityServer; using Duende.IdentityServer.Events; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Test; using Microsoft.AspNetCore.Identity; namespace IdentityServerHost.Quickstart.UI { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly ILogger<ExternalController> _logger; private readonly IEventService _events; private readonly UserManager<IdentityUser> _userManager; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, ILogger<ExternalController> logger, UserManager<IdentityUser> userManager) { _interaction = interaction; _clientStore = clientStore; _logger = logger; _events = events; _userManager = userManager; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public IActionResult Challenge(string scheme, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", scheme }, } }; return Challenge(props, scheme); } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } if (_logger.IsEnabled(LogLevel.Debug)) { var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}"); _logger.LogDebug("External claims: {@claims}", externalClaims); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = await FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = await AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additional claims or properties // for the specific protocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallback(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user var isuser = new IdentityServerUser(user.Id) { DisplayName = user.UserName, IdentityProvider = provider, AdditionalClaims = additionalLocalClaims }; await HttpContext.SignInAsync(isuser, localSignInProps); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, user.UserName, true, context?.Client.ClientId)); if (context != null) { if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return this.LoadingPage("Redirect", returnUrl); } } return Redirect(returnUrl); } private async Task<(IdentityUser user, string provider, string providerUserId, IEnumerable<Claim> claims)> FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = await _userManager.FindByLoginAsync(provider, providerUserId); return (user, provider, providerUserId, claims); } private async Task<IdentityUser> AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { // create dummy internal account (you can do something more complex) var user = new IdentityUser(Guid.NewGuid().ToString()); await _userManager.CreateAsync(user); // add external user ID to new account await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider)); return user; } // if the external login is OIDC-based, there are certain things we need to preserve to make logout work // this will be different for WS-Fed, SAML2p or other protocols private void ProcessLoginCallback(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var idToken = externalResult.Properties.GetTokenValue("id_token"); if (idToken != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = idToken } }); } } } }
using System; using System.Collections; using Server; using Server.Items; using Server.Multis; using Server.Targeting; namespace Knives.TownHouses { public class TownHouse : VersionHouse { private static ArrayList s_TownHouses = new ArrayList(); public static ArrayList AllTownHouses{ get{ return s_TownHouses; } } private TownHouseSign c_Sign; private Item c_Hanger; private ArrayList c_Sectors = new ArrayList(); public TownHouseSign ForSaleSign { get { return c_Sign; } } public Item Hanger { get { if ( c_Hanger == null ) { c_Hanger = new Item( 0xB98 ); c_Hanger.Movable = false; c_Hanger.Location = Sign.Location; c_Hanger.Map = Sign.Map; } return c_Hanger; } set{ c_Hanger = value; } } public TownHouse( Mobile m, TownHouseSign sign, int locks, int secures ) : base( 0x1DD6 | 0x4000, m, locks, secures ) { c_Sign = sign; SetSign( 0, 0, 0 ); s_TownHouses.Add( this ); } public void InitSectorDefinition() { if (c_Sign == null || c_Sign.Blocks.Count == 0) return; int minX = ((Rectangle2D)c_Sign.Blocks[0]).Start.X; int minY = ((Rectangle2D)c_Sign.Blocks[0]).Start.Y; int maxX = ((Rectangle2D)c_Sign.Blocks[0]).End.X; int maxY = ((Rectangle2D)c_Sign.Blocks[0]).End.Y; foreach( Rectangle2D rect in c_Sign.Blocks ) { if ( rect.Start.X < minX ) minX = rect.Start.X; if ( rect.Start.Y < minY ) minY = rect.Start.Y; if ( rect.End.X > maxX ) maxX = rect.End.X; if ( rect.End.Y > maxY ) maxY = rect.End.Y; } foreach (Sector sector in c_Sectors) sector.OnMultiLeave(this); c_Sectors.Clear(); for (int x = minX; x < maxX; ++x) for (int y = minY; y < maxY; ++y) if(!c_Sectors.Contains(Map.GetSector(new Point2D(x, y)))) c_Sectors.Add(Map.GetSector(new Point2D(x, y))); foreach (Sector sector in c_Sectors) sector.OnMultiEnter(this); Components.Resize(maxX - minX, maxY - minY); Components.Add(0x520, Components.Width - 1, Components.Height - 1, -5); } public override Rectangle2D[] Area { get { if (c_Sign == null) return new Rectangle2D[100]; Rectangle2D[] rects = new Rectangle2D[c_Sign.Blocks.Count]; for (int i = 0; i < c_Sign.Blocks.Count && i < rects.Length; ++i) rects[i] = (Rectangle2D)c_Sign.Blocks[i]; return rects; } } public override bool IsInside( Point3D p, int height ) { if (c_Sign == null) return false; if ( Map == null || Region == null ) { Delete(); return false; } Sector sector = null; try { if (c_Sign is RentalContract && Region.Contains(p)) return true; sector = Map.GetSector(p); foreach (BaseMulti m in sector.Multis) { if (m != this && m is TownHouse && ((TownHouse)m).ForSaleSign is RentalContract && ((TownHouse)m).IsInside(p, height)) return false; } return Region.Contains(p); } catch(Exception e) { Errors.Report("Error occured in IsInside(). More information on the console."); Console.WriteLine("Info:{0}, {1}, {2}", Map, sector, Region, sector != null ? "" + sector.Multis : "**"); Console.WriteLine(e.Source); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return false; } } public override int GetNewVendorSystemMaxVendors() { return 50; } public override int GetAosMaxSecures() { return MaxSecures; } public override int GetAosMaxLockdowns() { return MaxLockDowns; } public override void OnMapChange() { base.OnMapChange(); if ( c_Hanger != null ) c_Hanger.Map = Map; } public override void OnLocationChange( Point3D oldLocation ) { base.OnLocationChange( oldLocation ); if ( c_Hanger != null ) c_Hanger.Location = Sign.Location; } public override void OnSpeech( SpeechEventArgs e ) { if ( e.Mobile != Owner || !IsInside( e.Mobile ) ) return; if (e.Speech.ToLower() == "check house rent") c_Sign.CheckRentTimer(); Timer.DelayCall(TimeSpan.Zero, new TimerStateCallback(AfterSpeech), e.Mobile); } private void AfterSpeech(object o) { if (!(o is Mobile)) return; if (((Mobile)o).Target is HouseBanTarget && ForSaleSign != null && ForSaleSign.NoBanning) { ((Mobile)o).Target.Cancel((Mobile)o, TargetCancelType.Canceled); ((Mobile)o).SendMessage(0x161, "You cannot ban people from this house."); } } public override void OnDelete() { if (c_Hanger != null) c_Hanger.Delete(); foreach (Item item in Sign.GetItemsInRange(0)) if (item != Sign) item.Visible = true; c_Sign.ClearHouse(); Doors.Clear(); s_TownHouses.Remove(this); base.OnDelete(); } public TownHouse(Serial serial) : base(serial) { s_TownHouses.Add(this); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( 3 ); // Version 2 writer.Write( c_Hanger ); // Version 1 writer.Write( c_Sign ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( version >= 2 ) c_Hanger = reader.ReadItem(); c_Sign = (TownHouseSign)reader.ReadItem(); if (version <= 2) { int count = reader.ReadInt(); for (int i = 0; i < count; ++i) reader.ReadRect2D(); } if( Price == 0 ) Price = 1; ItemID = 0x1DD6 | 0x4000; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Factotum { public partial class ReportValidator : Form, IEntityEditForm { private EInspectedComponent curReport; // Allow the calling form to access the entity public IEntity Entity { get { return curReport; } } public ReportValidator(Guid inspectedComponentID) { InitializeComponent(); curReport = new EInspectedComponent((Guid?)inspectedComponentID); InitializeControls(); DoValidation(); } // Initialize the form control values private void InitializeControls() { SetControlValues(); dgvInfo.AllowUserToResizeColumns = true; } // Set the form controls to the unit object values. private void SetControlValues() { updateHeaderLabel(); } private void updateHeaderLabel() { lblReportName.Text = "Validating Report: " + curReport.InspComponentName; DowUtils.Util.CenterControlHorizInForm(lblReportName, this); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void btnValidate_Click(object sender, EventArgs e) { DoValidation(); } private void AddLine(string inspection, string dataset, string message) { dgvInfo.Rows.Add(new object[] { inspection, dataset, message }); } public void DoValidation() { // We need to do this, because we may be trying to refresh and the current // report data may have changed. Guid reportID = (Guid)curReport.ID; curReport = new EInspectedComponent(reportID); dgvInfo.Visible = true; dgvInfo.Rows.Clear(); EOutage outage = new EOutage(curReport.InspComponentOtgID); EComponent component = new EComponent(curReport.InspComponentCmpID); EInspectionCollection inspections = EInspection.ListByReportOrderForInspectedComponent((Guid)curReport.ID,false); EInspectorCollection contribInspectors = EInspector.ListForInspectedComponent((Guid)curReport.ID,true); bool gridProcedureRequired = false; bool warnEpriRecommended = UserSettings.sets.ValidateEpriRecommended; bool warnTemperatures = UserSettings.sets.ValidateTemperatures; bool warnNoUpMain = UserSettings.sets.ValidateNoUpMain; bool warnNoUpExt = UserSettings.sets.ValidateNoUpExt; bool warnNoDnExt = UserSettings.sets.ValidateNoDnExt; bool gridColCount_UseCeiling = UserSettings.sets.ValidateGridColCountWithCeiling; bool gridDsExtRowCount_UseCeiling = UserSettings.sets.ValidateDsExtRowCountWithCeiling; if (outage.OutageClpID == null) { AddLine("N/A", "N/A", "No Calibration procedure was specified for the outage"); } if (outage.OutageCptID == null) { AddLine("N/A", "N/A", "No couplant type was specified for the outage"); } if (outage.OutageCouplantBatch == null) { AddLine("N/A", "N/A", "No couplant batch was specified for the outage"); } if (outage.OutageStartedOn == null) { AddLine("N/A", "N/A", "No start date was specified for the outage"); } if (outage.OutageFacPhone == null) { AddLine("N/A", "N/A", "No FAC phone # was specified for the outage"); } if (curReport.InspComponentInsID == null) { AddLine("N/A", "N/A", "No reviewer was specified for the report"); } else { foreach (EInspector inspector in contribInspectors) { if (curReport.InspComponentInsID == inspector.ID) { AddLine("N/A", "N/A", "The reviewer for the report should not be a participant in inspections"); break; } } } if (!curReport.InspComponentIsUtFieldComplete) { AddLine("N/A", "N/A", "The report is not flagged as 'UT Field Complete'"); } if (curReport.InspComponentPageCountOverride == null) { AddLine("N/A", "N/A", "The number of pages for the report has not been set"); } if (component.ComponentLinID == null) { AddLine("N/A", "N/A", "The line has not been specified for the component"); } if (component.ComponentPslID == null) { AddLine("N/A", "N/A", "No pipe schedule was set for the component"); } if (component.ComponentUpMainOd == null) { AddLine("N/A", "N/A", "No Main (U/S Main) OD was set for the component"); } if (component.ComponentUpMainTnom == null) { AddLine("N/A", "N/A", "No Main (U/S Main) Tnom was set for the component"); } if (component.ComponentUpMainTscr == null) { AddLine("N/A", "N/A", "No Main (U/S Main) Tscr was set for the component"); } if (component.ComponentHasDs && !component.DnMainThicknessesDefined) { AddLine("N/A", "N/A", "The component has been flagged as having a downstream section, but downstream main dimensions have not been set"); } if (component.ComponentHasBranch && !component.BranchThicknessesDefined) { AddLine("N/A", "N/A", "The component has been flagged as having a branch, but branch dimensions have not been set"); } if (component.ComponentHasBranch && !component.BranchExtThicknessesDefined) { AddLine("N/A", "N/A", "The component has been flagged as having a branch, but branch extension dimensions have not been set"); } foreach (EInspection inspection in inspections) { EGrid grid = null; string inspName = inspection.InspectionName; if (inspection.InspectionPersonHours == null) { AddLine(inspName, "N/A", "Inspector hours were not recorded"); } if (inspection.InspectionHasGrid) { gridProcedureRequired = true; grid = new EGrid(inspection.GridID); EpriGrid epriGrid = new EpriGrid(); if (grid.GridAxialDistance == null) AddLine(inspName, "N/A", "No axial distance was specified for the grid"); if (grid.GridRadialDistance == null) AddLine(inspName, "N/A", "No radial distance was specified for the grid"); if (component.ComponentUpMainOd != null) { // Get the minimum od looking at all parts of the component decimal minComponentDiameter = Math.Min((decimal)component.ComponentUpMainOd, (component.ComponentDnMainOd == null ? decimal.MaxValue : (decimal)component.ComponentDnMainOd)); minComponentDiameter = Math.Min((decimal)minComponentDiameter, (component.ComponentBranchOd == null ? decimal.MaxValue : (decimal)component.ComponentBranchOd)); decimal epriMax = epriGrid.GetMaxGridForDiameter(minComponentDiameter); decimal epriRecommended = epriGrid.GetRecommendedGridForDiameter(minComponentDiameter); // Compare the axial distance to the EPRI guidelines if (grid.GridAxialDistance != null && grid.GridAxialDistance > epriMax) AddLine(inspName, "N/A", "The Grid axial distance exceeds the EPRI MAXIMUM of " + epriMax + " in. for the component min OD"); else if (warnEpriRecommended && grid.GridAxialDistance != null && grid.GridAxialDistance > epriRecommended) AddLine(inspName, "N/A", "The Grid axial distance exceeds the EPRI recommended of " + epriRecommended + " in. for the component min OD, though it is below the EPRI maximum"); // Compare the radial distance to the EPRI guidelines if (grid.GridRadialDistance != null && grid.GridRadialDistance > epriMax) AddLine(inspName, "N/A", "The Grid radial distance exceeds the EPRI MAXIMUM of " + epriMax + " in. for the component min OD"); else if (warnEpriRecommended && grid.GridRadialDistance != null && grid.GridRadialDistance > epriRecommended) AddLine(inspName, "N/A", "The Grid radial distance exceeds the EPRI recommended of " + epriRecommended + " in. for the component min OD, though it is below the EPRI maximum"); } if (component.ComponentUpMainOd != null && grid.GridRadialDistance != null) { decimal minCols = (gridColCount_UseCeiling ? Math.Ceiling((decimal)component.ComponentUpMainOd * (decimal)Math.PI / (decimal)grid.GridRadialDistance) : Math.Round((decimal)component.ComponentUpMainOd * (decimal)Math.PI / (decimal)grid.GridRadialDistance) ); if ((decimal)(grid.GridEndCol - grid.GridStartCol + 1) < minCols) AddLine(inspName, "N/A", "Too few columns for the grid. There are " + (grid.GridEndCol - grid.GridStartCol + 1) + ". Expected " + minCols + " based on the component OD and the grid radial dimension."); } if (warnNoUpExt && (grid.GridUpExtStartRow == null || grid.GridUpExtEndRow == null)) AddLine(inspName, "N/A", "No upstream extension partition rows provided for the grid"); if (warnNoUpMain && (grid.GridUpMainStartRow == null || grid.GridUpMainEndRow == null)) AddLine(inspName, "N/A", "No upstream main partition rows provided for the grid"); if (warnNoDnExt && (grid.GridDnExtStartRow == null || grid.GridDnExtEndRow == null)) AddLine(inspName, "N/A", "No downstream extension partition rows provided for the grid"); // Check that the downstream extension rows match what is specified in the grid procedure. if (grid.GridDnExtStartRow != null && grid.GridDnExtEndRow != null && component.ComponentUpMainOd != null && curReport.InspComponentGrpID != null && grid.GridAxialDistance != null) { EGridProcedure gridProc = new EGridProcedure(curReport.InspComponentGrpID); if (gridProc.GridProcedureDsDiameters != null) { decimal od = (decimal)(component.ComponentDnMainOd == null ? component.ComponentUpMainOd : component.ComponentDnMainOd); decimal minRows = (gridDsExtRowCount_UseCeiling ? Math.Ceiling((decimal)gridProc.GridProcedureDsDiameters * od / (decimal)grid.GridAxialDistance) : Math.Round((decimal)gridProc.GridProcedureDsDiameters * od / (decimal)grid.GridAxialDistance)); if ((grid.GridDnExtEndRow - grid.GridDnExtStartRow + 1) < minRows) AddLine(inspName, "N/A", "Too few downstream extension rows for the grid. There are " + (grid.GridDnExtEndRow - grid.GridDnExtStartRow + 1) + ". Expected " + minRows); } } // Check that there are at least 3 upstream rows unless a special axial location is set if (grid.GridUpExtEndRow != null && grid.GridUpExtStartRow != null && grid.GridAxialLocOverride == null) if (grid.GridUpExtEndRow - grid.GridUpExtStartRow + 1 < 3) AddLine(inspName, "N/A", "Too few upstream extension rows for the grid. There are " + (grid.GridUpExtEndRow - grid.GridUpExtStartRow + 1) + ". Expected 3"); if (grid.GridRdlID == null) AddLine(inspName, "N/A", "No radial location specified for the grid"); if (component.BranchThicknessesDefined && !grid.IsBranchDefined) AddLine(inspName, "N/A", "The component has a branch, but no branch partition information was specified for the grid"); if (component.BranchExtThicknessesDefined && !grid.IsBranchExtDefined) AddLine(inspName, "N/A", "The component has a branch, but no branch extension partition information was specified for the grid"); if (component.DnMainThicknessesDefined && !grid.IsDsMainDefined) AddLine(inspName, "N/A", "The component has a downstream section, but no downstream main partition information was specified for the grid"); } if (curReport.InspComponentGrpID == null && gridProcedureRequired) { AddLine("N/A", "N/A", "The report includes grids but no grid procedure was specified"); } EDsetCollection dsets = EDset.ListByNameForInspection((Guid)inspection.ID); foreach (EDset dset in dsets) { string dsetName = dset.DsetName; EInspector inspector = null; EMeter meter = null; EDucer ducer = null; ECalBlock calblock = null; EThermo thermo = null; EInspectionPeriodCollection inspPeriods = EInspectionPeriod.ListForDset(dset.ID); // Check if an inspector is specfied if (dset.DsetInsID == null) AddLine(inspName, dsetName, "No inspector specified"); else inspector = new EInspector(dset.DsetIspID); // Make sure all tools are specified if (dset.DsetMtrID == null) AddLine(inspName, dsetName, "No instrument specified"); else meter = new EMeter(dset.DsetMtrID); if (dset.DsetDcrID == null) AddLine(inspName, dsetName, "No transducer specified"); else ducer = new EDucer(dset.DsetDcrID); if (dset.DsetCbkID == null) AddLine(inspName, dsetName, "No calibration block specified"); else calblock = new ECalBlock(dset.DsetCbkID); if (dset.DsetThmID == null) { if (warnTemperatures) AddLine(inspName, dsetName, "No thermometer specified"); } else thermo = new EThermo(dset.DsetThmID); // Make sure that the ducer is ok for the meter if (dset.DsetMtrID != null && dset.DsetDcrID != null) { if (!ducer.DucerIsOkForMeter(dset.DsetMtrID)) { AddLine(inspName, dsetName, "Transducer model " + ducer.DucerModelName + " is not designed for use with instrument model " + meter.MeterModelName); } } // Make sure the meter has been calibrated recently if (dset.DsetMtrID != null) { if (meter.MeterCalDueDate == null) { AddLine(inspName, dsetName, "Meter " + meter.MeterModelAndSerial + " does not have its calibration due date set"); } else if (meter.MeterCalDueDate < DateTime.Today) { AddLine(inspName, dsetName, "Meter " + meter.MeterModelAndSerial + " was due for calibration on " + meter.MeterCalDueDate); } } // Make sure the cal block type matches the material type. if (dset.DsetCbkID != null) { EComponentMaterial cmpMaterial = new EComponentMaterial(component.ComponentCmtID); if (calblock.CalBlockMaterialType != cmpMaterial.CmpMaterialCalBlockMaterial) { AddLine(inspName, dsetName, "Calibration block material type " + calblock.CalBlockMaterialAbbr + " should not be used with component material type " + cmpMaterial.CmpMaterialName); } } // Make sure no inspections lasted too long without cal checks. if (inspPeriods.Count == 0) { AddLine(inspName, dsetName, "No inspection periods have been defined"); } else { foreach (EInspectionPeriod inspPeriod in inspPeriods) { TimeSpan span1 = TimeSpan.Zero; TimeSpan span2 = TimeSpan.Zero; TimeSpan span3 = TimeSpan.Zero; if (inspPeriod.InspectionPeriodCalCheck1At != null) span1 = (DateTime)inspPeriod.InspectionPeriodCalCheck1At - (DateTime)inspPeriod.InspectionPeriodInAt; else span1 = (DateTime)inspPeriod.InspectionPeriodOutAt - (DateTime)inspPeriod.InspectionPeriodInAt; if (inspPeriod.InspectionPeriodCalCheck1At != null) { if (inspPeriod.InspectionPeriodCalCheck2At != null) span2 = (DateTime)inspPeriod.InspectionPeriodCalCheck2At - (DateTime)inspPeriod.InspectionPeriodCalCheck1At; else span2 = (DateTime)inspPeriod.InspectionPeriodOutAt - (DateTime)inspPeriod.InspectionPeriodCalCheck1At; } if (inspPeriod.InspectionPeriodCalCheck2At != null) { span3 = (DateTime)inspPeriod.InspectionPeriodOutAt - (DateTime)inspPeriod.InspectionPeriodCalCheck2At; } if (span1.TotalHours > 4.0 || span2.TotalHours > 4.0 || span3.TotalHours > 4.0) { AddLine(inspName, dsetName, "An inspection period exceeded 4 hours between calibration checks"); } } } // Make sure the component temp is within 25 degrees of the cal block temp. if (warnTemperatures && dset.DsetCalBlockTemp == null) AddLine(inspName, dsetName, "No calibration block temperature specified"); if (warnTemperatures && dset.DsetCompTemp == null) AddLine(inspName, dsetName, "No component temperature specified"); if (dset.DsetCompTemp != null && dset.DsetCalBlockTemp != null && Math.Abs((int)(dset.DsetCompTemp - dset.DsetCalBlockTemp)) > 25) AddLine(inspName, dsetName, "Difference between calibration block temperature and component temperature exceeds 25 degrees F"); // Make sure the inspector is Level II or III if (dset.DsetInsID != null && inspector.InspectorLevel < 2) AddLine(inspName, dsetName, "Inspector " + inspector.InspectorName + " is not level II or III"); // Todo: check if they really want the inspector's impression of the min and max in the system. if (dset.DsetMinWall != null && dset.DsetCbkID != null) if (dset.DsetMinWall < System.Convert.ToSingle(calblock.CalBlockCalMin)) AddLine(inspName, dsetName, "The dataset contains readings below the minimum for the calibration block used"); if (dset.DsetMaxWall != null && dset.DsetCbkID != null) if (dset.DsetMaxWall > System.Convert.ToSingle(calblock.CalBlockCalMax)) AddLine(inspName, dsetName, "The dataset contains readings above the maximum for the calibration block used"); if (dset.DsetThin == null) AddLine(inspName, dsetName, "Low calibration thickness was not recorded"); if (dset.DsetThick == null) AddLine(inspName, dsetName, "High calibration thickness was not recorded"); if (dset.DsetRange == null) AddLine(inspName, dsetName, "Coarse range was not recorded"); if (dset.DsetThin != null && dset.DsetMinWall != null && dset.DsetMinWall < System.Convert.ToSingle(dset.DsetThin)) AddLine(inspName, dsetName, "The dataset contains readings below the low calibration thickness"); if (dset.DsetThick != null && dset.DsetMaxWall != null && dset.DsetMaxWall > System.Convert.ToSingle(dset.DsetThick)) AddLine(inspName, dsetName, "The dataset contains readings above the high calibration thickness"); if (dset.DsetRange != null && dset.DsetMaxWall != null && dset.DsetMaxWall > System.Convert.ToSingle(dset.DsetRange)) AddLine(inspName, dsetName, "The dataset contains readings above the coarse range for the instrument"); if (dset.DsetCrewDose == null) AddLine(inspName, dsetName, "The crew dose was not specified"); if (dset.DsetGainDb == null) AddLine(inspName, dsetName, "The gain was not specified"); if (dset.DsetVelocity == null) AddLine(inspName, dsetName, "The velocity was not specified"); } } if (dgvInfo.Rows.Count == 0) dgvInfo.Visible = false; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Collections; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Interfaces { /// <summary> /// Interface to an entity's (SceneObjectPart's) inventory /// </summary> /// /// This is not a finished 1.0 candidate interface public interface IEntityInventory { /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> void ForceInventoryPersistence(); /// <summary> /// Reset UUIDs for all the items in the prim's inventory. /// </summary> /// /// This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// /// <param name="linkNum">Link number for the part</param> void ResetInventoryIDs(); /// <summary> /// Reset parent object UUID for all the items in the prim's inventory. /// </summary> /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// /// <param name="linkNum">Link number for the part</param> void ResetObjectID(); /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> void ChangeInventoryOwner(UUID ownerId); /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> void ChangeInventoryGroup(UUID groupID); /// <summary> /// Start all the scripts contained in this entity's inventory /// </summary> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> /// <returns>Number of scripts started.</returns> int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource); ArrayList GetScriptErrors(UUID itemID); void ResumeScripts(); /// <summary> /// Stop and remove all the scripts in this entity from the scene. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> void RemoveScriptInstances(bool sceneObjectBeingDeleted); /// <summary> /// Stop all the scripts in this entity. /// </summary> void StopScriptInstances(); /// <summary> /// Start a script which is in this entity's inventory. /// </summary> /// <param name="item"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> /// <returns> /// true if the script instance was valid for starting, false otherwise. This does not guarantee /// that the script was actually started, just that the script was valid (i.e. its asset data could be found, etc.) /// </returns> bool CreateScriptInstance( TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource); /// <summary> /// Start a script which is in this entity's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> /// <returns> /// true if the script instance was valid for starting, false otherwise. This does not guarantee /// that the script was actually started, just that the script was valid (i.e. its asset data could be found, etc.) /// </returns> bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource); ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource); /// <summary> /// Stop and remove a script which is in this prim's inventory from the scene. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted); /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> void StopScriptInstance(UUID itemId); /// <summary> /// Try to get the script running status. /// </summary> /// <returns> /// Returns true if a script for the item was found in one of the simulator's script engines. In this case, /// the running parameter will reflect the running status. /// Returns false if the item could not be found, if the item is not a script or if a script instance for the /// item was not found in any of the script engines. In this case, running status is irrelevant. /// </returns> /// <param name='itemId'></param> /// <param name='running'></param> bool TryGetScriptInstanceRunning(UUID itemId, out bool running); /// <summary> /// Add an item to this entity's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> void AddInventoryItem(TaskInventoryItem item, bool allowedDrop); /// <summary> /// Add an item to this entity's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop); /// <summary> /// Restore a whole collection of items to the entity's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> void RestoreInventoryItems(ICollection<TaskInventoryItem> items); /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> TaskInventoryItem GetInventoryItem(UUID itemId); /// <summary> /// Get all inventory items. /// </summary> /// <param name="name"></param> /// <returns> /// If there are no inventory items then an empty list is returned. /// </returns> List<TaskInventoryItem> GetInventoryItems(); /// <summary> /// Gets an inventory item by name /// </summary> /// <remarks> /// This method returns the first inventory item that matches the given name. In SL this is all you need /// since each item in a prim inventory must have a unique name. /// </remarks> /// <param name='name'></param> /// <returns> /// The inventory item. Null if no such item was found. /// </returns> TaskInventoryItem GetInventoryItem(string name); /// <summary> /// Get inventory items by name. /// </summary> /// <param name="name"></param> /// <returns> /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. /// </returns> List<TaskInventoryItem> GetInventoryItems(string name); /// <summary> /// Get inventory items by type. /// </summary> /// <param type="name"></param> /// <returns> /// A list of inventory items of that type. /// If no inventory items of that type then an empty list is returned. /// </returns> List<TaskInventoryItem> GetInventoryItems(InventoryType type); /// <summary> /// Get the scene object(s) referenced by an inventory item. /// </summary> /// /// This is returned in a 'rez ready' state. That is, name, description, permissions and other details have /// been adjusted to reflect the part and item from which it originates. /// /// <param name="item">Inventory item</param> /// <param name="objlist">The scene objects</param> /// <param name="veclist">Relative offsets for each object</param> /// <returns>true = success, false = the scene object asset couldn't be found</returns> bool GetRezReadySceneObjects(TaskInventoryItem item, out List<SceneObjectGroup> objlist, out List<Vector3> veclist, out Vector3 bbox, out float offsetHeight); /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> bool UpdateInventoryItem(TaskInventoryItem item); bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents); bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged); /// <summary> /// Remove an item from this entity's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> int RemoveInventoryItem(UUID itemID); /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> void RequestInventoryFile(IClientAPI client, IXfer xferManager); /// <summary> /// Backup the inventory to the given data store /// </summary> /// <param name="datastore"></param> void ProcessInventoryBackup(ISimulationDataService datastore); uint MaskEffectivePermissions(); void ApplyNextOwnerPermissions(); void ApplyGodPermissions(uint perms); /// <summary> /// Number of items in this inventory. /// </summary> int Count { get; } /// <summary> /// Returns true if this inventory contains any scripts /// </summary></returns> bool ContainsScripts(); /// <summary> /// Number of scripts in this inventory. /// </summary> /// <remarks> /// Includes both running and non running scripts. /// </remarks> int ScriptCount(); /// <summary> /// Number of running scripts in this inventory. /// </summary></returns> int RunningScriptCount(); /// <summary> /// Get the uuids of all items in this inventory /// </summary> /// <returns></returns> List<UUID> GetInventoryList(); /// <summary> /// Get the xml representing the saved states of scripts in this inventory. /// </summary> /// <returns> /// A <see cref="Dictionary`2"/> /// </returns> Dictionary<UUID, string> GetScriptStates(); Dictionary<UUID, string> GetScriptStates(bool oldIDs); } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.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 OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// HudsonMasterComputer /// </summary> [DataContract] public partial class HudsonMasterComputer : IEquatable<HudsonMasterComputer>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HudsonMasterComputer" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="executors">executors.</param> /// <param name="icon">icon.</param> /// <param name="iconClassName">iconClassName.</param> /// <param name="idle">idle.</param> /// <param name="jnlpAgent">jnlpAgent.</param> /// <param name="launchSupported">launchSupported.</param> /// <param name="loadStatistics">loadStatistics.</param> /// <param name="manualLaunchAllowed">manualLaunchAllowed.</param> /// <param name="monitorData">monitorData.</param> /// <param name="numExecutors">numExecutors.</param> /// <param name="offline">offline.</param> /// <param name="offlineCause">offlineCause.</param> /// <param name="offlineCauseReason">offlineCauseReason.</param> /// <param name="temporarilyOffline">temporarilyOffline.</param> public HudsonMasterComputer(string _class = default(string), string displayName = default(string), List<HudsonMasterComputerexecutors> executors = default(List<HudsonMasterComputerexecutors>), string icon = default(string), string iconClassName = default(string), bool idle = default(bool), bool jnlpAgent = default(bool), bool launchSupported = default(bool), Label1 loadStatistics = default(Label1), bool manualLaunchAllowed = default(bool), HudsonMasterComputermonitorData monitorData = default(HudsonMasterComputermonitorData), int numExecutors = default(int), bool offline = default(bool), string offlineCause = default(string), string offlineCauseReason = default(string), bool temporarilyOffline = default(bool)) { this.Class = _class; this.DisplayName = displayName; this.Executors = executors; this.Icon = icon; this.IconClassName = iconClassName; this.Idle = idle; this.JnlpAgent = jnlpAgent; this.LaunchSupported = launchSupported; this.LoadStatistics = loadStatistics; this.ManualLaunchAllowed = manualLaunchAllowed; this.MonitorData = monitorData; this.NumExecutors = numExecutors; this.Offline = offline; this.OfflineCause = offlineCause; this.OfflineCauseReason = offlineCauseReason; this.TemporarilyOffline = temporarilyOffline; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets Executors /// </summary> [DataMember(Name="executors", EmitDefaultValue=false)] public List<HudsonMasterComputerexecutors> Executors { get; set; } /// <summary> /// Gets or Sets Icon /// </summary> [DataMember(Name="icon", EmitDefaultValue=false)] public string Icon { get; set; } /// <summary> /// Gets or Sets IconClassName /// </summary> [DataMember(Name="iconClassName", EmitDefaultValue=false)] public string IconClassName { get; set; } /// <summary> /// Gets or Sets Idle /// </summary> [DataMember(Name="idle", EmitDefaultValue=false)] public bool Idle { get; set; } /// <summary> /// Gets or Sets JnlpAgent /// </summary> [DataMember(Name="jnlpAgent", EmitDefaultValue=false)] public bool JnlpAgent { get; set; } /// <summary> /// Gets or Sets LaunchSupported /// </summary> [DataMember(Name="launchSupported", EmitDefaultValue=false)] public bool LaunchSupported { get; set; } /// <summary> /// Gets or Sets LoadStatistics /// </summary> [DataMember(Name="loadStatistics", EmitDefaultValue=false)] public Label1 LoadStatistics { get; set; } /// <summary> /// Gets or Sets ManualLaunchAllowed /// </summary> [DataMember(Name="manualLaunchAllowed", EmitDefaultValue=false)] public bool ManualLaunchAllowed { get; set; } /// <summary> /// Gets or Sets MonitorData /// </summary> [DataMember(Name="monitorData", EmitDefaultValue=false)] public HudsonMasterComputermonitorData MonitorData { get; set; } /// <summary> /// Gets or Sets NumExecutors /// </summary> [DataMember(Name="numExecutors", EmitDefaultValue=false)] public int NumExecutors { get; set; } /// <summary> /// Gets or Sets Offline /// </summary> [DataMember(Name="offline", EmitDefaultValue=false)] public bool Offline { get; set; } /// <summary> /// Gets or Sets OfflineCause /// </summary> [DataMember(Name="offlineCause", EmitDefaultValue=false)] public string OfflineCause { get; set; } /// <summary> /// Gets or Sets OfflineCauseReason /// </summary> [DataMember(Name="offlineCauseReason", EmitDefaultValue=false)] public string OfflineCauseReason { get; set; } /// <summary> /// Gets or Sets TemporarilyOffline /// </summary> [DataMember(Name="temporarilyOffline", EmitDefaultValue=false)] public bool TemporarilyOffline { 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 HudsonMasterComputer {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" Executors: ").Append(Executors).Append("\n"); sb.Append(" Icon: ").Append(Icon).Append("\n"); sb.Append(" IconClassName: ").Append(IconClassName).Append("\n"); sb.Append(" Idle: ").Append(Idle).Append("\n"); sb.Append(" JnlpAgent: ").Append(JnlpAgent).Append("\n"); sb.Append(" LaunchSupported: ").Append(LaunchSupported).Append("\n"); sb.Append(" LoadStatistics: ").Append(LoadStatistics).Append("\n"); sb.Append(" ManualLaunchAllowed: ").Append(ManualLaunchAllowed).Append("\n"); sb.Append(" MonitorData: ").Append(MonitorData).Append("\n"); sb.Append(" NumExecutors: ").Append(NumExecutors).Append("\n"); sb.Append(" Offline: ").Append(Offline).Append("\n"); sb.Append(" OfflineCause: ").Append(OfflineCause).Append("\n"); sb.Append(" OfflineCauseReason: ").Append(OfflineCauseReason).Append("\n"); sb.Append(" TemporarilyOffline: ").Append(TemporarilyOffline).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as HudsonMasterComputer); } /// <summary> /// Returns true if HudsonMasterComputer instances are equal /// </summary> /// <param name="input">Instance of HudsonMasterComputer to be compared</param> /// <returns>Boolean</returns> public bool Equals(HudsonMasterComputer input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.Executors == input.Executors || this.Executors != null && input.Executors != null && this.Executors.SequenceEqual(input.Executors) ) && ( this.Icon == input.Icon || (this.Icon != null && this.Icon.Equals(input.Icon)) ) && ( this.IconClassName == input.IconClassName || (this.IconClassName != null && this.IconClassName.Equals(input.IconClassName)) ) && ( this.Idle == input.Idle || (this.Idle != null && this.Idle.Equals(input.Idle)) ) && ( this.JnlpAgent == input.JnlpAgent || (this.JnlpAgent != null && this.JnlpAgent.Equals(input.JnlpAgent)) ) && ( this.LaunchSupported == input.LaunchSupported || (this.LaunchSupported != null && this.LaunchSupported.Equals(input.LaunchSupported)) ) && ( this.LoadStatistics == input.LoadStatistics || (this.LoadStatistics != null && this.LoadStatistics.Equals(input.LoadStatistics)) ) && ( this.ManualLaunchAllowed == input.ManualLaunchAllowed || (this.ManualLaunchAllowed != null && this.ManualLaunchAllowed.Equals(input.ManualLaunchAllowed)) ) && ( this.MonitorData == input.MonitorData || (this.MonitorData != null && this.MonitorData.Equals(input.MonitorData)) ) && ( this.NumExecutors == input.NumExecutors || (this.NumExecutors != null && this.NumExecutors.Equals(input.NumExecutors)) ) && ( this.Offline == input.Offline || (this.Offline != null && this.Offline.Equals(input.Offline)) ) && ( this.OfflineCause == input.OfflineCause || (this.OfflineCause != null && this.OfflineCause.Equals(input.OfflineCause)) ) && ( this.OfflineCauseReason == input.OfflineCauseReason || (this.OfflineCauseReason != null && this.OfflineCauseReason.Equals(input.OfflineCauseReason)) ) && ( this.TemporarilyOffline == input.TemporarilyOffline || (this.TemporarilyOffline != null && this.TemporarilyOffline.Equals(input.TemporarilyOffline)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); if (this.Executors != null) hashCode = hashCode * 59 + this.Executors.GetHashCode(); if (this.Icon != null) hashCode = hashCode * 59 + this.Icon.GetHashCode(); if (this.IconClassName != null) hashCode = hashCode * 59 + this.IconClassName.GetHashCode(); if (this.Idle != null) hashCode = hashCode * 59 + this.Idle.GetHashCode(); if (this.JnlpAgent != null) hashCode = hashCode * 59 + this.JnlpAgent.GetHashCode(); if (this.LaunchSupported != null) hashCode = hashCode * 59 + this.LaunchSupported.GetHashCode(); if (this.LoadStatistics != null) hashCode = hashCode * 59 + this.LoadStatistics.GetHashCode(); if (this.ManualLaunchAllowed != null) hashCode = hashCode * 59 + this.ManualLaunchAllowed.GetHashCode(); if (this.MonitorData != null) hashCode = hashCode * 59 + this.MonitorData.GetHashCode(); if (this.NumExecutors != null) hashCode = hashCode * 59 + this.NumExecutors.GetHashCode(); if (this.Offline != null) hashCode = hashCode * 59 + this.Offline.GetHashCode(); if (this.OfflineCause != null) hashCode = hashCode * 59 + this.OfflineCause.GetHashCode(); if (this.OfflineCauseReason != null) hashCode = hashCode * 59 + this.OfflineCauseReason.GetHashCode(); if (this.TemporarilyOffline != null) hashCode = hashCode * 59 + this.TemporarilyOffline.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using UnityEngine; namespace UnityStandardAssets.Characters.ThirdPerson { [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] public class ThirdPersonCharacter : MonoBehaviour { [SerializeField] float m_MovingTurnSpeed = 660; [SerializeField] float m_StationaryTurnSpeed = 180; [SerializeField] float m_JumpPower = 12f; [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f; [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others [SerializeField] float m_MoveSpeedMultiplier = 4f; [SerializeField] float m_AnimSpeedMultiplier = 1f; [SerializeField] float m_GroundCheckDistance = 0.1f; Rigidbody m_Rigidbody; Animator m_Animator; bool m_IsGrounded; float m_OrigGroundCheckDistance; const float k_Half = 0.5f; float m_TurnAmount; float m_ForwardAmount; Vector3 m_GroundNormal; float m_CapsuleHeight; Vector3 m_CapsuleCenter; CapsuleCollider m_Capsule; bool m_Crouching; Rigidbody m_GrabRigidbody; void Start() { m_Animator = GetComponent<Animator>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); m_CapsuleHeight = m_Capsule.height; m_CapsuleCenter = m_Capsule.center; m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; m_OrigGroundCheckDistance = m_GroundCheckDistance; } public void Move(Vector3 move, bool crouch, bool jump) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); CheckGroundStatus(); move = Vector3.ProjectOnPlane(move, m_GroundNormal); m_TurnAmount = Mathf.Atan2(move.x, move.z); m_ForwardAmount = move.z; ApplyExtraTurnRotation(); // control and velocity handling is different when grounded and airborne: if (m_IsGrounded) { if(m_GrabRigidbody != null){ HandleGrabMovement(crouch, jump); }else{ HandleGroundedMovement(crouch, jump); } } else { HandleAirborneMovement(); } ScaleCapsuleForCrouching(crouch); PreventStandingInLowHeadroom(); // send input and other state parameters to the animator UpdateAnimator(move); } public void Grab(Rigidbody grabRigidbody){ m_GrabRigidbody = grabRigidbody; } public void Drop(){ m_GrabRigidbody.freezeRotation = false; m_GrabRigidbody = null; } void ScaleCapsuleForCrouching(bool crouch) { if (m_IsGrounded && crouch) { if (m_Crouching) return; m_Capsule.height = m_Capsule.height / 2f; m_Capsule.center = m_Capsule.center / 2f; m_Crouching = true; } else { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength)) { m_Crouching = true; return; } m_Capsule.height = m_CapsuleHeight; m_Capsule.center = m_CapsuleCenter; m_Crouching = false; } } void PreventStandingInLowHeadroom() { // prevent standing up in crouch-only zones if (!m_Crouching) { Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up); float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half; if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength)) { m_Crouching = true; } } } void UpdateAnimator(Vector3 move) { // update the animator parameters m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime); m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime); m_Animator.SetBool("Crouch", m_Crouching); m_Animator.SetBool("OnGround", m_IsGrounded); if (!m_IsGrounded) { m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y); } // calculate which leg is behind, so as to leave that leg trailing in the jump animation // (This code is reliant on the specific run cycle offset in our animations, // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5) float runCycle = Mathf.Repeat( m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1); float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount; if (m_IsGrounded) { m_Animator.SetFloat("JumpLeg", jumpLeg); } // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector, // which affects the movement speed because of the root motion. if (m_IsGrounded && move.magnitude > 0) { m_Animator.speed = m_AnimSpeedMultiplier; } else { // don't use that while airborne m_Animator.speed = 1; } } void HandleAirborneMovement() { // apply extra gravity from multiplier: Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity; m_Rigidbody.AddForce(extraGravityForce); m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f; } void HandleGroundedMovement(bool crouch, bool jump) { // check whether conditions are right to allow a jump: if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded")) { // jump! m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z); m_IsGrounded = false; m_Animator.applyRootMotion = false; m_GroundCheckDistance = 0.1f; } } void HandleGrabMovement(bool crouch, bool jump) { } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount * 4); transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0); } public void OnAnimatorMove() { // we implement this function to override the default root motion. // this allows us to modify the positional speed before it's applied. if (m_IsGrounded && Time.deltaTime > 0) { Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime; // we preserve the existing y part of the current velocity. v.y = m_Rigidbody.velocity.y; m_Rigidbody.velocity = v; if(m_GrabRigidbody != null){ Quaternion target = Quaternion.Euler( m_GrabRigidbody.rotation.eulerAngles.x, Mathf.Round (m_GrabRigidbody.rotation.eulerAngles.y / 90) * 90, m_GrabRigidbody.rotation.eulerAngles.z ); m_GrabRigidbody.rotation = Quaternion.Slerp(m_GrabRigidbody.rotation, target, Time.deltaTime * 3f); m_GrabRigidbody.freezeRotation = true; m_GrabRigidbody.velocity = v; } } } void CheckGroundStatus() { RaycastHit hitInfo; #if UNITY_EDITOR // helper to visualise the ground check ray in the scene view Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance)); #endif // 0.1f is a small offset to start the ray from inside the character // it is also good to note that the transform position in the sample assets is at the base of the character if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance)) { m_GroundNormal = hitInfo.normal; m_IsGrounded = true; m_Animator.applyRootMotion = true; } else { m_IsGrounded = false; m_GroundNormal = Vector3.up; m_Animator.applyRootMotion = false; } } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Globalization; namespace Reporting.RdlDesign { /// <summary> /// Summary description for StyleCtl. /// </summary> internal class StyleBorderCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; // flags for controlling whether syntax changed for a particular property private bool fStyleDefault, fStyleLeft, fStyleRight, fStyleTop, fStyleBottom; private bool fColorDefault, fColorLeft, fColorRight, fColorTop, fColorBottom; private bool fWidthDefault, fWidthLeft, fWidthRight, fWidthTop, fWidthBottom; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cbStyleLeft; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox cbStyleBottom; private System.Windows.Forms.ComboBox cbStyleTop; private System.Windows.Forms.ComboBox cbStyleRight; private System.Windows.Forms.Button bColorLeft; private System.Windows.Forms.ComboBox cbColorLeft; private System.Windows.Forms.Button bColorRight; private System.Windows.Forms.ComboBox cbColorRight; private System.Windows.Forms.Button bColorTop; private System.Windows.Forms.ComboBox cbColorTop; private System.Windows.Forms.Button bColorBottom; private System.Windows.Forms.ComboBox cbColorBottom; private System.Windows.Forms.TextBox tbWidthLeft; private System.Windows.Forms.TextBox tbWidthRight; private System.Windows.Forms.TextBox tbWidthTop; private System.Windows.Forms.TextBox tbWidthBottom; private System.Windows.Forms.TextBox tbWidthDefault; private System.Windows.Forms.Button bColorDefault; private System.Windows.Forms.ComboBox cbColorDefault; private System.Windows.Forms.ComboBox cbStyleDefault; private System.Windows.Forms.Label lLeft; private System.Windows.Forms.Label lBottom; private System.Windows.Forms.Label lTop; private System.Windows.Forms.Label lRight; private System.Windows.Forms.Button bSD; private System.Windows.Forms.Button bSL; private System.Windows.Forms.Button bSR; private System.Windows.Forms.Button bST; private System.Windows.Forms.Button bSB; private System.Windows.Forms.Button bCD; private System.Windows.Forms.Button bCT; private System.Windows.Forms.Button bCB; private System.Windows.Forms.Button bWB; private System.Windows.Forms.Button bWT; private System.Windows.Forms.Button bWR; private System.Windows.Forms.Button bCR; private System.Windows.Forms.Button bWL; private System.Windows.Forms.Button bWD; private System.Windows.Forms.Button bCL; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private string[] _names; internal StyleBorderCtl(DesignXmlDraw dxDraw, string[] names, List<XmlNode> reportItems) { _ReportItems = reportItems; _Draw = dxDraw; _names = names; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitBorders(reportItems[0]); } private void InitBorders(XmlNode node) { cbColorDefault.Items.AddRange(StaticLists.ColorList); cbColorLeft.Items.AddRange(StaticLists.ColorList); cbColorRight.Items.AddRange(StaticLists.ColorList); cbColorTop.Items.AddRange(StaticLists.ColorList); cbColorBottom.Items.AddRange(StaticLists.ColorList); if (_names != null) { node = _Draw.FindCreateNextInHierarchy(node, _names); } XmlNode sNode = _Draw.GetCreateNamedChildNode(node, "Style"); // Handle BorderStyle XmlNode bsNode = _Draw.SetElement(sNode, "BorderStyle", null); cbStyleDefault.Text = _Draw.GetElementValue(bsNode, "Default", "None"); cbStyleLeft.Text = _Draw.GetElementValue(bsNode, "Left", cbStyleDefault.Text); cbStyleRight.Text = _Draw.GetElementValue(bsNode, "Right", cbStyleDefault.Text); cbStyleTop.Text = _Draw.GetElementValue(bsNode, "Top", cbStyleDefault.Text); cbStyleBottom.Text = _Draw.GetElementValue(bsNode, "Bottom", cbStyleDefault.Text); // Handle BorderColor XmlNode bcNode = _Draw.SetElement(sNode, "BorderColor", null); cbColorDefault.Text = _Draw.GetElementValue(bcNode, "Default", "Black"); cbColorLeft.Text = _Draw.GetElementValue(bcNode, "Left", cbColorDefault.Text); cbColorRight.Text = _Draw.GetElementValue(bcNode, "Right", cbColorDefault.Text); cbColorTop.Text = _Draw.GetElementValue(bcNode, "Top", cbColorDefault.Text); cbColorBottom.Text = _Draw.GetElementValue(bcNode, "Bottom", cbColorDefault.Text); // Handle BorderWidth XmlNode bwNode = _Draw.SetElement(sNode, "BorderWidth", null); tbWidthDefault.Text = _Draw.GetElementValue(bwNode, "Default", "1pt"); tbWidthLeft.Text = _Draw.GetElementValue(bwNode, "Left", tbWidthDefault.Text); tbWidthRight.Text = _Draw.GetElementValue(bwNode, "Right", tbWidthDefault.Text); tbWidthTop.Text = _Draw.GetElementValue(bwNode, "Top", tbWidthDefault.Text); tbWidthBottom.Text = _Draw.GetElementValue(bwNode, "Bottom", tbWidthDefault.Text); if (node.Name == "Line") { cbColorLeft.Visible = cbColorRight.Visible = cbColorTop.Visible = cbColorBottom.Visible = bColorLeft.Visible = bColorRight.Visible = bColorTop.Visible = bColorBottom.Visible = cbStyleLeft.Visible = cbStyleRight.Visible = cbStyleTop.Visible = cbStyleBottom.Visible = lLeft.Visible = lRight.Visible = lTop.Visible = lBottom.Visible = tbWidthLeft.Visible = tbWidthRight.Visible = tbWidthTop.Visible = tbWidthBottom.Visible = bCR.Visible = bCL.Visible = bCT.Visible = bCB.Visible = bSR.Visible = bSL.Visible = bST.Visible = bSB.Visible = bWR.Visible = bWL.Visible = bWT.Visible = bWB.Visible = false; } fStyleDefault = fStyleLeft = fStyleRight = fStyleTop = fStyleBottom = fColorDefault = fColorLeft = fColorRight = fColorTop = fColorBottom = fWidthDefault = fWidthLeft = fWidthRight = fWidthTop = fWidthBottom= false; } /// <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 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.lLeft = new System.Windows.Forms.Label(); this.lBottom = new System.Windows.Forms.Label(); this.lTop = new System.Windows.Forms.Label(); this.lRight = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.cbStyleLeft = new System.Windows.Forms.ComboBox(); this.cbStyleBottom = new System.Windows.Forms.ComboBox(); this.cbStyleTop = new System.Windows.Forms.ComboBox(); this.cbStyleRight = new System.Windows.Forms.ComboBox(); this.bColorLeft = new System.Windows.Forms.Button(); this.cbColorLeft = new System.Windows.Forms.ComboBox(); this.bColorRight = new System.Windows.Forms.Button(); this.cbColorRight = new System.Windows.Forms.ComboBox(); this.bColorTop = new System.Windows.Forms.Button(); this.cbColorTop = new System.Windows.Forms.ComboBox(); this.bColorBottom = new System.Windows.Forms.Button(); this.cbColorBottom = new System.Windows.Forms.ComboBox(); this.tbWidthLeft = new System.Windows.Forms.TextBox(); this.tbWidthRight = new System.Windows.Forms.TextBox(); this.tbWidthTop = new System.Windows.Forms.TextBox(); this.tbWidthBottom = new System.Windows.Forms.TextBox(); this.tbWidthDefault = new System.Windows.Forms.TextBox(); this.bColorDefault = new System.Windows.Forms.Button(); this.cbColorDefault = new System.Windows.Forms.ComboBox(); this.cbStyleDefault = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.bSD = new System.Windows.Forms.Button(); this.bSL = new System.Windows.Forms.Button(); this.bSR = new System.Windows.Forms.Button(); this.bST = new System.Windows.Forms.Button(); this.bSB = new System.Windows.Forms.Button(); this.bCD = new System.Windows.Forms.Button(); this.bCT = new System.Windows.Forms.Button(); this.bCB = new System.Windows.Forms.Button(); this.bWB = new System.Windows.Forms.Button(); this.bWT = new System.Windows.Forms.Button(); this.bWR = new System.Windows.Forms.Button(); this.bCR = new System.Windows.Forms.Button(); this.bWL = new System.Windows.Forms.Button(); this.bWD = new System.Windows.Forms.Button(); this.bCL = new System.Windows.Forms.Button(); this.SuspendLayout(); // // lLeft // this.lLeft.Location = new System.Drawing.Point(16, 74); this.lLeft.Name = "lLeft"; this.lLeft.Size = new System.Drawing.Size(40, 16); this.lLeft.TabIndex = 0; this.lLeft.Text = "Left"; this.lLeft.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lBottom // this.lBottom.Location = new System.Drawing.Point(16, 170); this.lBottom.Name = "lBottom"; this.lBottom.Size = new System.Drawing.Size(40, 16); this.lBottom.TabIndex = 2; this.lBottom.Text = "Bottom"; this.lBottom.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lTop // this.lTop.Location = new System.Drawing.Point(16, 138); this.lTop.Name = "lTop"; this.lTop.Size = new System.Drawing.Size(40, 16); this.lTop.TabIndex = 3; this.lTop.Text = "Top"; this.lTop.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // lRight // this.lRight.Location = new System.Drawing.Point(16, 106); this.lRight.Name = "lRight"; this.lRight.Size = new System.Drawing.Size(40, 16); this.lRight.TabIndex = 4; this.lRight.Text = "Right"; this.lRight.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.Location = new System.Drawing.Point(72, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(56, 16); this.label2.TabIndex = 5; this.label2.Text = "Style"; // // label6 // this.label6.Location = new System.Drawing.Point(343, 16); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(56, 16); this.label6.TabIndex = 6; this.label6.Text = "Width"; // // label7 // this.label7.Location = new System.Drawing.Point(192, 16); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(56, 16); this.label7.TabIndex = 7; this.label7.Text = "Color"; // // cbStyleLeft // this.cbStyleLeft.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbStyleLeft.Location = new System.Drawing.Point(56, 72); this.cbStyleLeft.Name = "cbStyleLeft"; this.cbStyleLeft.Size = new System.Drawing.Size(88, 21); this.cbStyleLeft.TabIndex = 7; this.cbStyleLeft.SelectedIndexChanged += new System.EventHandler(this.cbStyle_SelectedIndexChanged); // // cbStyleBottom // this.cbStyleBottom.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbStyleBottom.Location = new System.Drawing.Point(56, 168); this.cbStyleBottom.Name = "cbStyleBottom"; this.cbStyleBottom.Size = new System.Drawing.Size(88, 21); this.cbStyleBottom.TabIndex = 28; this.cbStyleBottom.SelectedIndexChanged += new System.EventHandler(this.cbStyle_SelectedIndexChanged); // // cbStyleTop // this.cbStyleTop.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbStyleTop.Location = new System.Drawing.Point(56, 136); this.cbStyleTop.Name = "cbStyleTop"; this.cbStyleTop.Size = new System.Drawing.Size(88, 21); this.cbStyleTop.TabIndex = 21; this.cbStyleTop.SelectedIndexChanged += new System.EventHandler(this.cbStyle_SelectedIndexChanged); // // cbStyleRight // this.cbStyleRight.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbStyleRight.Location = new System.Drawing.Point(56, 104); this.cbStyleRight.Name = "cbStyleRight"; this.cbStyleRight.Size = new System.Drawing.Size(88, 21); this.cbStyleRight.TabIndex = 14; this.cbStyleRight.SelectedIndexChanged += new System.EventHandler(this.cbStyle_SelectedIndexChanged); // // bColorLeft // this.bColorLeft.Location = new System.Drawing.Point(306, 72); this.bColorLeft.Name = "bColorLeft"; this.bColorLeft.Size = new System.Drawing.Size(24, 21); this.bColorLeft.TabIndex = 11; this.bColorLeft.Text = "..."; this.bColorLeft.Click += new System.EventHandler(this.bColor_Click); // // cbColorLeft // this.cbColorLeft.Location = new System.Drawing.Point(176, 72); this.cbColorLeft.Name = "cbColorLeft"; this.cbColorLeft.Size = new System.Drawing.Size(96, 21); this.cbColorLeft.TabIndex = 9; this.cbColorLeft.SelectedIndexChanged += new System.EventHandler(this.cbColor_SelectedIndexChanged); // // bColorRight // this.bColorRight.Location = new System.Drawing.Point(306, 104); this.bColorRight.Name = "bColorRight"; this.bColorRight.Size = new System.Drawing.Size(24, 21); this.bColorRight.TabIndex = 18; this.bColorRight.Text = "..."; this.bColorRight.Click += new System.EventHandler(this.bColor_Click); // // cbColorRight // this.cbColorRight.Location = new System.Drawing.Point(176, 104); this.cbColorRight.Name = "cbColorRight"; this.cbColorRight.Size = new System.Drawing.Size(96, 21); this.cbColorRight.TabIndex = 16; this.cbColorRight.SelectedIndexChanged += new System.EventHandler(this.cbColor_SelectedIndexChanged); // // bColorTop // this.bColorTop.Location = new System.Drawing.Point(306, 136); this.bColorTop.Name = "bColorTop"; this.bColorTop.Size = new System.Drawing.Size(24, 21); this.bColorTop.TabIndex = 25; this.bColorTop.Text = "..."; this.bColorTop.Click += new System.EventHandler(this.bColor_Click); // // cbColorTop // this.cbColorTop.Location = new System.Drawing.Point(176, 136); this.cbColorTop.Name = "cbColorTop"; this.cbColorTop.Size = new System.Drawing.Size(96, 21); this.cbColorTop.TabIndex = 23; this.cbColorTop.SelectedIndexChanged += new System.EventHandler(this.cbColor_SelectedIndexChanged); // // bColorBottom // this.bColorBottom.Location = new System.Drawing.Point(306, 168); this.bColorBottom.Name = "bColorBottom"; this.bColorBottom.Size = new System.Drawing.Size(24, 21); this.bColorBottom.TabIndex = 32; this.bColorBottom.Text = "..."; this.bColorBottom.Click += new System.EventHandler(this.bColor_Click); // // cbColorBottom // this.cbColorBottom.Location = new System.Drawing.Point(176, 168); this.cbColorBottom.Name = "cbColorBottom"; this.cbColorBottom.Size = new System.Drawing.Size(96, 21); this.cbColorBottom.TabIndex = 30; this.cbColorBottom.SelectedIndexChanged += new System.EventHandler(this.cbColor_SelectedIndexChanged); // // tbWidthLeft // this.tbWidthLeft.Location = new System.Drawing.Point(334, 72); this.tbWidthLeft.Name = "tbWidthLeft"; this.tbWidthLeft.Size = new System.Drawing.Size(64, 20); this.tbWidthLeft.TabIndex = 12; this.tbWidthLeft.TextChanged += new System.EventHandler(this.tbWidth_Changed); // // tbWidthRight // this.tbWidthRight.Location = new System.Drawing.Point(334, 104); this.tbWidthRight.Name = "tbWidthRight"; this.tbWidthRight.Size = new System.Drawing.Size(64, 20); this.tbWidthRight.TabIndex = 19; this.tbWidthRight.TextChanged += new System.EventHandler(this.tbWidth_Changed); // // tbWidthTop // this.tbWidthTop.Location = new System.Drawing.Point(334, 136); this.tbWidthTop.Name = "tbWidthTop"; this.tbWidthTop.Size = new System.Drawing.Size(64, 20); this.tbWidthTop.TabIndex = 26; this.tbWidthTop.TextChanged += new System.EventHandler(this.tbWidth_Changed); // // tbWidthBottom // this.tbWidthBottom.Location = new System.Drawing.Point(334, 168); this.tbWidthBottom.Name = "tbWidthBottom"; this.tbWidthBottom.Size = new System.Drawing.Size(64, 20); this.tbWidthBottom.TabIndex = 33; this.tbWidthBottom.TextChanged += new System.EventHandler(this.tbWidth_Changed); // // tbWidthDefault // this.tbWidthDefault.Location = new System.Drawing.Point(334, 40); this.tbWidthDefault.Name = "tbWidthDefault"; this.tbWidthDefault.Size = new System.Drawing.Size(64, 20); this.tbWidthDefault.TabIndex = 5; this.tbWidthDefault.TextChanged += new System.EventHandler(this.tbWidthDefault_TextChanged); // // bColorDefault // this.bColorDefault.Location = new System.Drawing.Point(306, 40); this.bColorDefault.Name = "bColorDefault"; this.bColorDefault.Size = new System.Drawing.Size(24, 21); this.bColorDefault.TabIndex = 4; this.bColorDefault.Text = "..."; this.bColorDefault.Click += new System.EventHandler(this.bColor_Click); // // cbColorDefault // this.cbColorDefault.Location = new System.Drawing.Point(176, 40); this.cbColorDefault.Name = "cbColorDefault"; this.cbColorDefault.Size = new System.Drawing.Size(96, 21); this.cbColorDefault.TabIndex = 2; this.cbColorDefault.SelectedIndexChanged += new System.EventHandler(this.cbColorDefault_SelectedIndexChanged); // // cbStyleDefault // this.cbStyleDefault.Items.AddRange(new object[] { "None", "Dotted", "Dashed", "Solid", "Double", "Groove", "Ridge", "Inset", "WindowInset", "Outset"}); this.cbStyleDefault.Location = new System.Drawing.Point(56, 40); this.cbStyleDefault.Name = "cbStyleDefault"; this.cbStyleDefault.Size = new System.Drawing.Size(88, 21); this.cbStyleDefault.TabIndex = 0; this.cbStyleDefault.SelectedIndexChanged += new System.EventHandler(this.cbStyleDefault_SelectedIndexChanged); // // label8 // this.label8.Location = new System.Drawing.Point(16, 42); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(40, 16); this.label8.TabIndex = 36; this.label8.Text = "Default"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // bSD // this.bSD.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bSD.Location = new System.Drawing.Point(148, 40); this.bSD.Name = "bSD"; this.bSD.Size = new System.Drawing.Size(24, 21); this.bSD.TabIndex = 1; this.bSD.Tag = "sd"; this.bSD.Text = "fx"; this.bSD.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bSD.Click += new System.EventHandler(this.bExpr_Click); // // bSL // this.bSL.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bSL.Location = new System.Drawing.Point(148, 72); this.bSL.Name = "bSL"; this.bSL.Size = new System.Drawing.Size(24, 21); this.bSL.TabIndex = 8; this.bSL.Tag = "sl"; this.bSL.Text = "fx"; this.bSL.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bSL.Click += new System.EventHandler(this.bExpr_Click); // // bSR // this.bSR.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bSR.Location = new System.Drawing.Point(148, 104); this.bSR.Name = "bSR"; this.bSR.Size = new System.Drawing.Size(24, 21); this.bSR.TabIndex = 15; this.bSR.Tag = "sr"; this.bSR.Text = "fx"; this.bSR.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bSR.Click += new System.EventHandler(this.bExpr_Click); // // bST // this.bST.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bST.Location = new System.Drawing.Point(148, 136); this.bST.Name = "bST"; this.bST.Size = new System.Drawing.Size(24, 21); this.bST.TabIndex = 22; this.bST.Tag = "st"; this.bST.Text = "fx"; this.bST.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bST.Click += new System.EventHandler(this.bExpr_Click); // // bSB // this.bSB.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bSB.Location = new System.Drawing.Point(148, 168); this.bSB.Name = "bSB"; this.bSB.Size = new System.Drawing.Size(24, 21); this.bSB.TabIndex = 29; this.bSB.Tag = "sb"; this.bSB.Text = "fx"; this.bSB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bSB.Click += new System.EventHandler(this.bExpr_Click); // // bCD // this.bCD.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bCD.Location = new System.Drawing.Point(276, 40); this.bCD.Name = "bCD"; this.bCD.Size = new System.Drawing.Size(24, 21); this.bCD.TabIndex = 3; this.bCD.Tag = "cd"; this.bCD.Text = "fx"; this.bCD.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCD.Click += new System.EventHandler(this.bExpr_Click); // // bCT // this.bCT.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bCT.Location = new System.Drawing.Point(276, 136); this.bCT.Name = "bCT"; this.bCT.Size = new System.Drawing.Size(24, 21); this.bCT.TabIndex = 24; this.bCT.Tag = "ct"; this.bCT.Text = "fx"; this.bCT.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCT.Click += new System.EventHandler(this.bExpr_Click); // // bCB // this.bCB.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bCB.Location = new System.Drawing.Point(276, 168); this.bCB.Name = "bCB"; this.bCB.Size = new System.Drawing.Size(24, 21); this.bCB.TabIndex = 31; this.bCB.Tag = "cb"; this.bCB.Text = "fx"; this.bCB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCB.Click += new System.EventHandler(this.bExpr_Click); // // bWB // this.bWB.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWB.Location = new System.Drawing.Point(403, 168); this.bWB.Name = "bWB"; this.bWB.Size = new System.Drawing.Size(24, 21); this.bWB.TabIndex = 34; this.bWB.Tag = "wb"; this.bWB.Text = "fx"; this.bWB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWB.Click += new System.EventHandler(this.bExpr_Click); // // bWT // this.bWT.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWT.Location = new System.Drawing.Point(403, 136); this.bWT.Name = "bWT"; this.bWT.Size = new System.Drawing.Size(24, 21); this.bWT.TabIndex = 27; this.bWT.Tag = "wt"; this.bWT.Text = "fx"; this.bWT.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWT.Click += new System.EventHandler(this.bExpr_Click); // // bWR // this.bWR.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWR.Location = new System.Drawing.Point(403, 104); this.bWR.Name = "bWR"; this.bWR.Size = new System.Drawing.Size(24, 21); this.bWR.TabIndex = 20; this.bWR.Tag = "wr"; this.bWR.Text = "fx"; this.bWR.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWR.Click += new System.EventHandler(this.bExpr_Click); // // bCR // this.bCR.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bCR.Location = new System.Drawing.Point(276, 104); this.bCR.Name = "bCR"; this.bCR.Size = new System.Drawing.Size(24, 21); this.bCR.TabIndex = 17; this.bCR.Tag = "cr"; this.bCR.Text = "fx"; this.bCR.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCR.Click += new System.EventHandler(this.bExpr_Click); // // bWL // this.bWL.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWL.Location = new System.Drawing.Point(403, 72); this.bWL.Name = "bWL"; this.bWL.Size = new System.Drawing.Size(24, 21); this.bWL.TabIndex = 13; this.bWL.Tag = "wl"; this.bWL.Text = "fx"; this.bWL.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWL.Click += new System.EventHandler(this.bExpr_Click); // // bWD // this.bWD.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWD.Location = new System.Drawing.Point(403, 40); this.bWD.Name = "bWD"; this.bWD.Size = new System.Drawing.Size(24, 21); this.bWD.TabIndex = 6; this.bWD.Tag = "wd"; this.bWD.Text = "fx"; this.bWD.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWD.Click += new System.EventHandler(this.bExpr_Click); // // bCL // this.bCL.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bCL.Location = new System.Drawing.Point(276, 72); this.bCL.Name = "bCL"; this.bCL.Size = new System.Drawing.Size(24, 21); this.bCL.TabIndex = 10; this.bCL.Tag = "cl"; this.bCL.Text = "fx"; this.bCL.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCL.Click += new System.EventHandler(this.bExpr_Click); // // StyleBorderCtl // this.Controls.Add(this.bCL); this.Controls.Add(this.bWD); this.Controls.Add(this.bWL); this.Controls.Add(this.bCR); this.Controls.Add(this.bWR); this.Controls.Add(this.bWT); this.Controls.Add(this.bWB); this.Controls.Add(this.bCB); this.Controls.Add(this.bCT); this.Controls.Add(this.bCD); this.Controls.Add(this.bSB); this.Controls.Add(this.bST); this.Controls.Add(this.bSR); this.Controls.Add(this.bSL); this.Controls.Add(this.bSD); this.Controls.Add(this.tbWidthDefault); this.Controls.Add(this.bColorDefault); this.Controls.Add(this.cbColorDefault); this.Controls.Add(this.cbStyleDefault); this.Controls.Add(this.label8); this.Controls.Add(this.tbWidthBottom); this.Controls.Add(this.tbWidthTop); this.Controls.Add(this.tbWidthRight); this.Controls.Add(this.tbWidthLeft); this.Controls.Add(this.bColorBottom); this.Controls.Add(this.cbColorBottom); this.Controls.Add(this.bColorTop); this.Controls.Add(this.cbColorTop); this.Controls.Add(this.bColorRight); this.Controls.Add(this.cbColorRight); this.Controls.Add(this.bColorLeft); this.Controls.Add(this.cbColorLeft); this.Controls.Add(this.cbStyleRight); this.Controls.Add(this.cbStyleTop); this.Controls.Add(this.cbStyleBottom); this.Controls.Add(this.cbStyleLeft); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label2); this.Controls.Add(this.lRight); this.Controls.Add(this.lTop); this.Controls.Add(this.lBottom); this.Controls.Add(this.lLeft); this.Name = "StyleBorderCtl"; this.Size = new System.Drawing.Size(472, 312); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { string name=""; try { if (fWidthDefault && !this.tbWidthDefault.Text.StartsWith("=")) { name = "Default Width"; DesignerUtility.ValidateSize(this.tbWidthDefault.Text, true, false); } if (fWidthLeft && !this.tbWidthLeft.Text.StartsWith("=")) { name = "Left Width"; DesignerUtility.ValidateSize(this.tbWidthLeft.Text, true, false); } if (fWidthTop && !this.tbWidthTop.Text.StartsWith("=")) { name = "Top Width"; DesignerUtility.ValidateSize(this.tbWidthTop.Text, true, false); } if (fWidthBottom && !this.tbWidthBottom.Text.StartsWith("=")) { name = "Bottom Width"; DesignerUtility.ValidateSize(this.tbWidthBottom.Text, true, false); } if (fWidthRight && !this.tbWidthRight.Text.StartsWith("=")) { name = "Right Width"; DesignerUtility.ValidateSize(this.tbWidthRight.Text, true, false); } } catch (Exception ex) { MessageBox.Show(ex.Message, name + " Size Invalid"); return false; } return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); fStyleDefault = fStyleLeft = fStyleRight = fStyleTop = fStyleBottom = fColorDefault = fColorLeft = fColorRight = fColorTop = fColorBottom = fWidthDefault = fWidthLeft = fWidthRight = fWidthTop = fWidthBottom= false; } private void ApplyChanges(XmlNode xNode) { if (_names != null) { xNode = _Draw.FindCreateNextInHierarchy(xNode, _names); } bool bLine = xNode.Name == "Line"; XmlNode sNode = _Draw.GetCreateNamedChildNode(xNode, "Style"); // Handle BorderStyle XmlNode bsNode = _Draw.SetElement(sNode, "BorderStyle", null); if (fStyleDefault) _Draw.SetElement(bsNode, "Default", cbStyleDefault.Text); if (fStyleLeft && !bLine) _Draw.SetElement(bsNode, "Left", cbStyleLeft.Text); if (fStyleRight && !bLine) _Draw.SetElement(bsNode, "Right", cbStyleRight.Text); if (fStyleTop && !bLine) _Draw.SetElement(bsNode, "Top", cbStyleTop.Text); if (fStyleBottom && !bLine) _Draw.SetElement(bsNode, "Bottom", cbStyleBottom.Text); // Handle BorderColor XmlNode csNode = _Draw.SetElement(sNode, "BorderColor", null); if (fColorDefault) _Draw.SetElement(csNode, "Default", cbColorDefault.Text); if (fColorLeft && !bLine) _Draw.SetElement(csNode, "Left", cbColorLeft.Text); if (fColorRight && !bLine) _Draw.SetElement(csNode, "Right", cbColorRight.Text); if (fColorTop && !bLine) _Draw.SetElement(csNode, "Top", cbColorTop.Text); if (fColorBottom && !bLine) _Draw.SetElement(csNode, "Bottom", cbColorBottom.Text); // Handle BorderWidth XmlNode bwNode = _Draw.SetElement(sNode, "BorderWidth", null); if (fWidthDefault) _Draw.SetElement(bwNode, "Default", GetSize(tbWidthDefault.Text)); if (fWidthLeft && !bLine) _Draw.SetElement(bwNode, "Left", GetSize(tbWidthLeft.Text)); if (fWidthRight && !bLine) _Draw.SetElement(bwNode, "Right", GetSize(tbWidthRight.Text)); if (fWidthTop && !bLine) _Draw.SetElement(bwNode, "Top", GetSize(tbWidthTop.Text)); if (fWidthBottom && !bLine) _Draw.SetElement(bwNode, "Bottom", GetSize(tbWidthBottom.Text)); } private string GetSize(string sz) { if (sz.Trim().StartsWith("=")) // Don't mess with expressions return sz; float size = DesignXmlDraw.GetSize(sz); if (size <= 0) { size = DesignXmlDraw.GetSize(sz+"pt"); // Try assuming pt if (size <= 0) // still no good size = 10; // just set default value } string rs = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.#}pt", size); return rs; } private void bColor_Click(object sender, System.EventArgs e) { using (ColorDialog cd = new ColorDialog()) { cd.AnyColor = true; cd.FullOpen = true; cd.CustomColors = RdlDesignerForm.CustomColors; if (cd.ShowDialog() != DialogResult.OK) return; RdlDesignerForm.CustomColors = cd.CustomColors; if (sender == this.bColorDefault) { cbColorDefault.Text = ColorTranslator.ToHtml(cd.Color); cbColorLeft.Text = ColorTranslator.ToHtml(cd.Color); cbColorRight.Text = ColorTranslator.ToHtml(cd.Color); cbColorTop.Text = ColorTranslator.ToHtml(cd.Color); cbColorBottom.Text = ColorTranslator.ToHtml(cd.Color); } else if (sender == this.bColorLeft) cbColorLeft.Text = ColorTranslator.ToHtml(cd.Color); else if (sender == this.bColorRight) cbColorRight.Text = ColorTranslator.ToHtml(cd.Color); else if (sender == this.bColorTop) cbColorTop.Text = ColorTranslator.ToHtml(cd.Color); else if (sender == this.bColorBottom) cbColorBottom.Text = ColorTranslator.ToHtml(cd.Color); } return; } private void cbStyleDefault_SelectedIndexChanged(object sender, System.EventArgs e) { cbStyleLeft.Text = cbStyleRight.Text = cbStyleTop.Text = cbStyleBottom.Text = cbStyleDefault.Text; fStyleDefault = fStyleLeft = fStyleRight = fStyleTop = fStyleBottom = true; } private void cbColorDefault_SelectedIndexChanged(object sender, System.EventArgs e) { cbColorLeft.Text = cbColorRight.Text = cbColorTop.Text = cbColorBottom.Text = cbColorDefault.Text; fColorDefault = fColorLeft = fColorRight = fColorTop = fColorBottom = true; } private void tbWidthDefault_TextChanged(object sender, System.EventArgs e) { tbWidthLeft.Text = tbWidthRight.Text = tbWidthTop.Text = tbWidthBottom.Text = tbWidthDefault.Text; fWidthDefault = fWidthLeft = fWidthRight = fWidthTop = fWidthBottom = true; } private void cbStyle_SelectedIndexChanged(object sender, System.EventArgs e) { if (sender == cbStyleLeft) fStyleLeft = true; else if (sender == cbStyleRight) fStyleRight = true; else if (sender == cbStyleTop) fStyleTop = true; else if (sender == cbStyleBottom) fStyleBottom = true; } private void cbColor_SelectedIndexChanged(object sender, System.EventArgs e) { if (sender == cbColorLeft) fColorLeft = true; else if (sender == cbColorRight) fColorRight = true; else if (sender == cbColorTop) fColorTop = true; else if (sender == cbColorBottom) fColorBottom = true; } private void tbWidth_Changed(object sender, System.EventArgs e) { if (sender == tbWidthLeft) fWidthLeft = true; else if (sender == tbWidthRight) fWidthRight = true; else if (sender == tbWidthTop) fWidthTop = true; else if (sender == tbWidthBottom) fWidthBottom = true; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; bool bColor=false; switch (b.Tag as string) { case "sd": c = cbStyleDefault; break; case "cd": c = cbColorDefault; bColor = true; break; case "wd": c = tbWidthDefault; break; case "sl": c = cbStyleLeft; break; case "cl": c = cbColorLeft; bColor = true; break; case "wl": c = tbWidthLeft; break; case "sr": c = cbStyleRight; break; case "cr": c = cbColorRight; bColor = true; break; case "wr": c = tbWidthRight; break; case "st": c = cbStyleTop; break; case "ct": c = cbColorTop; bColor = true; break; case "wt": c = tbWidthTop; break; case "sb": c = cbStyleBottom; break; case "cb": c = cbColorBottom; bColor = true; break; case "wb": c = tbWidthBottom; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor)) { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } return; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using Common; using Fairweather.Service; namespace DTA { public class Printing_Helper : Ini_Helper { public Printing_Helper(Ini_File ini, Company_Number number, Printing_Scenario scenario) : base(ini, number) { this.company = number; this.Scenario = scenario; } public Printing_Scenario Scenario { get; set; } readonly Company_Number company; public Company_Number Company { get { return company; } } public string Get_Filename() { var dir = Data.Get_Printing_Directory(company, Scenario).Value; var prefix = Data.Get_Printing_Prefix(); var ext = Data.Printing_Extension; var file = Data.Get_Next_Filename(dir, prefix, ext); return file; } public object OPOS_Printer_Id { get { return "" + OPOS_Paper_Cutting_Percentage + OPOS_High_Quality_Letters + OPOS_Keep_Printer_Open + OPOS_Image_DPI + OPOS_Logical_Name; } } public int OPOS_Paper_Cutting_Percentage { get { return Int(DTA_Fields.POS_printing_opos_cut_paper_perc); } } public bool OPOS_High_Quality_Letters { get { return True(DTA_Fields.POS_printing_opos_hiq_letters); } } public bool OPOS_Keep_Printer_Open { get { return True(DTA_Fields.POS_printing_opos_keep_open); } } public int OPOS_Image_DPI { get { return Int(DTA_Fields.POS_printing_opos_image_dpi); } } public string OPOS_Logical_Name { get { return String(DTA_Fields.POS_printing_opos_logical_name); } } public bool Notepad_Print_Tags { get { return True(DTA_Fields.POS_printing_txt_print_tags); } } public bool Notepad_Open_File { get { return True(DTA_Fields.POS_printing_txt_open_file); } } public bool Notepad_Open_Dir { get { return True(DTA_Fields.POS_printing_txt_open_dir); } } public int GDI_DPI { get { return Int(DTA_Fields.POS_printing_gdi_dpi); } } public bool GDI_Show_Preview { get { return True(DTA_Fields.POS_printing_gdi_preview); } } public bool GDI_Show_Print_Dialog { get { return True(DTA_Fields.POS_printing_gdi_print_dialog); } } public bool GDI_Show_Page_Setup { get { return True(DTA_Fields.POS_printing_gdi_page_setup); } } public string GDI_Printer_To_Use { get { var preferred = GDI_Preferred_Printer; bool _; var ret = H.Printer_Or_Default(preferred, out _); return ret; } } public bool GDI_Preferred_Printer_Available { get { var preferred = GDI_Preferred_Printer; // No preferred printer if (preferred == null) return true; bool available; H.Printer_Or_Default(preferred, out available); return available; } } public string GDI_Preferred_Printer { get { var str = String(DTA_Fields.POS_printing_gdi_printer); if (str.Safe_Equals(Ini_Main.DEFAULT, true)) return null; return str; } } public Pos_GDI_Font GDI_Font { get { var size = Int(DTA_Fields.POS_printing_gdi_font_size); var ret = Get_GDI_Font(size, false); return ret; } } public Pos_GDI_Font Get_GDI_FontR(int? size, bool bold) { size = size ?? 0; size += Int(DTA_Fields.POS_printing_gdi_font_size); return Get_GDI_Font(size, bold); } public Pos_GDI_Font Get_GDI_Font(int? size, bool bold) { size = size ?? Int(DTA_Fields.POS_printing_gdi_font_size); var face = Font(DTA_Fields.POS_printing_gdi_font_face); var func = ((Func<Font>)(() => new Font(face, size.Value, bold ? FontStyle.Bold : FontStyle.Regular))); var ret = new Pos_GDI_Font(func); return ret; } public int GDI_Page_Width_MM { get { return Int(DTA_Fields.POS_printing_gdi_page_width); } } public Printing_Provider Provider { get { var dta = String(DTA_Fields.POS_printing_provider); var dict = new Dictionary<string, Printing_Provider>{ {Ini_Main.TEXT, Printing_Provider.Notepad}, {Ini_Main.WINDOWS, Printing_Provider.Windows}, {Ini_Main.BIXOLON, Printing_Provider.Bixolon}, {Ini_Main.OPOS, Printing_Provider.Pos_For_Net}, }; var ret = dict[dta]; return ret; } } public int Copies { get { if (this.Scenario == Printing_Scenario.Preview) return 1; var str = new Dictionary<Printing_Scenario, Ini_Field>{ {Printing_Scenario.Sales_Receipt, DTA_Fields.POS_printout_count_sale}, {Printing_Scenario.Future_Cheque, DTA_Fields.POS_printout_count_receipt}, {Printing_Scenario.Receipt_On_Account, DTA_Fields.POS_printout_count_receipt}, {Printing_Scenario.End_Of_Shift, DTA_Fields.POS_printout_count_eos}, }[this.Scenario]; return Int(str); } } Receipt_Layout_SV Get_Default_Layout() { Sage_Logic sdr; Sage_Logic.Get(ini, Company, out sdr).tiff(); var name = sdr.Get_Company_Data().Name; var ret = new Receipt_Layout_SV(name, "", "", "logo.bmp", true, false); return ret; } public bool Print_Image { get { return Layout.Use_Image && H.Validate_Image(Layout.Image); } } public Receipt_Layout_SV Layout { set { S.Serialize_To_File(Receipt_Layout_File, false, value).tiff(); } get { Receipt_Layout_SV ret; if (!S.Deserialize_From_File(Receipt_Layout_File, false, out ret)) { Layout = Get_Default_Layout(); ret = Layout; } return ret; } } // Manual serialization /// //public Printing_Header Header { // set { // using (var sw = new StreamWriter(Current_File, false)) { // sw.WriteLine(value.Image); // sw.WriteLine(value.Use_Image ? "yes" : "no"); // sw.WriteLine(value.Name); // sw.WriteLine(value.Text); // } // } // get { // if (!File.Exists(Current_File)) // return Get_Default_Header(); // using (var sw = new StreamReader(Current_File)) { // var img = sw.ReadLine(); // var use_image = sw.ReadLine() != "no"; // var title = sw.ReadLine(); // var text = sw.ReadToEnd(); // return new Printing_Header(title, text, img, use_image); // } // } //} string Receipt_Layout_File { get { return Data.Get_Header_Filename(Company); } } string Receipt_Layout_Backup { get { return Receipt_Layout_File + ".bak"; } } public void Backup_Layout() { if (File.Exists(Receipt_Layout_File)) File.Copy(Receipt_Layout_File, Receipt_Layout_Backup, true); } public void Restore_Layout() { File.Delete(Receipt_Layout_File); if (File.Exists(Receipt_Layout_Backup)) File.Move(Receipt_Layout_Backup, Receipt_Layout_File); } public void Remove_Layout_Backup() { File.Delete(Receipt_Layout_Backup); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; namespace Microsoft.Azure.Management.Resources { public static partial class ResourceOperationsExtensions { /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static ResourceExistsResult CheckExistence(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CheckExistenceAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static Task<ResourceExistsResult> CheckExistenceAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.CheckExistenceAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceCreateOrUpdateResult CreateOrUpdate(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CreateOrUpdateAsync(resourceGroupName, identity, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, identity, parameters, CancellationToken.None); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).DeleteAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.DeleteAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceGetResult Get(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).GetAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceGetResult> GetAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.GetAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult List(this IResourceOperations operations, ResourceListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListAsync(this IResourceOperations operations, ResourceListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult ListNext(this IResourceOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListNextAsync(this IResourceOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Move resources within or across subscriptions. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse MoveResources(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).MoveResourcesAsync(sourceResourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Move resources within or across subscriptions. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='sourceResourceGroupName'> /// Required. Source resource group name. /// </param> /// <param name='parameters'> /// Required. move resources' parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> MoveResourcesAsync(this IResourceOperations operations, string sourceResourceGroupName, ResourcesMoveInfo parameters) { return operations.MoveResourcesAsync(sourceResourceGroupName, parameters, CancellationToken.None); } } }
using System; using System.Runtime; using System.Collections.Generic; using System.Threading; namespace System.ServiceModel.Channels { internal class SynchronizedPool<T> where T : class { private struct Entry { public int threadID; public T value; } private struct PendingEntry { public int returnCount; public int threadID; } private static class SynchronizedPoolHelper { public static readonly int ProcessorCount = SynchronizedPool<T>.SynchronizedPoolHelper.GetProcessorCount(); private static int GetProcessorCount() { return Environment.ProcessorCount; } } private class GlobalPool { private Stack<T> items; private int maxCount; public int MaxCount { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.maxCount; } set { lock (this.ThisLock) { while (this.items.Count > value) { this.items.Pop(); } this.maxCount = value; } } } private object ThisLock { get { return this; } } public GlobalPool(int maxCount) { this.items = new Stack<T>(); this.maxCount = maxCount; } public void DecrementMaxCount() { lock (this.ThisLock) { if (this.items.Count == this.maxCount) { this.items.Pop(); } this.maxCount--; } } public T Take() { if (this.items.Count > 0) { lock (this.ThisLock) { if (this.items.Count > 0) { return this.items.Pop(); } } } return default(T); } public bool Return(T value) { if (this.items.Count < this.MaxCount) { lock (this.ThisLock) { if (this.items.Count < this.MaxCount) { this.items.Push(value); return true; } } return false; } return false; } public void Clear() { lock (this.ThisLock) { this.items.Clear(); } } } private SynchronizedPool<T>.Entry[] entries; private SynchronizedPool<T>.GlobalPool globalPool; private int maxCount; private SynchronizedPool<T>.PendingEntry[] pending; private int promotionFailures; private const int maxPendingEntries = 128; private const int maxPromotionFailures = 64; private const int maxReturnsBeforePromotion = 64; private const int maxThreadItemsPerProcessor = 16; private object ThisLock { get { return this; } } public SynchronizedPool(int maxCount) { int num = maxCount; int num2 = 16 + SynchronizedPool<T>.SynchronizedPoolHelper.ProcessorCount; if (num > num2) { num = num2; } this.maxCount = maxCount; this.entries = new SynchronizedPool<T>.Entry[num]; this.pending = new SynchronizedPool<T>.PendingEntry[4]; this.globalPool = new SynchronizedPool<T>.GlobalPool(maxCount); } public void Clear() { SynchronizedPool<T>.Entry[] array = this.entries; for (int i = 0; i < array.Length; i++) { array[i].value = default(T); } this.globalPool.Clear(); } private void HandlePromotionFailure(int thisThreadID) { int num = this.promotionFailures + 1; if (num >= 64) { lock (this.ThisLock) { this.entries = new SynchronizedPool<T>.Entry[this.entries.Length]; this.globalPool.MaxCount = this.maxCount; } this.PromoteThread(thisThreadID); return; } this.promotionFailures = num; } private bool PromoteThread(int thisThreadID) { lock (this.ThisLock) { for (int i = 0; i < this.entries.Length; i++) { int threadID = this.entries[i].threadID; if (threadID == thisThreadID) { bool result = true; return result; } if (threadID == 0) { this.globalPool.DecrementMaxCount(); this.entries[i].threadID = thisThreadID; bool result = true; return result; } } } return false; } private void RecordReturnToGlobalPool(int thisThreadID) { SynchronizedPool<T>.PendingEntry[] array = this.pending; int i = 0; while (i < array.Length) { int threadID = array[i].threadID; if (threadID == thisThreadID) { int num = array[i].returnCount + 1; if (num < 64) { array[i].returnCount = num; return; } array[i].returnCount = 0; if (!this.PromoteThread(thisThreadID)) { this.HandlePromotionFailure(thisThreadID); return; } break; } else { if (threadID == 0) { return; } i++; } } } private void RecordTakeFromGlobalPool(int thisThreadID) { SynchronizedPool<T>.PendingEntry[] array = this.pending; for (int i = 0; i < array.Length; i++) { int threadID = array[i].threadID; if (threadID == thisThreadID) { return; } if (threadID == 0) { lock (array) { if (array[i].threadID == 0) { array[i].threadID = thisThreadID; return; } } } } if (array.Length >= 128) { this.pending = new SynchronizedPool<T>.PendingEntry[array.Length]; return; } SynchronizedPool<T>.PendingEntry[] destinationArray = new SynchronizedPool<T>.PendingEntry[array.Length * 2]; Array.Copy(array, destinationArray, array.Length); this.pending = destinationArray; } public bool Return(T value) { int managedThreadId = Thread.CurrentThread.ManagedThreadId; return managedThreadId != 0 && (this.ReturnToPerThreadPool(managedThreadId, value) || this.ReturnToGlobalPool(managedThreadId, value)); } private bool ReturnToPerThreadPool(int thisThreadID, T value) { SynchronizedPool<T>.Entry[] array = this.entries; int i = 0; while (i < array.Length) { int threadID = array[i].threadID; if (threadID == thisThreadID) { if (array[i].value == null) { array[i].value = value; return true; } return false; } else { if (threadID == 0) { break; } i++; } } return false; } private bool ReturnToGlobalPool(int thisThreadID, T value) { this.RecordReturnToGlobalPool(thisThreadID); return this.globalPool.Return(value); } public T Take() { int managedThreadId = Thread.CurrentThread.ManagedThreadId; if (managedThreadId == 0) { return default(T); } T t = this.TakeFromPerThreadPool(managedThreadId); if (t != null) { return t; } return this.TakeFromGlobalPool(managedThreadId); } private T TakeFromPerThreadPool(int thisThreadID) { SynchronizedPool<T>.Entry[] array = this.entries; int i = 0; while (i < array.Length) { int threadID = array[i].threadID; if (threadID == thisThreadID) { T value = array[i].value; if (value != null) { array[i].value = default(T); return value; } return default(T); } else { if (threadID == 0) { break; } i++; } } return default(T); } private T TakeFromGlobalPool(int thisThreadID) { this.RecordTakeFromGlobalPool(thisThreadID); return this.globalPool.Take(); } } internal abstract class InternalBufferManager { private class PooledBufferManager : InternalBufferManager { private abstract class BufferPool { private class SynchronizedBufferPool : InternalBufferManager.PooledBufferManager.BufferPool { private SynchronizedPool<byte[]> innerPool; internal SynchronizedBufferPool(int bufferSize, int limit) : base(bufferSize, limit) { this.innerPool = new SynchronizedPool<byte[]>(limit); } internal override void OnClear() { this.innerPool.Clear(); } internal override byte[] Take() { return this.innerPool.Take(); } internal override bool Return(byte[] buffer) { return this.innerPool.Return(buffer); } } private class LargeBufferPool : InternalBufferManager.PooledBufferManager.BufferPool { private Stack<byte[]> items; private object ThisLock { get { return this.items; } } internal LargeBufferPool(int bufferSize, int limit) : base(bufferSize, limit) { this.items = new Stack<byte[]>(limit); } internal override void OnClear() { lock (this.ThisLock) { this.items.Clear(); } } internal override byte[] Take() { lock (this.ThisLock) { if (this.items.Count > 0) { return this.items.Pop(); } } return null; } internal override bool Return(byte[] buffer) { lock (this.ThisLock) { if (this.items.Count < base.Limit) { this.items.Push(buffer); return true; } } return false; } } private int bufferSize; private int count; private int limit; private int misses; private int peak; public int BufferSize { get { return this.bufferSize; } } public int Limit { get { return this.limit; } } public int Misses { get { return this.misses; } set { this.misses = value; } } public int Peak { get { return this.peak; } } public BufferPool(int bufferSize, int limit) { this.bufferSize = bufferSize; this.limit = limit; } public void Clear() { this.OnClear(); this.count = 0; } public void DecrementCount() { int num = this.count - 1; if (num >= 0) { this.count = num; } } public void IncrementCount() { int num = this.count + 1; if (num <= this.limit) { this.count = num; if (num > this.peak) { this.peak = num; } } } internal abstract byte[] Take(); internal abstract bool Return(byte[] buffer); internal abstract void OnClear(); internal static InternalBufferManager.PooledBufferManager.BufferPool CreatePool(int bufferSize, int limit) { if (bufferSize < 85000) { return new InternalBufferManager.PooledBufferManager.BufferPool.SynchronizedBufferPool(bufferSize, limit); } return new InternalBufferManager.PooledBufferManager.BufferPool.LargeBufferPool(bufferSize, limit); } } private const int minBufferSize = 128; private const int maxMissesBeforeTuning = 8; private const int initialBufferCount = 1; private readonly object tuningLock; private int[] bufferSizes; private InternalBufferManager.PooledBufferManager.BufferPool[] bufferPools; private long memoryLimit; private long remainingMemory; private bool areQuotasBeingTuned; private int totalMisses; public PooledBufferManager(long maxMemoryToPool, int maxBufferSize) { this.tuningLock = new object(); this.memoryLimit = maxMemoryToPool; this.remainingMemory = maxMemoryToPool; List<InternalBufferManager.PooledBufferManager.BufferPool> list = new List<InternalBufferManager.PooledBufferManager.BufferPool>(); int num = 128; while (true) { long num2 = this.remainingMemory / (long)num; int num3 = (num2 > 2147483647L) ? 2147483647 : ((int)num2); if (num3 > 1) { num3 = 1; } list.Add(InternalBufferManager.PooledBufferManager.BufferPool.CreatePool(num, num3)); this.remainingMemory -= (long)num3 * (long)num; if (num >= maxBufferSize) { break; } long num4 = (long)num * 2L; if (num4 > (long)maxBufferSize) { num = maxBufferSize; } else { num = (int)num4; } } this.bufferPools = list.ToArray(); this.bufferSizes = new int[this.bufferPools.Length]; for (int i = 0; i < this.bufferPools.Length; i++) { this.bufferSizes[i] = this.bufferPools[i].BufferSize; } } public override void Clear() { for (int i = 0; i < this.bufferPools.Length; i++) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.bufferPools[i]; bufferPool.Clear(); } } private void ChangeQuota(ref InternalBufferManager.PooledBufferManager.BufferPool bufferPool, int delta) { if (TraceCore.BufferPoolChangeQuotaIsEnabled(Fx.Trace)) { TraceCore.BufferPoolChangeQuota(Fx.Trace, bufferPool.BufferSize, delta); } InternalBufferManager.PooledBufferManager.BufferPool bufferPool2 = bufferPool; int num = bufferPool2.Limit + delta; InternalBufferManager.PooledBufferManager.BufferPool bufferPool3 = InternalBufferManager.PooledBufferManager.BufferPool.CreatePool(bufferPool2.BufferSize, num); for (int i = 0; i < num; i++) { byte[] array = bufferPool2.Take(); if (array == null) { break; } bufferPool3.Return(array); bufferPool3.IncrementCount(); } this.remainingMemory -= (long)(bufferPool2.BufferSize * delta); bufferPool = bufferPool3; } private void DecreaseQuota(ref InternalBufferManager.PooledBufferManager.BufferPool bufferPool) { this.ChangeQuota(ref bufferPool, -1); } private int FindMostExcessivePool() { long num = 0L; int result = -1; for (int i = 0; i < this.bufferPools.Length; i++) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.bufferPools[i]; if (bufferPool.Peak < bufferPool.Limit) { long num2 = (long)(bufferPool.Limit - bufferPool.Peak) * (long)bufferPool.BufferSize; if (num2 > num) { result = i; num = num2; } } } return result; } private int FindMostStarvedPool() { long num = 0L; int result = -1; for (int i = 0; i < this.bufferPools.Length; i++) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.bufferPools[i]; if (bufferPool.Peak == bufferPool.Limit) { long num2 = (long)bufferPool.Misses * (long)bufferPool.BufferSize; if (num2 > num) { result = i; num = num2; } } } return result; } private InternalBufferManager.PooledBufferManager.BufferPool FindPool(int desiredBufferSize) { for (int i = 0; i < this.bufferSizes.Length; i++) { if (desiredBufferSize <= this.bufferSizes[i]) { return this.bufferPools[i]; } } return null; } private void IncreaseQuota(ref InternalBufferManager.PooledBufferManager.BufferPool bufferPool) { this.ChangeQuota(ref bufferPool, 1); } public override void ReturnBuffer(byte[] buffer) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.FindPool(buffer.Length); if (bufferPool != null) { if (buffer.Length != bufferPool.BufferSize) { throw Fx.Exception.Argument("buffer", InternalSR.BufferIsNotRightSizeForBufferManager); } if (bufferPool.Return(buffer)) { bufferPool.IncrementCount(); } } } public override byte[] TakeBuffer(int bufferSize) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.FindPool(bufferSize); if (bufferPool == null) { if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace)) { TraceCore.BufferPoolAllocation(Fx.Trace, bufferSize); } return Fx.AllocateByteArray(bufferSize); } byte[] array = bufferPool.Take(); if (array != null) { bufferPool.DecrementCount(); return array; } if (bufferPool.Peak == bufferPool.Limit) { bufferPool.Misses++; if (++this.totalMisses >= 8) { this.TuneQuotas(); } } if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace)) { TraceCore.BufferPoolAllocation(Fx.Trace, bufferPool.BufferSize); } return Fx.AllocateByteArray(bufferPool.BufferSize); } private void TuneQuotas() { if (this.areQuotasBeingTuned) { return; } bool flag = false; try { Monitor.TryEnter(this.tuningLock, ref flag); if (!flag || this.areQuotasBeingTuned) { return; } this.areQuotasBeingTuned = true; } finally { if (flag) { Monitor.Exit(this.tuningLock); } } int num = this.FindMostStarvedPool(); if (num >= 0) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.bufferPools[num]; if (this.remainingMemory < (long)bufferPool.BufferSize) { int num2 = this.FindMostExcessivePool(); if (num2 >= 0) { this.DecreaseQuota(ref this.bufferPools[num2]); } } if (this.remainingMemory >= (long)bufferPool.BufferSize) { this.IncreaseQuota(ref this.bufferPools[num]); } } for (int i = 0; i < this.bufferPools.Length; i++) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool2 = this.bufferPools[i]; bufferPool2.Misses = 0; } this.totalMisses = 0; this.areQuotasBeingTuned = false; } } private class GCBufferManager : InternalBufferManager { private static InternalBufferManager.GCBufferManager value = new InternalBufferManager.GCBufferManager(); public static InternalBufferManager.GCBufferManager Value { get { return InternalBufferManager.GCBufferManager.value; } } private GCBufferManager() { } public override void Clear() { } public override byte[] TakeBuffer(int bufferSize) { return Fx.AllocateByteArray(bufferSize); } public override void ReturnBuffer(byte[] buffer) { } } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] protected InternalBufferManager() { } public abstract byte[] TakeBuffer(int bufferSize); public abstract void ReturnBuffer(byte[] buffer); public abstract void Clear(); public static InternalBufferManager Create(long maxBufferPoolSize, int maxBufferSize) { if (maxBufferPoolSize == 0L) { return InternalBufferManager.GCBufferManager.Value; } return new InternalBufferManager.PooledBufferManager(maxBufferPoolSize, maxBufferSize); } } /// <summary>Many features require the use of buffers, which are expensive to create and destroy. You can use the <see cref="T:System.ServiceModel.Channels.BufferManager" /> class to manage a buffer pool. The pool and its buffers are created when you instantiate this class and destroyed when the buffer pool is reclaimed by garbage collection. Every time you need to use a buffer, you take one from the pool, use it, and return it to the pool when done. This process is much faster than creating and destroying a buffer every time you need to use one.</summary> [__DynamicallyInvokable] public abstract class BufferManager { private class WrappingBufferManager : BufferManager { private InternalBufferManager innerBufferManager; public InternalBufferManager InternalBufferManager { get { return this.innerBufferManager; } } public WrappingBufferManager(InternalBufferManager innerBufferManager) { this.innerBufferManager = innerBufferManager; } public override byte[] TakeBuffer(int bufferSize) { if (bufferSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("bufferSize", bufferSize, SR.GetString("ValueMustBeNonNegative"))); } return this.innerBufferManager.TakeBuffer(bufferSize); } public override void ReturnBuffer(byte[] buffer) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } this.innerBufferManager.ReturnBuffer(buffer); } public override void Clear() { this.innerBufferManager.Clear(); } } private class WrappingInternalBufferManager : InternalBufferManager { private BufferManager innerBufferManager; public WrappingInternalBufferManager(BufferManager innerBufferManager) { this.innerBufferManager = innerBufferManager; } public override void Clear() { this.innerBufferManager.Clear(); } public override void ReturnBuffer(byte[] buffer) { this.innerBufferManager.ReturnBuffer(buffer); } public override byte[] TakeBuffer(int bufferSize) { return this.innerBufferManager.TakeBuffer(bufferSize); } } /// <summary>Gets a buffer of at least the specified size from the pool. </summary> /// <returns>A byte array that is the requested size of the buffer.</returns> /// <param name="bufferSize">The size, in bytes, of the requested buffer.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> cannot be less than zero.</exception> [__DynamicallyInvokable] public abstract byte[] TakeBuffer(int bufferSize); /// <summary>Returns a buffer to the pool.</summary> /// <param name="buffer">A reference to the buffer being returned.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer" /> reference cannot be null.</exception> /// <exception cref="T:System.ArgumentException">Length of <paramref name="buffer" /> does not match the pool's buffer length property.</exception> [__DynamicallyInvokable] public abstract void ReturnBuffer(byte[] buffer); /// <summary>Releases the buffers currently cached in the manager.</summary> [__DynamicallyInvokable] public abstract void Clear(); /// <summary>Creates a new BufferManager with a specified maximum buffer pool size and a maximum size for each individual buffer in the pool.</summary> /// <returns>Returns a <see cref="T:System.ServiceModel.Channels.BufferManager" /> object with the specified parameters.</returns> /// <param name="maxBufferPoolSize">The maximum size of the pool.</param> /// <param name="maxBufferSize">The maximum size of an individual buffer.</param> /// <exception cref="T:System.InsufficientMemoryException">There was insufficient memory to create the requested buffer pool.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="maxBufferPoolSize" /> or <paramref name="maxBufferSize" /> was less than zero.</exception> [__DynamicallyInvokable] public static BufferManager CreateBufferManager(long maxBufferPoolSize, int maxBufferSize) { if (maxBufferPoolSize < 0L) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferPoolSize", maxBufferPoolSize, SR.GetString("ValueMustBeNonNegative"))); } if (maxBufferSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, SR.GetString("ValueMustBeNonNegative"))); } return new BufferManager.WrappingBufferManager(InternalBufferManager.Create(maxBufferPoolSize, maxBufferSize)); } internal static InternalBufferManager GetInternalBufferManager(BufferManager bufferManager) { if (bufferManager is BufferManager.WrappingBufferManager) { return ((BufferManager.WrappingBufferManager)bufferManager).InternalBufferManager; } return new BufferManager.WrappingInternalBufferManager(bufferManager); } /// <summary>Initializes a new instance of the <see cref="T:System.ServiceModel.Channels.BufferManager" /> class. </summary> [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] protected BufferManager() { } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Math.Raw; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP192R1Field { // 2^192 - 2^64 - 1 internal static readonly uint[] P = new uint[]{ 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; internal static readonly uint[] PExt = new uint[]{ 0x00000001, 0x00000000, 0x00000002, 0x00000000, 0x00000001, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; private static readonly uint[] PExtInv = new uint[]{ 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x00000001, 0x00000000, 0x00000002 }; private const uint P5 = 0xFFFFFFFF; private const uint PExt11 = 0xFFFFFFFF; public static void Add(uint[] x, uint[] y, uint[] z) { uint c = Nat192.Add(x, y, z); if (c != 0 || (z[5] == P5 && Nat192.Gte(z, P))) { AddPInvTo(z); } } public static void AddExt(uint[] xx, uint[] yy, uint[] zz) { uint c = Nat.Add(12, xx, yy, zz); if (c != 0 || (zz[11] == PExt11 && Nat.Gte(12, zz, PExt))) { if (Nat.AddTo(PExtInv.Length, PExtInv, zz) != 0) { Nat.IncAt(12, zz, PExtInv.Length); } } } public static void AddOne(uint[] x, uint[] z) { uint c = Nat.Inc(6, x, z); if (c != 0 || (z[5] == P5 && Nat192.Gte(z, P))) { AddPInvTo(z); } } public static uint[] FromBigInteger(BigInteger x) { uint[] z = Nat192.FromBigInteger(x); if (z[5] == P5 && Nat192.Gte(z, P)) { Nat192.SubFrom(P, z); } return z; } public static void Half(uint[] x, uint[] z) { if ((x[0] & 1) == 0) { Nat.ShiftDownBit(6, x, 0, z); } else { uint c = Nat192.Add(x, P, z); Nat.ShiftDownBit(6, z, c); } } public static void Multiply(uint[] x, uint[] y, uint[] z) { uint[] tt = Nat192.CreateExt(); Nat192.Mul(x, y, tt); Reduce(tt, z); } public static void MultiplyAddToExt(uint[] x, uint[] y, uint[] zz) { uint c = Nat192.MulAddTo(x, y, zz); if (c != 0 || (zz[11] == PExt11 && Nat.Gte(12, zz, PExt))) { if (Nat.AddTo(PExtInv.Length, PExtInv, zz) != 0) { Nat.IncAt(12, zz, PExtInv.Length); } } } public static void Negate(uint[] x, uint[] z) { if (Nat192.IsZero(x)) { Nat192.Zero(z); } else { Nat192.Sub(P, x, z); } } public static void Reduce(uint[] xx, uint[] z) { ulong xx06 = xx[6], xx07 = xx[7], xx08 = xx[8]; ulong xx09 = xx[9], xx10 = xx[10], xx11 = xx[11]; ulong t0 = xx06 + xx10; ulong t1 = xx07 + xx11; ulong cc = 0; cc += (ulong)xx[0] + t0; uint z0 = (uint)cc; cc >>= 32; cc += (ulong)xx[1] + t1; z[1] = (uint)cc; cc >>= 32; t0 += xx08; t1 += xx09; cc += (ulong)xx[2] + t0; ulong z2 = (uint)cc; cc >>= 32; cc += (ulong)xx[3] + t1; z[3] = (uint)cc; cc >>= 32; t0 -= xx06; t1 -= xx07; cc += (ulong)xx[4] + t0; z[4] = (uint)cc; cc >>= 32; cc += (ulong)xx[5] + t1; z[5] = (uint)cc; cc >>= 32; z2 += cc; cc += z0; z[0] = (uint)cc; cc >>= 32; if (cc != 0) { cc += z[1]; z[1] = (uint)cc; z2 += cc >> 32; } z[2] = (uint)z2; cc = z2 >> 32; Debug.Assert(cc == 0 || cc == 1); if ((cc != 0 && Nat.IncAt(6, z, 3) != 0) || (z[5] == P5 && Nat192.Gte(z, P))) { AddPInvTo(z); } } public static void Reduce32(uint x, uint[] z) { ulong cc = 0; if (x != 0) { cc += (ulong)z[0] + x; z[0] = (uint)cc; cc >>= 32; if (cc != 0) { cc += (ulong)z[1]; z[1] = (uint)cc; cc >>= 32; } cc += (ulong)z[2] + x; z[2] = (uint)cc; cc >>= 32; Debug.Assert(cc == 0 || cc == 1); } if ((cc != 0 && Nat.IncAt(6, z, 3) != 0) || (z[5] == P5 && Nat192.Gte(z, P))) { AddPInvTo(z); } } public static void Square(uint[] x, uint[] z) { uint[] tt = Nat192.CreateExt(); Nat192.Square(x, tt); Reduce(tt, z); } public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); uint[] tt = Nat192.CreateExt(); Nat192.Square(x, tt); Reduce(tt, z); while (--n > 0) { Nat192.Square(z, tt); Reduce(tt, z); } } public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat192.Sub(x, y, z); if (c != 0) { SubPInvFrom(z); } } public static void SubtractExt(uint[] xx, uint[] yy, uint[] zz) { int c = Nat.Sub(12, xx, yy, zz); if (c != 0) { if (Nat.SubFrom(PExtInv.Length, PExtInv, zz) != 0) { Nat.DecAt(12, zz, PExtInv.Length); } } } public static void Twice(uint[] x, uint[] z) { uint c = Nat.ShiftUpBit(6, x, 0, z); if (c != 0 || (z[5] == P5 && Nat192.Gte(z, P))) { AddPInvTo(z); } } private static void AddPInvTo(uint[] z) { long c = (long)z[0] + 1; z[0] = (uint)c; c >>= 32; if (c != 0) { c += (long)z[1]; z[1] = (uint)c; c >>= 32; } c += (long)z[2] + 1; z[2] = (uint)c; c >>= 32; if (c != 0) { Nat.IncAt(6, z, 3); } } private static void SubPInvFrom(uint[] z) { long c = (long)z[0] - 1; z[0] = (uint)c; c >>= 32; if (c != 0) { c += (long)z[1]; z[1] = (uint)c; c >>= 32; } c += (long)z[2] - 1; z[2] = (uint)c; c >>= 32; if (c != 0) { Nat.DecAt(6, z, 3); } } } } #endif
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Runtime.Serialization; using TrackableEntities; using TrackableEntities.Client; using System.ComponentModel.DataAnnotations; namespace AIM.Web.Admin.Models.EntityModels { [JsonObject(IsReference = true)] [DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")] public partial class Job : ModelBase<Job>, IEquatable<Job>, ITrackable { public Job() { this.Applications = new ChangeTrackingCollection<Application>(); this.Employees = new ChangeTrackingCollection<Employee>(); this.OpenJobs = new ChangeTrackingCollection<OpenJob>(); } [DataMember] [Display(Name = "Job ID")] public int JobId { get { return _JobId; } set { if (Equals(value, _JobId)) return; _JobId = value; NotifyPropertyChanged(m => m.JobId); } } private int _JobId; [DataMember] [Display(Name = "Position")] public string Position { get { return _Position; } set { if (Equals(value, _Position)) return; _Position = value; NotifyPropertyChanged(m => m.Position); } } private string _Position; [DataMember] [Display(Name = "Description")] public string Description { get { return _Description; } set { if (Equals(value, _Description)) return; _Description = value; NotifyPropertyChanged(m => m.Description); } } private string _Description; [DataMember] [Display(Name = "Full Part Time")] public string FullPartTime { get { return _FullPartTime; } set { if (Equals(value, _FullPartTime)) return; _FullPartTime = value; NotifyPropertyChanged(m => m.FullPartTime); } } private string _FullPartTime; [DataMember] [Display(Name = "Salary Range")] public string SalaryRange { get { return _SalaryRange; } set { if (Equals(value, _SalaryRange)) return; _SalaryRange = value; NotifyPropertyChanged(m => m.SalaryRange); } } private string _SalaryRange; [DataMember] [Display(Name = "Questionnaire ID")] public int? QuestionnaireId { get { return _QuestionnaireId; } set { if (Equals(value, _QuestionnaireId)) return; _QuestionnaireId = value; NotifyPropertyChanged(m => m.QuestionnaireId); } } private int? _QuestionnaireId; [DataMember] [Display(Name = "Hours ID")] public int? HoursId { get { return _HoursId; } set { if (Equals(value, _HoursId)) return; _HoursId = value; NotifyPropertyChanged(m => m.HoursId); } } private int? _HoursId; [DataMember] [Display(Name = "Interview Question ID")] public int? InterviewQuestionId { get { return _InterviewQuestionId; } set { if (Equals(value, _InterviewQuestionId)) return; _InterviewQuestionId = value; NotifyPropertyChanged(m => m.InterviewQuestionId); } } private int? _InterviewQuestionId; [DataMember] [Display(Name = "Applications")] public ChangeTrackingCollection<Application> Applications { get { return _Applications; } set { if (Equals(value, _Applications)) return; _Applications = value; NotifyPropertyChanged(m => m.Applications); } } private ChangeTrackingCollection<Application> _Applications; [DataMember] [Display(Name = "Employees")] public ChangeTrackingCollection<Employee> Employees { get { return _Employees; } set { if (Equals(value, _Employees)) return; _Employees = value; NotifyPropertyChanged(m => m.Employees); } } private ChangeTrackingCollection<Employee> _Employees; [DataMember] [Display(Name = "Hour")] public Hour Hour { get { return _Hour; } set { if (Equals(value, _Hour)) return; _Hour = value; HourChangeTracker = _Hour == null ? null : new ChangeTrackingCollection<Hour> { _Hour }; NotifyPropertyChanged(m => m.Hour); } } private Hour _Hour; private ChangeTrackingCollection<Hour> HourChangeTracker { get; set; } [DataMember] [Display(Name = "Interview Question")] public InterviewQuestion InterviewQuestion { get { return _InterviewQuestion; } set { if (Equals(value, _InterviewQuestion)) return; _InterviewQuestion = value; InterviewQuestionChangeTracker = _InterviewQuestion == null ? null : new ChangeTrackingCollection<InterviewQuestion> { _InterviewQuestion }; NotifyPropertyChanged(m => m.InterviewQuestion); } } private InterviewQuestion _InterviewQuestion; private ChangeTrackingCollection<InterviewQuestion> InterviewQuestionChangeTracker { get; set; } [DataMember] [Display(Name = "Questionnaire")] public Questionnaire Questionnaire { get { return _Questionnaire; } set { if (Equals(value, _Questionnaire)) return; _Questionnaire = value; QuestionnaireChangeTracker = _Questionnaire == null ? null : new ChangeTrackingCollection<Questionnaire> { _Questionnaire }; NotifyPropertyChanged(m => m.Questionnaire); } } private Questionnaire _Questionnaire; private ChangeTrackingCollection<Questionnaire> QuestionnaireChangeTracker { get; set; } [DataMember] [Display(Name = "Open Jobs")] public ChangeTrackingCollection<OpenJob> OpenJobs { get { return _OpenJobs; } set { if (Equals(value, _OpenJobs)) return; _OpenJobs = value; NotifyPropertyChanged(m => m.OpenJobs); } } private ChangeTrackingCollection<OpenJob> _OpenJobs; #region Change Tracking [DataMember] public TrackingState TrackingState { get; set; } [DataMember] public ICollection<string> ModifiedProperties { get; set; } [JsonProperty, DataMember] private Guid EntityIdentifier { get; set; } #pragma warning disable 414 [JsonProperty, DataMember] private Guid _entityIdentity = default(Guid); #pragma warning restore 414 bool IEquatable<Job>.Equals(Job other) { if (EntityIdentifier != default(Guid)) return EntityIdentifier == other.EntityIdentifier; return false; } #endregion Change Tracking } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject, IDisposable { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); private static TaskScheduler s_UIThreadScheduler; private InteractiveAssemblyLoader _assemblyLoader; private MetadataShadowCopyProvider _metadataFileProvider; private ReplServiceProvider _replServiceProvider; private InteractiveScriptGlobals _globals; // Session is not thread-safe by itself, and the compilation // and execution of scripts are asynchronous operations. // However since the operations are executed serially, it // is sufficient to lock when creating the async tasks. private readonly object _lastTaskGuard = new object(); private Task<EvaluationState> _lastTask; private struct EvaluationState { internal ImmutableArray<string> SourceSearchPaths; internal ImmutableArray<string> ReferenceSearchPaths; internal string WorkingDirectory; internal readonly ScriptState<object> ScriptStateOpt; internal readonly ScriptOptions ScriptOptions; internal EvaluationState( ScriptState<object> scriptState, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { ScriptStateOpt = scriptState; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; } internal EvaluationState WithScriptState(ScriptState<object> state) { return new EvaluationState( state, ScriptOptions, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } internal EvaluationState WithOptions(ScriptOptions options) { return new EvaluationState( ScriptStateOpt, options, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } } private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); #region Setup public Service() { var initialState = new EvaluationState( scriptState: null, scriptOptions: ScriptOptions.Default, sourceSearchPaths: ImmutableArray<string>.Empty, referenceSearchPaths: ImmutableArray<string>.Empty, workingDirectory: Directory.GetCurrentDirectory()); _lastTask = Task.FromResult(initialState); Console.OutputEncoding = Encoding.UTF8; // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; } private void HandleProcessExit(object sender, EventArgs e) { Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; } public void Dispose() { _metadataFileProvider.Dispose(); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replServiceProviderType, string cultureName) { Debug.Assert(replServiceProviderType != null); Debug.Assert(cultureName != null); Debug.Assert(_metadataFileProvider == null); Debug.Assert(_assemblyLoader == null); Debug.Assert(_replServiceProvider == null); // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories, documentationCommentsCulture: new CultureInfo(cultureName)); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType); _globals = new InteractiveScriptGlobals(Console.Out, _replServiceProvider.ObjectFormatter); } private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties)); } private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { var c = new Control(); c.CreateControl(); s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_lastTaskGuard) { _lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory); } } private async Task<EvaluationState> SetPathsAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { Directory.SetCurrentDirectory(baseDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(referenceSearchPaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(sourceSearchPaths); } finally { state = CompleteExecution(state, operation, success: true); } return state; } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); lock (_lastTaskGuard) { _lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting); } } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); lock (_lastTaskGuard) { _lastTask = AddReferenceAsync(_lastTask, operation, reference); } } private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences)); success = true; } else { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } return state; } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); lock (_lastTaskGuard) { _lastTask = ExecuteAsync(_lastTask, operation, text); } } private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions); if (script != null) { // successful if compiled success = true; // remove references and imports from the options, they have been applied and will be inherited from now on: state = state.WithOptions(state.ScriptOptions.RemoveImportsAndReferences()); var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); if (newScriptState != null) { DisplaySubmissionResult(newScriptState); state = state.WithScriptState(newScriptState); } } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success); } return state; } private void DisplaySubmissionResult(ScriptState<object> state) { if (state.Script.HasReturnValue()) { _globals.Print(state.ReturnValue); } } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); lock (_lastTaskGuard) { _lastTask = ExecuteFileAsync(operation, _lastTask, path); } } private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success) { // send any updates to the host object and current directory back to the client: var currentSourcePaths = _globals.SourcePaths.ToArray(); var currentReferencePaths = _globals.ReferencePaths.ToArray(); var currentWorkingDirectory = Directory.GetCurrentDirectory(); var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths; var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths; var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory; operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory)); // no changes in resolvers: if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null) { return state; } var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths); var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths); var newWorkingDirectory = currentWorkingDirectory; ScriptOptions newOptions = state.ScriptOptions; if (changedReferencePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory)); } if (changedSourcePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory)); } return new EvaluationState( state.ScriptStateOpt, newOptions, newSourcePaths, newReferencePaths, workingDirectory: newWorkingDirectory); } private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask) { try { return await lastTask.ConfigureAwait(false); } catch (Exception e) { ReportUnhandledException(e); return lastTask.Result; } } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations // TODO (tomat): testing only public void SetTestObjectFormattingOptions() { _globals.PrintOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: int.MaxValue, memberIndentation: " "); } /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task<EvaluationState> InitializeContextAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory); var metadataReferences = new List<PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions. WithFilePath(scriptPathOpt). WithReferences(metadataReferences). WithImports(CommandLineHelpers.GetImports(args)). WithMetadataResolver(metadataResolver). WithSourceResolver(sourceResolver), args.SourcePaths, args.ReferencePaths, rspDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(args.ReferencePaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(args.SourcePaths); _globals.Args.AddRange(args.ScriptArguments); if (scriptPathOpt != null) { var newScriptState = await ExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false); if (newScriptState != null) { // remove references and imports from the options, they have been applied and will be inherited from now on: rspState = rspState. WithScriptState(newScriptState). WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences()); } } state = rspState; } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return state; } private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithFilePath(path); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader); } var diagnostics = script.Compile(); if (diagnostics.HasAnyErrors()) { DisplayInteractiveErrors(diagnostics, Console.Error); return null; } return (Script<object>)script; } private async Task<EvaluationState> ExecuteFileAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, Task<EvaluationState> lastTask, string path) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false); var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false); if (newScriptState != null) { success = true; state = state.WithScriptState(newScriptState); } } finally { state = CompleteExecution(state, operation, success); } return state; } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath) { string content = null; if (fullPath != null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } ScriptState<object> newScriptState = null; if (content != null) { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions); if (script != null) { newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); } } return newScriptState; } private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray(); var uniqueDirectories = new HashSet<string>(directories); writer.WriteLine(uniqueDirectories.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string directory in directories) { if (uniqueDirectories.Remove(directory)) { writer.Write(" "); writer.WriteLine(directory); } } } private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt) { return await Task.Factory.StartNew(async () => { try { var task = (stateOpt == null) ? script.RunAsync(_globals, CancellationToken.None) : script.ContinueAsync(stateOpt, CancellationToken.None); return await task.ConfigureAwait(false); } catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException) { Console.Error.WriteLine(e.InnerException.Message); return null; } catch (Exception e) { // TODO (tomat): format exception Console.Error.WriteLine(e); return null; } }, CancellationToken.None, TaskCreationOptions.None, s_UIThreadScheduler).Unwrap().ConfigureAwait(false); } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _replServiceProvider.DiagnosticFormatter; foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #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.Reflection; using System.Net; using System.IO; using System.Timers; using System.Drawing; using System.Drawing.Imaging; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage { /// <summary> /// </summary> /// <remarks> /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageServiceModule")] public class MapImageServiceModule : IMapImageUploadModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MAP IMAGE SERVICE MODULE]"; private bool m_enabled = false; private IMapImageService m_MapService; private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private int m_refreshtime = 0; private int m_lastrefresh = 0; private System.Timers.Timer m_refreshTimer; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "MapImageServiceModule"; } } public void RegionLoaded(Scene scene) { } public void Close() { } public void PostInitialise() { } ///<summary> /// ///</summary> public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("MapImageService", ""); if (name != Name) return; } IConfig config = source.Configs["MapImageService"]; if (config == null) return; int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime")); // if refresh is less than zero, disable the module if (refreshminutes < 0) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Negative refresh time given in config. Module disabled."); return; } string service = config.GetString("LocalServiceModule", string.Empty); if (service == string.Empty) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed."); return; } Object[] args = new Object[] { source }; m_MapService = ServerUtils.LoadPlugin<IMapImageService>(service, args); if (m_MapService == null) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service); return; } // we don't want the timer if the interval is zero, but we still want this module enables if(refreshminutes > 0) { m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms m_refreshTimer = new System.Timers.Timer(); m_refreshTimer.Enabled = true; m_refreshTimer.AutoReset = true; m_refreshTimer.Interval = m_refreshtime; m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh); m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}", refreshminutes, service); } else { m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with no refresh and service object {0}", service); } m_enabled = true; } ///<summary> /// ///</summary> public void AddRegion(Scene scene) { if (!m_enabled) return; // Every shared region module has to maintain an indepedent list of // currently running regions lock (m_scenes) m_scenes[scene.RegionInfo.RegionID] = scene; // v2 Map generation on startup is now handled by scene to allow bmp to be shared with // v1 service and not generate map tiles twice as was previous behavior //scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) UploadMapTile(s); }; scene.RegisterModuleInterface<IMapImageUploadModule>(this); } ///<summary> /// ///</summary> public void RemoveRegion(Scene scene) { if (! m_enabled) return; lock (m_scenes) m_scenes.Remove(scene.RegionInfo.RegionID); } #endregion ISharedRegionModule ///<summary> /// ///</summary> private void HandleMaptileRefresh(object sender, EventArgs ea) { // this approach is a bit convoluted becase we want to wait for the // first upload to happen on startup but after all the objects are // loaded and initialized if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime) return; m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: map refresh!"); lock (m_scenes) { foreach (IScene scene in m_scenes.Values) { try { UploadMapTile(scene); } catch (Exception ex) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: something bad happened {0}", ex.Message); } } } m_lastrefresh = Util.EnvironmentTickCount(); } public void UploadMapTile(IScene scene, Bitmap mapTile) { m_log.DebugFormat("{0} Upload maptile for {1}", LogHeader, scene.Name); // mapTile.Save( // DEBUG DEBUG // String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY), // ImageFormat.Jpeg); // If the region/maptile is legacy sized, just upload the one tile like it has always been done if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize) { ConvertAndUploadMaptile(mapTile, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.RegionName); } else { // For larger regions (varregion) we must cut the region image into legacy sized // pieces since that is how the maptile system works. // Note the assumption that varregions are always a multiple of legacy size. for (uint xx = 0; xx < mapTile.Width; xx += Constants.RegionSize) { for (uint yy = 0; yy < mapTile.Height; yy += Constants.RegionSize) { // Images are addressed from the upper left corner so have to do funny // math to pick out the sub-tile since regions are numbered from // the lower left. Rectangle rect = new Rectangle( (int)xx, mapTile.Height - (int)yy - (int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionSize); using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat)) { ConvertAndUploadMaptile(subMapTile, scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize), scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize), scene.Name); } } } } } ///<summary> /// ///</summary> private void UploadMapTile(IScene scene) { // Create a JPG map tile and upload it to the AddMapTile API IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>(); if (tileGenerator == null) { m_log.WarnFormat("{0} Cannot upload map tile without an ImageGenerator", LogHeader); return; } using (Bitmap mapTile = tileGenerator.CreateMapTile()) { if (mapTile != null) { UploadMapTile(scene, mapTile); } else { m_log.WarnFormat("{0} Tile image generation failed", LogHeader); } } } private void ConvertAndUploadMaptile(Image tileImage, uint locX, uint locY, string regionName) { byte[] jpgData = Utils.EmptyBytes; using (MemoryStream stream = new MemoryStream()) { tileImage.Save(stream, ImageFormat.Jpeg); jpgData = stream.ToArray(); } if (jpgData != Utils.EmptyBytes) { string reason = string.Empty; if (!m_MapService.AddMapTile((int)locX, (int)locY, jpgData, out reason)) { m_log.DebugFormat("{0} Unable to upload tile image for {1} at {2}-{3}: {4}", LogHeader, regionName, locX, locY, reason); } } else { m_log.WarnFormat("{0} Tile image generation failed for region {1}", LogHeader, regionName); } } } }
//----------------------------------------------------------------------- // <copyright file="Iis6Website.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Web { using System; using System.DirectoryServices; using System.Globalization; using System.IO; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Create</i> (<b>Required: </b> Name <b>Optional:</b> Force, Properties, Identifier <b>OutPut: </b>Identifier)</para> /// <para><i>CheckExists</i> (<b>Required: </b> Name <b>Output: </b>Exists)</para> /// <para><i>Continue</i> (<b>Required: </b> Name)</para> /// <para><i>Delete</i> (<b>Required: </b> Name)</para> /// <para><i>GetMetabasePropertyValue</i> (<b>Required: </b> Name, MetabasePropertyName<b>Output: </b>MetabasePropertyValue)</para> /// <para><i>Start</i> (<b>Required: </b> Name)</para> /// <para><i>Stop</i> (<b>Required: </b> Name)</para> /// <para><i>Pause</i> (<b>Required: </b> Name)</para> /// <para><b>Remote Execution Support:</b> Yes. Please note that the machine you execute from must have IIS installed.</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <!-- Create a website --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="Create" Name="awebsite" Force="true" Properties="AspEnableApplicationRestart=False;AspScriptTimeout=1200;ContentIndexed=False;LogExtFileFlags=917455;ScriptMaps=;ServerBindings=:80:www.free2todev.com;SecureBindings=;ServerAutoStart=True;UseHostName=True"/> /// <!-- Pause a website --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="Pause" Name="awebsite" /> /// <!-- Stop a website --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="Stop" Name="awebsite" /> /// <!-- GetMetabasePropertyValue --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="GetMetabasePropertyValue" Name="awebsite" MetabasePropertyName="ServerState"> /// <Output PropertyName="WebsiteState" TaskParameter="MetabasePropertyValue"/> /// </MSBuild.ExtensionPack.Web.Iis6Website> /// <Message Text="WebsiteState: $(ServerState)"/> /// <!-- Start a website --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="Start" Name="awebsite" /> /// <!-- Check whether a website exists --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="CheckExists" Name="awebsite"> /// <Output PropertyName="SiteExists" TaskParameter="Exists"/> /// </MSBuild.ExtensionPack.Web.Iis6Website> /// <Message Text="Website Exists: $(SiteExists)"/> /// <!-- Check whether a website exists --> /// <MSBuild.ExtensionPack.Web.Iis6Website TaskAction="CheckExists" Name="anonwebsite"> /// <Output PropertyName="SiteExists" TaskParameter="Exists"/> /// </MSBuild.ExtensionPack.Web.Iis6Website> /// <Message Text="Website Exists: $(SiteExists)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class Iis6Website : BaseTask { private DirectoryEntry websiteEntry; private string properties; private int sleep = 250; /// <summary> /// Sets the Properties. Use a semi-colon delimiter. See <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cde669f1-5714-4159-af95-f334251c8cbd.mspx?mfr=true">Metabase Property Reference (IIS 6.0)</a><para/> /// Some properties may be split within the semi colon, e.g. to set multiple server bindings you could use Properties="ServerBindings=:80:first.host.header|:80:second.host.header" /// If a property contains =, enter #~# as a special sequence which will be replaced with = during processing /// </summary> public string Properties { get { return System.Web.HttpUtility.HtmlDecode(this.properties); } set { this.properties = value; } } /// <summary> /// Sets the Metabase Property Name to retrieve. See <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cde669f1-5714-4159-af95-f334251c8cbd.mspx?mfr=true">Metabase Property Reference (IIS 6.0)</a><para/> /// </summary> public string MetabasePropertyName { get; set; } /// <summary> /// Gets the string value of the requested MetabasePropertyName /// </summary> [Output] public string MetabasePropertyValue { get; set; } /// <summary> /// Gets or sets the name. /// </summary> [Required] public string Name { get; set; } /// <summary> /// Set force to true to delete an existing website when calling Create. Default is false. /// </summary> public bool Force { get; set; } /// <summary> /// Set the sleep time in ms for when calling Start, Stop, Pause or Continue. Default is 250ms. /// </summary> public int Sleep { get { return this.sleep; } set { this.sleep = value; } } /// <summary> /// Gets or sets the Identifier for the website. If specified for Create and the Identifier already exists, an error is logged. /// </summary> [Output] public int Identifier { get; set; } /// <summary> /// Gets whether the website exists. /// </summary> [Output] public bool Exists { get; set; } /// <summary> /// Gets the IIS path. /// </summary> /// <value>The IIS path.</value> internal string IisPath { get { return "IIS://" + this.MachineName + "/W3SVC"; } } /// <summary> /// When overridden in a derived class, executes the task. /// </summary> protected override void InternalExecute() { switch (this.TaskAction) { case "Create": this.Create(); break; case "Delete": this.Delete(); break; case "Start": case "Stop": case "Pause": case "Continue": this.ControlWebsite(); break; case "CheckExists": this.CheckWebsiteExists(); break; case "GetMetabasePropertyValue": this.GetMetabasePropertyValue(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private static void UpdateMetaBaseProperty(DirectoryEntry entry, string metaBasePropertyName, string metaBaseProperty) { if (metaBaseProperty.IndexOf('|') == -1) { string propertyTypeName; using (DirectoryEntry di = new DirectoryEntry(entry.SchemaEntry.Parent.Path + "/" + metaBasePropertyName)) { propertyTypeName = (string)di.Properties["Syntax"].Value; } if (string.Compare(propertyTypeName, "binary", StringComparison.OrdinalIgnoreCase) == 0) { object[] metaBasePropertyBinaryFormat = new object[metaBaseProperty.Length / 2]; for (int i = 0; i < metaBasePropertyBinaryFormat.Length; i++) { metaBasePropertyBinaryFormat[i] = metaBaseProperty.Substring(i * 2, 2); } PropertyValueCollection propValues = entry.Properties[metaBasePropertyName]; propValues.Clear(); propValues.Add(metaBasePropertyBinaryFormat); entry.CommitChanges(); } else { if (string.Compare(metaBasePropertyName, "path", StringComparison.OrdinalIgnoreCase) == 0) { DirectoryInfo f = new DirectoryInfo(metaBaseProperty); metaBaseProperty = f.FullName; } entry.Invoke("Put", metaBasePropertyName, metaBaseProperty); entry.Invoke("SetInfo"); } } else { entry.Invoke("Put", metaBasePropertyName, string.Empty); entry.Invoke("SetInfo"); string[] metabaseProperties = metaBaseProperty.Split('|'); foreach (string metabasePropertySplit in metabaseProperties) { entry.Properties[metaBasePropertyName].Add(metabasePropertySplit); } entry.CommitChanges(); } } private void GetMetabasePropertyValue() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Getting Metabase Property Value for: {0} from: {1}", this.MetabasePropertyName, this.Name)); if (this.CheckWebsiteExists()) { if (this.websiteEntry.Properties[this.MetabasePropertyName] != null && this.websiteEntry.Properties[this.MetabasePropertyName].Value != null) { this.MetabasePropertyValue = this.websiteEntry.Properties[this.MetabasePropertyName].Value.ToString(); } else { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "MetabasePropertyName not found: {0}", this.MetabasePropertyName)); } } else { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Website not found: {0}", this.Name)); } } private bool CheckWebsiteExists() { this.LoadWebsite(); if (this.websiteEntry != null) { this.Exists = true; } return this.Exists; } private DirectoryEntry LoadWebService() { return new DirectoryEntry(this.IisPath); } private void LoadWebsite() { using (DirectoryEntry webService = this.LoadWebService()) { DirectoryEntries webEntries = webService.Children; foreach (DirectoryEntry webEntry in webEntries) { if (webEntry.SchemaClassName == "IIsWebServer") { if (string.Compare(this.Name, webEntry.Properties["ServerComment"][0].ToString(), StringComparison.CurrentCultureIgnoreCase) == 0) { this.websiteEntry = webEntry; break; } } webEntry.Dispose(); } } } private void Create() { this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentUICulture, "Creating Website: {0}", this.Name)); using (DirectoryEntry webserviceEntry = this.LoadWebService()) { // We'll try and find the website first. this.LoadWebsite(); if (this.websiteEntry != null) { if (this.Force) { this.LogTaskMessage(string.Format(CultureInfo.CurrentUICulture, "Website exists. Deleting Website: {0}", this.Name)); this.Delete(); } else { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "The Website already exists: {0}", this.Name)); return; } } if (this.Identifier > 0) { try { this.websiteEntry = (DirectoryEntry)webserviceEntry.Invoke("Create", "IIsWebServer", this.Identifier); this.websiteEntry.CommitChanges(); webserviceEntry.CommitChanges(); } catch { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "WebsiteIdentifier {0} already exists. Aborting: {1}", this.Identifier, this.Name)); return; } } else { bool foundSlot = false; this.Identifier = 1; do { try { this.websiteEntry = (DirectoryEntry)webserviceEntry.Invoke("Create", "IIsWebServer", this.Identifier); this.websiteEntry.CommitChanges(); webserviceEntry.CommitChanges(); foundSlot = true; } catch { if (this.Identifier > 1000) { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "websiteIdentifier > 1000. Aborting: {0}", this.Name)); return; } ++this.Identifier; } } while (foundSlot == false); } using (DirectoryEntry vdirEntry = (DirectoryEntry)this.websiteEntry.Invoke("Create", "IIsWebVirtualDir", "ROOT")) { vdirEntry.CommitChanges(); this.websiteEntry.Invoke("Put", "AppFriendlyName", this.Name); this.websiteEntry.Invoke("Put", "ServerComment", this.Name); this.websiteEntry.Invoke("SetInfo"); // Now loop through all the metabase properties specified. if (string.IsNullOrEmpty(this.Properties) == false) { string[] propList = this.Properties.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in propList) { string[] propPair = s.Split(new[] { '=' }); string propName = propPair[0]; string propValue = propPair.Length > 1 ? propPair[1] : string.Empty; // handle the special character sequence to insert '=' if property requires it propValue = propValue.Replace("#~#", "="); this.LogTaskMessage(string.Format(CultureInfo.CurrentUICulture, "\tAdding Property: {0}({1})", propName, propValue)); UpdateMetaBaseProperty(this.websiteEntry, propName, propValue); } } vdirEntry.CommitChanges(); this.websiteEntry.CommitChanges(); this.websiteEntry.Dispose(); } } } private void Delete() { if (this.CheckWebsiteExists()) { this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentUICulture, "Deleting Website: {0}", this.Name)); using (DirectoryEntry webService = this.LoadWebService()) { object[] args = { "IIsWebServer", Convert.ToInt32(this.websiteEntry.Name, CultureInfo.InvariantCulture) }; webService.Invoke("Delete", args); } } } private void ControlWebsite() { if (this.CheckWebsiteExists()) { this.LogTaskMessage(string.Format(CultureInfo.CurrentUICulture, "{0} Website: {1}", this.TaskAction, this.Name)); // need to insert a sleep as the code occasionaly fails to work without a wait. System.Threading.Thread.Sleep(this.Sleep); this.websiteEntry.Invoke(this.TaskAction, null); } else { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Website not found: {0}", this.Name)); } } } }
using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace OmniSharp { public class SnippetGenerator { private int _counter = 1; private StringBuilder _sb = new StringBuilder(); private SymbolDisplayFormat _format; public bool IncludeMarkers { get; set; } public bool IncludeOptionalParameters { get; set; } public string GenerateSnippet(ISymbol symbol) { _format = SymbolDisplayFormat.MinimallyQualifiedFormat; _format = _format.WithMemberOptions(_format.MemberOptions ^ SymbolDisplayMemberOptions.IncludeContainingType ^ SymbolDisplayMemberOptions.IncludeType); if (IsConstructor(symbol)) { // only the containing type contains the type parameters var parts = symbol.ContainingType.ToDisplayParts(_format); RenderDisplayParts(symbol, parts); parts = symbol.ToDisplayParts(_format); RenderParameters(symbol as IMethodSymbol); } else { var symbolKind = symbol.Kind; if (symbol.Kind == SymbolKind.Method) { RenderMethodSymbol(symbol as IMethodSymbol); } else if (symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter) { _sb.Append(symbol.Name); } else { var parts = symbol.ToDisplayParts(_format); RenderDisplayParts(symbol, parts); } } if (IncludeMarkers) { _sb.Append("$0"); } return _sb.ToString(); } private void RenderMethodSymbol(IMethodSymbol methodSymbol) { var nonInferredTypeArguments = NonInferredTypeArguments(methodSymbol); _sb.Append(methodSymbol.Name); if (nonInferredTypeArguments.Any()) { _sb.Append("<"); var last = nonInferredTypeArguments.Last(); foreach (var arg in nonInferredTypeArguments) { RenderSnippetStartMarker(); _sb.Append(arg); RenderSnippetEndMarker(); if (arg != last) { _sb.Append(", "); } } _sb.Append(">"); } RenderParameters(methodSymbol); if (methodSymbol.ReturnsVoid) { _sb.Append(";"); } } private void RenderParameters(IMethodSymbol methodSymbol) { IEnumerable<IParameterSymbol> parameters = methodSymbol.Parameters; if (!IncludeOptionalParameters) { parameters = parameters.Where(p => !p.IsOptional); } _sb.Append("("); if (parameters.Any()) { var last = parameters.Last(); foreach (var parameter in parameters) { RenderSnippetStartMarker(); _sb.Append(parameter.ToDisplayString(_format)); RenderSnippetEndMarker(); if (parameter != last) { _sb.Append(", "); } } } _sb.Append(")"); } private IEnumerable<ISymbol> NonInferredTypeArguments(IMethodSymbol methodSymbol) { var typeParameters = methodSymbol.TypeParameters; var typeArguments = methodSymbol.TypeArguments; var nonInferredTypeArguments = new List<ISymbol>(); for (int i = 0; i < typeParameters.Count(); i++) { var arg = typeArguments[i]; var param = typeParameters[i]; if (arg == param) { // this type parameter has not been resolved nonInferredTypeArguments.Add(arg); } } // We might have more inferred types once the method parameters have // been supplied. Remove these. var parameterTypes = ParameterTypes(methodSymbol); return nonInferredTypeArguments.Except(parameterTypes); } private IEnumerable<ISymbol> ParameterTypes(IMethodSymbol methodSymbol) { foreach (var parameter in methodSymbol.Parameters) { var types = ExplodeTypes(parameter.Type); foreach (var type in types) { yield return type; } } } private IEnumerable<ISymbol> ExplodeTypes(ISymbol symbol) { var typeSymbol = symbol as INamedTypeSymbol; if (typeSymbol != null) { var typeParams = typeSymbol.TypeArguments; foreach (var typeParam in typeParams) { var explodedTypes = ExplodeTypes(typeParam); foreach (var type in explodedTypes) { yield return type; } } } yield return symbol; } private bool IsConstructor(ISymbol symbol) { var methodSymbol = symbol as IMethodSymbol; return methodSymbol != null && methodSymbol.MethodKind == MethodKind.Constructor; } private void RenderSnippetStartMarker() { if (IncludeMarkers) { _sb.Append("${"); _sb.Append(_counter++); _sb.Append(":"); } } private void RenderSnippetEndMarker() { if (IncludeMarkers) { _sb.Append("}"); } } private void RenderDisplayParts(ISymbol symbol, IEnumerable<SymbolDisplayPart> parts) { foreach (var part in parts) { if (part.Kind == SymbolDisplayPartKind.TypeParameterName) { RenderSnippetStartMarker(); _sb.Append(part.ToString()); RenderSnippetEndMarker(); } else { _sb.Append(part.ToString()); } } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Subject Book List Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SUBLDataSet : EduHubDataSet<SUBL> { /// <inheritdoc /> public override string Name { get { return "SUBL"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SUBLDataSet(EduHubContext Context) : base(Context) { Index_BLKEY = new Lazy<Dictionary<string, IReadOnlyList<SUBL>>>(() => this.ToGroupedDictionary(i => i.BLKEY)); Index_BOOK = new Lazy<NullDictionary<string, IReadOnlyList<SUBL>>>(() => this.ToGroupedNullDictionary(i => i.BOOK)); Index_TID = new Lazy<Dictionary<int, SUBL>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SUBL" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SUBL" /> fields for each CSV column header</returns> internal override Action<SUBL, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SUBL, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "BLKEY": mapper[i] = (e, v) => e.BLKEY = v; break; case "BOOK": mapper[i] = (e, v) => e.BOOK = v; break; case "TTPERIOD": mapper[i] = (e, v) => e.TTPERIOD = v; break; case "TAG": mapper[i] = (e, v) => e.TAG = v; break; case "SEMESTER": mapper[i] = (e, v) => e.SEMESTER = v == null ? (short?)null : short.Parse(v); break; case "NUMBER_REQUIRED": mapper[i] = (e, v) => e.NUMBER_REQUIRED = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SUBL" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SUBL" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SUBL" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SUBL}"/> of entities</returns> internal override IEnumerable<SUBL> ApplyDeltaEntities(IEnumerable<SUBL> Entities, List<SUBL> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.BLKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.BLKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<SUBL>>> Index_BLKEY; private Lazy<NullDictionary<string, IReadOnlyList<SUBL>>> Index_BOOK; private Lazy<Dictionary<int, SUBL>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SUBL by BLKEY field /// </summary> /// <param name="BLKEY">BLKEY value used to find SUBL</param> /// <returns>List of related SUBL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SUBL> FindByBLKEY(string BLKEY) { return Index_BLKEY.Value[BLKEY]; } /// <summary> /// Attempt to find SUBL by BLKEY field /// </summary> /// <param name="BLKEY">BLKEY value used to find SUBL</param> /// <param name="Value">List of related SUBL entities</param> /// <returns>True if the list of related SUBL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByBLKEY(string BLKEY, out IReadOnlyList<SUBL> Value) { return Index_BLKEY.Value.TryGetValue(BLKEY, out Value); } /// <summary> /// Attempt to find SUBL by BLKEY field /// </summary> /// <param name="BLKEY">BLKEY value used to find SUBL</param> /// <returns>List of related SUBL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SUBL> TryFindByBLKEY(string BLKEY) { IReadOnlyList<SUBL> value; if (Index_BLKEY.Value.TryGetValue(BLKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SUBL by BOOK field /// </summary> /// <param name="BOOK">BOOK value used to find SUBL</param> /// <returns>List of related SUBL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SUBL> FindByBOOK(string BOOK) { return Index_BOOK.Value[BOOK]; } /// <summary> /// Attempt to find SUBL by BOOK field /// </summary> /// <param name="BOOK">BOOK value used to find SUBL</param> /// <param name="Value">List of related SUBL entities</param> /// <returns>True if the list of related SUBL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByBOOK(string BOOK, out IReadOnlyList<SUBL> Value) { return Index_BOOK.Value.TryGetValue(BOOK, out Value); } /// <summary> /// Attempt to find SUBL by BOOK field /// </summary> /// <param name="BOOK">BOOK value used to find SUBL</param> /// <returns>List of related SUBL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SUBL> TryFindByBOOK(string BOOK) { IReadOnlyList<SUBL> value; if (Index_BOOK.Value.TryGetValue(BOOK, out value)) { return value; } else { return null; } } /// <summary> /// Find SUBL by TID field /// </summary> /// <param name="TID">TID value used to find SUBL</param> /// <returns>Related SUBL entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SUBL FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SUBL by TID field /// </summary> /// <param name="TID">TID value used to find SUBL</param> /// <param name="Value">Related SUBL entity</param> /// <returns>True if the related SUBL entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SUBL Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SUBL by TID field /// </summary> /// <param name="TID">TID value used to find SUBL</param> /// <returns>Related SUBL entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SUBL TryFindByTID(int TID) { SUBL value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SUBL table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SUBL]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SUBL]( [TID] int IDENTITY NOT NULL, [BLKEY] varchar(5) NOT NULL, [BOOK] varchar(13) NULL, [TTPERIOD] varchar(6) NULL, [TAG] varchar(4) NULL, [SEMESTER] smallint NULL, [NUMBER_REQUIRED] smallint NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SUBL_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SUBL_Index_BLKEY] ON [dbo].[SUBL] ( [BLKEY] ASC ); CREATE NONCLUSTERED INDEX [SUBL_Index_BOOK] ON [dbo].[SUBL] ( [BOOK] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SUBL]') AND name = N'SUBL_Index_BOOK') ALTER INDEX [SUBL_Index_BOOK] ON [dbo].[SUBL] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SUBL]') AND name = N'SUBL_Index_TID') ALTER INDEX [SUBL_Index_TID] ON [dbo].[SUBL] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SUBL]') AND name = N'SUBL_Index_BOOK') ALTER INDEX [SUBL_Index_BOOK] ON [dbo].[SUBL] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SUBL]') AND name = N'SUBL_Index_TID') ALTER INDEX [SUBL_Index_TID] ON [dbo].[SUBL] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SUBL"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SUBL"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SUBL> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SUBL] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SUBL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SUBL data set</returns> public override EduHubDataSetDataReader<SUBL> GetDataSetDataReader() { return new SUBLDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SUBL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SUBL data set</returns> public override EduHubDataSetDataReader<SUBL> GetDataSetDataReader(List<SUBL> Entities) { return new SUBLDataReader(new EduHubDataSetLoadedReader<SUBL>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SUBLDataReader : EduHubDataSetDataReader<SUBL> { public SUBLDataReader(IEduHubDataSetReader<SUBL> Reader) : base (Reader) { } public override int FieldCount { get { return 10; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // BLKEY return Current.BLKEY; case 2: // BOOK return Current.BOOK; case 3: // TTPERIOD return Current.TTPERIOD; case 4: // TAG return Current.TAG; case 5: // SEMESTER return Current.SEMESTER; case 6: // NUMBER_REQUIRED return Current.NUMBER_REQUIRED; case 7: // LW_DATE return Current.LW_DATE; case 8: // LW_TIME return Current.LW_TIME; case 9: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // BOOK return Current.BOOK == null; case 3: // TTPERIOD return Current.TTPERIOD == null; case 4: // TAG return Current.TAG == null; case 5: // SEMESTER return Current.SEMESTER == null; case 6: // NUMBER_REQUIRED return Current.NUMBER_REQUIRED == null; case 7: // LW_DATE return Current.LW_DATE == null; case 8: // LW_TIME return Current.LW_TIME == null; case 9: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // BLKEY return "BLKEY"; case 2: // BOOK return "BOOK"; case 3: // TTPERIOD return "TTPERIOD"; case 4: // TAG return "TAG"; case 5: // SEMESTER return "SEMESTER"; case 6: // NUMBER_REQUIRED return "NUMBER_REQUIRED"; case 7: // LW_DATE return "LW_DATE"; case 8: // LW_TIME return "LW_TIME"; case 9: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "BLKEY": return 1; case "BOOK": return 2; case "TTPERIOD": return 3; case "TAG": return 4; case "SEMESTER": return 5; case "NUMBER_REQUIRED": return 6; case "LW_DATE": return 7; case "LW_TIME": return 8; case "LW_USER": return 9; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Threading; using MonoBrick; using System.Diagnostics; using System.Collections.Generic; namespace MonoBrick.NXT { #region Base Sensor /// <summary> /// Sensor ports /// </summary> public enum SensorPort { #pragma warning disable In1 = 0, In2 = 1, In3 = 2, In4 = 3 #pragma warning restore }; /// <summary> /// Sensor types /// </summary> public enum SensorType { #pragma warning disable NoSensor = 0x00, Touch = 0x01, Temperature = 0x02, Reflection = 0x03, Angle = 0x04, LightActive = 0x05, LightInactive = 0x06, SoundDB = 0x07, SoundDBA = 0x08, Custom = 0x09,LowSpeed = 0x0A, LowSpeed9V = 0x0B, HighSpeed = 0x0C, ColorFull = 0x0D, ColorRed = 0x0E, ColorGreen = 0x0F, ColorBlue = 0x10, ColorNone = 0x11, ColorExit = 0x12 #pragma warning restore }; /// <summary> /// Sensor modes /// </summary> public enum SensorMode { #pragma warning disable Raw = 0x00, Bool = 0x20, Transition = 0x40, Period = 0x60, Percent = 0x80, Celsius = 0xA0, Fahrenheit = 0xc0, Angle = 0xe0 #pragma warning restore }; internal class SensorReadings{ public UInt16 Raw;//device dependent public UInt16 Normalized;//type dependent public Int16 Scaled;//mode dependent //public Int32 Calibrated;//not used } /// <summary> /// Analog Sensor class. Works as base class for all NXT sensors /// </summary> public class Sensor : ISensor { /// <summary> /// The sensor port to use /// </summary> protected SensorPort port; /// <summary> /// The connection to use for communication /// </summary> protected Connection<Command,Reply> connection = null; /// <summary> /// The sensor mode to use /// </summary> protected SensorMode Mode{get;private set;} /// <summary> /// The sensor type to use /// </summary> protected SensorType Type{get;private set;} /// <summary> /// True if sensor has been initialized /// </summary> protected bool hasInit; /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.Sensor"/> class with no sensor as type. /// </summary> public Sensor() { Mode = SensorMode.Raw; Type = SensorType.NoSensor; } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.Sensor"/> class. /// </summary> /// <param name='sensorType'> /// Sensor type /// </param> /// <param name='sensorMode'> /// Sensor mode /// </param> public Sensor(SensorType sensorType, SensorMode sensorMode) { Mode = sensorMode; Type = sensorType; } /// <summary> /// Resets the scaled value. /// </summary> protected void ResetScaledValue(){ ResetScaledValue(false); } /// <summary> /// Resets the scaled value. /// </summary> /// <param name='reply'> /// If set to <c>true</c> brick will send a reply /// </param> protected void ResetScaledValue(bool reply){ var command = new Command(CommandType.DirecCommand, CommandByte.ResetInputScaledValue, reply); command.Append((byte)port); connection.Send(command); if (reply) { var brickReply = connection.Receive(); Error.CheckForError(brickReply, 3); } } /// <summary> /// Updates the sensor type and mode. /// </summary> /// <param name='sensorType'> /// Sensor type. /// </param> /// <param name='sensorMode'> /// Sensor mode. /// </param> protected void UpdateTypeAndMode(SensorType sensorType, SensorMode sensorMode){ Type = sensorType; Mode = sensorMode; var command = new Command(CommandType.DirecCommand, CommandByte.SetInputMode, true); command.Append((byte)port); command.Append((byte)Type); command.Append((byte)Mode); connection.Send(command); var reply = connection.Receive(); Error.CheckForError(reply, 3); } internal SensorPort Port{ get{ return port;} set{ port = value;} } internal Connection<Command,Reply> Connection{ get{ return connection;} set{ connection = value;} } internal SensorReadings GetSensorReadings() { if (!hasInit) { Initialize(); } SensorReadings sensorReadings = new SensorReadings(); var command = new Command(CommandType.DirecCommand,CommandByte.GetInputValues, true); command.Append((byte) port); var reply = connection.SendAndReceive(command); Error.CheckForError(reply, 16); sensorReadings.Raw = reply.GetUInt16(8); sensorReadings.Normalized = reply.GetUInt16(10); sensorReadings.Scaled = reply.GetInt16(12); return sensorReadings; } /// <summary> /// Read mode dependent sensor value /// </summary> /// <returns> /// The scaled value /// </returns> protected Int16 GetScaledValue() { return GetSensorReadings().Scaled; } /// <summary> /// Read device dependent sensor value /// </summary> /// <returns> /// The raw value. /// </returns> protected UInt16 GetRawValue() { return GetSensorReadings().Raw; } /// <summary> /// Read type dependent sensor value /// </summary> /// <returns> /// The normalized value. /// </returns> protected UInt16 GetNormalizedValue() { return GetSensorReadings().Normalized; } /*protected Int32 CalibratedValue(){ return GetSensorValues().Scaled; }*/ /// <summary> /// Initialize this sensor /// </summary> virtual public void Initialize() { //Console.WriteLine("Sensor " + Port + " init"); if (connection != null && connection.IsConnected) { UpdateTypeAndMode(Type, Mode); Thread.Sleep(100); ResetScaledValue(); Thread.Sleep(100); UpdateTypeAndMode(Type, Mode); hasInit = true; } else { hasInit = false; } } /// <summary> /// Reset the sensor /// </summary> /// <param name='reply'> /// If set to <c>true</c> the brick will send a reply /// </param> virtual public void Reset(bool reply) { ResetScaledValue(reply); } /// <summary> /// Reads the sensor value as a string. /// </summary> /// <returns> /// The value as a string /// </returns> virtual public string ReadAsString() { return GetScaledValue().ToString(); } /// <summary> /// Reads a sensor value as int /// </summary> /// <returns> /// The value as int /// </returns> virtual public int ReadAsInt() { return GetScaledValue(); } /// <summary> /// Method for HiTec Color and Tilt Sensors /// </summary> /// <param name="mode"></param> /// <returns></returns> virtual public int ReadAsInt(int mode) { return GetScaledValue(); } /// <summary> /// Gets a value indicating whether the sensor has been initialized. /// </summary> /// <value> /// <c>true</c> if the sensor is initialized; otherwise, <c>false</c>. /// </value> public bool IsInitialized{get{return hasInit;}} /// <summary> /// Gets a dictionary of sensors that has been implemented. Can be use in a combobox or simular /// </summary> /// <value>The sensor dictionary.</value> public static Dictionary<string,Sensor> SensorDictionary{ get{ Dictionary<string,Sensor> dictionary = new Dictionary<string, Sensor>(); dictionary.Add("None" , new NoSensor()); dictionary.Add("HiTechnic Color",new HiTecColor()); dictionary.Add("HiTechnic Compass", new HiTecCompass()); dictionary.Add("HiTechnic Gyro", new HiTecGyro(0)); dictionary.Add("HiTechnic Tilt", new HiTecTilt()); dictionary.Add("NXT Color", new NXTColorSensor()); dictionary.Add("NXT Color Reflection Pct", new NXTColorSensor(SensorMode.Percent)); dictionary.Add("NXT Color Reflection Raw", new NXTColorSensor(SensorMode.Raw)); dictionary.Add("NXT Color Inactive Pct", new NXTColorSensor(ColorMode.None,SensorMode.Percent)); dictionary.Add("NXT Color Inactive Raw", new NXTColorSensor(ColorMode.None,SensorMode.Raw)); dictionary.Add("NXT Light Active Pct", new NXTLightSensor(LightMode.On,SensorMode.Percent)); dictionary.Add("NXT Light Active Raw", new NXTLightSensor(LightMode.On,SensorMode.Raw)); dictionary.Add("NXT Light Inactive Pct", new NXTLightSensor(LightMode.Off,SensorMode.Percent)); dictionary.Add("NXT Light Inactive Raw", new NXTLightSensor(LightMode.Off,SensorMode.Raw)); dictionary.Add("NXT Sonar Inch", new Sonar(SonarMode.CentiInch)); dictionary.Add("NXT Sonar Metric", new Sonar(SonarMode.Centimeter)); dictionary.Add("NXT Sound dBA",new NXTSoundSensor(SoundMode.SoundDBA)); dictionary.Add("NXT Sound dB", new NXTSoundSensor(SoundMode.SoundDB)); dictionary.Add("NXT/RCX Touch Bool", new TouchSensor(SensorMode.Bool)); dictionary.Add("NXT/RCX Touch Raw", new TouchSensor(SensorMode.Raw)); dictionary.Add("RCX Angle", new RCXRotationSensor()); dictionary.Add("RCX Light Pct", new RCXLightSensor(SensorMode.Percent)); dictionary.Add("RCX Light Raw", new RCXLightSensor(SensorMode.Raw)); dictionary.Add("RCX Temp Celcius", new RCXTemperatureSensor(TemperatureMode.Celsius)); dictionary.Add("RCX Temp Fahrenheit", new RCXTemperatureSensor(TemperatureMode.Fahrenheit)); return dictionary; } } } #endregion //Sensor #region No Sensor /// <summary> /// When a sensor is not connected use the class to minimize power consumption /// </summary> public class NoSensor: Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NoSensor"/> class. /// </summary> public NoSensor(): base (SensorType.NoSensor, SensorMode.Raw) { } } #endregion #region No Sensor /// <summary> /// When a sensor analog sensor is connected /// </summary> public class CustomSensor: Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.CustomSensor"/> class using custom sensor type and raw mode /// </summary> public CustomSensor(): base (SensorType.Custom, SensorMode.Percent) { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.CustomSensor"/> class. /// </summary> /// <param name='type'> /// Sensor type /// </param> /// <param name='mode'> /// Sensor mode /// </param> public CustomSensor(SensorType type, SensorMode mode): base (type, mode) { } /// <summary> /// Read the sensor value /// </summary> public virtual int Read() { return GetScaledValue(); } } #endregion #region NXT 2.0 Color sensor /// <summary> /// Sensor modes when using a NXT 2.0 color sensor /// </summary> public enum ColorMode { #pragma warning disable Full = SensorType.ColorFull, Red = SensorType.ColorRed, Green = SensorType.ColorGreen, Blue = SensorType.ColorBlue, None = SensorType.ColorNone #pragma warning restore }; /// <summary> /// Colors that can be read from the NXT 2.0 color sensor /// </summary> public enum Color { #pragma warning disable Black = 0x01, Blue = 0x02, Green = 0x03, Yellow = 0x04, Red = 0x05, White = 0x06 #pragma warning restore }; /// <summary> /// NXT 2.0 color sensor. /// </summary> public class NXTColorSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class as a color sensor. /// </summary> public NXTColorSensor() : base ((SensorType)ColorMode.Full,SensorMode.Raw){ } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class as a light sensor. /// </summary> public NXTColorSensor(SensorMode mode) : base ((SensorType)ColorMode.Red,mode){ } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTColorSensor"/> class. /// </summary> /// <param name="colorMode">The color mode to use</param> /// <param name="mode">The sensor mode to use</param> public NXTColorSensor(ColorMode colorMode, SensorMode mode) : base ((SensorType)colorMode,mode){ } /// <summary> /// Set the sensor to be used as a color sensor /// </summary> public void UseAsColorSensor(){ UpdateTypeAndMode(SensorType.ColorFull,SensorMode.Raw); } /// <summary> /// Set the sensor to be used as a light sensor /// </summary> public void UseAsLightSensor(SensorMode mode = SensorMode.Percent){ UpdateTypeAndMode(SensorType.ColorRed,mode); } /// <summary> /// Gets or sets the light mode. /// </summary> /// <value> /// The light mode /// </value> public ColorMode ColorMode { set{ UpdateTypeAndMode((SensorType)value, Mode); } get{ return (ColorMode) Type; } } /// <summary> /// Gets or sets the sensor mode. /// </summary> /// <value> /// The sensor mode. /// </value> public SensorMode SensorMode { get{ return Mode; } set{ UpdateTypeAndMode(Type,value); } } /// <summary> /// Read the intensity of the reflected light /// </summary> public int ReadLightLevel() { return GetScaledValue(); } /// <summary> /// Reads the color value /// </summary> /// <returns>The color read from the sensor</returns> public Color ReadColor(){ Color color = Color.Black; try{ color = (Color) (GetScaledValue()); } catch(InvalidCastException){ } return color; } /// <summary> /// Reads the sensor value as a string. /// </summary> /// <returns>The value as a string</returns> public override string ReadAsString(){ if(Type == SensorType.ColorFull && Mode == SensorMode.Raw){ return ReadColor().ToString(); } return ReadLightLevel().ToString(); } public override int ReadAsInt() { if (Type == SensorType.ColorFull && Mode == SensorMode.Raw) { return (int) ReadColor(); } return ReadLightLevel(); } } #endregion #region NXT Light Sensor /// <summary> /// Sensor modes when using a light sensor /// </summary> public enum LightMode { #pragma warning disable Off = SensorType.LightInactive, On = SensorType.LightActive #pragma warning restore }; /// <summary> /// NXT light sensor. /// </summary> public class NXTLightSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class with active light. /// </summary> public NXTLightSensor() : base ((SensorType)LightMode.On,SensorMode.Percent){ } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class. /// </summary> /// <param name='lightMode'> /// Light sensor mode /// </param> public NXTLightSensor(LightMode lightMode) : base ((SensorType)lightMode, SensorMode.Percent){ } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTLightSensor"/> class. /// </summary> /// <param name='lightMode'> /// Light sensor mode /// </param> /// <param name='sensorMode'> /// Sensor mode. Raw, bool, percent... /// </param> public NXTLightSensor(LightMode lightMode, SensorMode sensorMode) : base ((SensorType)lightMode, sensorMode){ } /// <summary> /// Gets or sets the light mode. /// </summary> /// <value> /// The light mode /// </value> public LightMode LightMode { set{ UpdateTypeAndMode((SensorType)value, Mode); } get{ return (LightMode) Type; } } /// <summary> /// Gets or sets the sensor mode. /// </summary> /// <value> /// The sensor mode. /// </value> public SensorMode SensorMode { get{ return Mode; } set{ UpdateTypeAndMode(Type,value); } } /// <summary> /// Read the intensity of the reflected light /// </summary> public int ReadLightLevel() { return GetScaledValue(); } } #endregion #region RCX Light Sensor /// <summary> /// RCX light sensor. /// </summary> public class RCXLightSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXLightSensor"/> class. /// </summary> public RCXLightSensor() : base(SensorType.Reflection, SensorMode.Percent) {} /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXLightSensor"/> class. /// </summary> /// <param name='sensorMode'> /// Sensor mode. Raw, bool, percent... /// </param> public RCXLightSensor(SensorMode sensorMode) : base(SensorType.Reflection, sensorMode) {} /// <summary> /// Gets or sets the sensor mode. /// </summary> /// <value> /// The sensor mode. /// </value> public SensorMode SensorMode { get{ return Mode; } set{ UpdateTypeAndMode(Type,value); } } /// <summary> /// Read the intensity of the reflected light /// </summary> public int ReadLightLevel() { return GetScaledValue(); } } #endregion #region RCX Rotation Sensor /// <summary> /// RCX rotation sensor. /// </summary> public class RCXRotationSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXRotationSensor"/> class. /// </summary> public RCXRotationSensor() : base(SensorType.Angle, SensorMode.Angle) { } /// <summary> /// Read the rotation count /// </summary> public int ReadCount() { return GetScaledValue(); } } #endregion #region RCX Temperature Sensor /// <summary> /// Sensor mode when using a temperature sensor /// </summary> public enum TemperatureMode { /// <summary> /// Result is in celsius /// </summary> Celsius = SensorMode.Celsius, /// <summary> /// Result is in fahrenheit. /// </summary> Fahrenheit = SensorMode.Fahrenheit }; /// <summary> /// RCX temperature sensor. /// </summary> public class RCXTemperatureSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXTemperatureSensor"/> class as celsius /// </summary> public RCXTemperatureSensor() : base(SensorType.Temperature, (SensorMode)TemperatureMode.Celsius) { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXTemperatureSensor"/> class. /// </summary> /// <param name='temperatureMode'> /// Temperature mode /// </param> public RCXTemperatureSensor(TemperatureMode temperatureMode) : base(SensorType.Temperature, (SensorMode)temperatureMode) { } /// <summary> /// Gets or sets the temperature mode. /// </summary> /// <value> /// The temperature mode. /// </value> public TemperatureMode TemperatureMode{ get{return (TemperatureMode) Mode;} set { UpdateTypeAndMode(Type,(SensorMode)value); } } /// <summary> /// Read the temperature /// </summary> public int ReadTemperature() { return GetScaledValue(); } } #endregion #region NXT Sound Sensor /// <summary> /// Sensor mode when using a sound sensor /// </summary> public enum SoundMode { /// <summary> /// The sound level is measured in A-weighting decibel /// </summary> SoundDBA = SensorType.SoundDBA, /// <summary> /// The sound level is measured in decibel /// </summary> SoundDB = SensorType.SoundDB }; /// <summary> /// NXT sound sensor. /// </summary> public class NXTSoundSensor : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTSoundSensor"/> class in DBA mode. /// </summary> public NXTSoundSensor() : base((SensorType)SoundMode.SoundDBA, SensorMode.Percent) { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.NXTSoundSensor"/> class. /// </summary> /// <param name='soundMode'> /// Sound mode /// </param> public NXTSoundSensor(SoundMode soundMode) : base((SensorType)soundMode, SensorMode.Percent) { } /// <summary> /// Gets or sets the sound mode. /// </summary> /// <value> /// The sound mode. /// </value> public SoundMode SoundMode{ get{return (SoundMode) Type;} set { UpdateTypeAndMode((SensorType)value,Mode); } } /// <summary> /// Read the sound level /// </summary> public int ReadSoundLevel() { return GetScaledValue(); } } #endregion #region Touch Sensor /// <summary> /// Touch sensor. /// </summary> public class TouchSensor : CustomSensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.TouchSensor"/> class in bool mode /// </summary> public TouchSensor() : base(SensorType.Touch, SensorMode.Bool) { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.TouchSensor"/> class. /// </summary> /// <param name='sensorMode'> /// Sensor mode. Raw, bool, percent... /// </param> public TouchSensor(SensorMode sensorMode) : base(SensorType.Touch, sensorMode) { } /// <summary> /// Gets or sets the sensor mode. /// </summary> /// <value> /// The sensor mode. /// </value> public SensorMode SensorMode { get{ return Mode; } set{ UpdateTypeAndMode(Type,value); } } } #endregion #region HiTechnic gyro sensor /// <summary> /// HiTechnic gyro sensor /// </summary> public class HiTecGyro : Sensor { /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.HiTecGyro"/> class without offset /// </summary> public HiTecGyro() : base(SensorType.Custom , SensorMode.Raw) { Offset = 0; } /// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.HiTecGyro"/> class. /// </summary> /// <param name='offset'> /// Offset /// </param> public HiTecGyro(int offset) : base(SensorType.Custom , SensorMode.Raw) { Offset = offset; } /// <summary> /// Read angular acceleration /// </summary> public int ReadAngularAcceleration() { return GetRawValue()-Offset; } /// <summary> /// Reads the angular acceleration as a string. /// </summary> /// <returns> /// The value as a string. /// </returns> public override string ReadAsString() { return this.ReadAngularAcceleration().ToString() + " deg/sec"; } public override int ReadAsInt() { return this.ReadAngularAcceleration(); } /// <summary> /// Gets or sets the offset. /// </summary> /// <value> /// The offset. /// </value> public int Offset{get;set;} } #endregion }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using Tilde.Framework.Model; using Tilde.Framework.Model.ProjectHierarchy; using Tilde.Framework.View; using WeifenLuo.WinFormsUI.Docking; using System.Collections.ObjectModel; using Microsoft.Win32; namespace Tilde.Framework.Controller { public class ProjectClosingEventArgs { private Project m_project; private bool m_cancelled; private bool m_cancel; public ProjectClosingEventArgs(Project project, bool cancelled) { m_project = project; m_cancelled = cancelled; m_cancel = false; } public Project Project { get { return m_project; } } public bool Cancelled { get { return m_cancelled; } } public bool Cancel { get { return m_cancel; } set { m_cancel = value; } } } public class FindInFilesResultEventArgs { string m_file; int m_line; int m_startChar; int m_endChar; string m_message; public FindInFilesResultEventArgs(string file, int line, string message) { m_file = file; m_line = line; m_startChar = -1; m_endChar = -1; m_message = message; } public FindInFilesResultEventArgs(string file, int line, int startChar, int endChar, string message) { m_file = file; m_line = line; m_startChar = startChar; m_endChar = endChar; m_message = message; } public string File { get { return m_file; } } public int Line { get { return m_line; } } public int StartChar { get { return m_startChar; } } public int EndChar { get { return m_endChar; } } public string Message { get { return m_message; } } } public delegate void ProjectOpenedEventHandler(IManager sender, Project project); public delegate void ProjectClosingEventHandler(IManager sender, ProjectClosingEventArgs args); public delegate void ProjectClosedEventHandler(IManager sender); public delegate void ManagerDocumentOpenedEventHandler(IManager sender, Document document); public delegate void ManagerDocumentClosedEventHandler(IManager sender, Document document); public delegate void ActiveDocumentChangedEventHandler(IManager sender, Document view); public delegate void SelectionChangedEventHandler(IManager sender, object [] selection); public delegate void FindInFilesStartedEventHandler(object sender, string message); public delegate void FindInFilesResultEventHandler(object sender, FindInFilesResultEventArgs args); public delegate void FindInFilesStoppedEventHandler(object sender, string message); public delegate void GoToNextLocationEventHandler(IManager sender, ref bool consumed); public delegate void GoToPreviousLocationEventHandler(IManager sender, ref bool consumed); public interface IManager { event PropertyChangeEventHandler PropertyChange; event ProjectOpenedEventHandler ProjectOpened; event ProjectClosingEventHandler ProjectClosing; event ProjectClosedEventHandler ProjectClosed; event ManagerDocumentOpenedEventHandler DocumentOpened; event ManagerDocumentClosedEventHandler DocumentClosed; event ActiveDocumentChangedEventHandler ActiveDocumentChanged; event SelectionChangedEventHandler SelectionChanged; event FindInFilesStartedEventHandler FindInFilesStarted; event FindInFilesResultEventHandler FindInFilesResult; event FindInFilesStoppedEventHandler FindInFilesStopped; event GoToNextLocationEventHandler GoToNextLocation; event GoToPreviousLocationEventHandler GoToPreviousLocation; RegistryKey RegistryRoot { get; } PluginCollection Plugins { get; } Project Project { get; } Form MainWindow { get; set; } Document ActiveDocument { get; set; } DocumentView ActiveView { get; } DockPanel DockPanel { get; } FileWatcher FileWatcher { get; } OptionsManager OptionsManager { get; } ApplicationOptions ApplicationOptions { get; } bool IsClosing { get; } ReadOnlyCollection<Document> Documents { get; } ReadOnlyCollection<DocumentView> DocumentViews { get; } object SelectedObject { get; set; } object[] SelectedObjects { get; set; } void AddToMenuStrip(ToolStripItemCollection toolStripItemCollection); void AddToStatusStrip(ToolStripItemCollection toolStripItemCollection); void AddToolStrip(ToolStrip toolStrip, DockStyle side, int row); void SetStatusMessage(String message, float duration); void SetProgressBar(int progress); void StartProgressBarMarquee(); void StopProgressBarMarquee(); void FlashMainWindow(); bool LoadProject(string fileName); bool NewProject(Type projType); bool CloseProject(bool force); Document CreateDocument(string fileName); Document CreateDocument(string fileName, Type docType); Document CreateDocument(string fileName, Type docType, Stream stream); Document CreateDocument(string fileName, Type docType, Stream stream, object[] args); Document OpenDocument(DocumentItem docItem); Document OpenDocument(string fileName); Document OpenDocument(string fileName, Type docType); Document OpenDocument(string fileName, Type docType, object[] args); Document FindOpenDocument(string fileName); DocumentView ShowDocument(DocumentItem docItem); DocumentView ShowDocument(string fileName); DocumentView ShowDocument(Document doc); bool CloseDocument(Document doc, bool force); bool CloseAllDocuments(bool force); int SaveAllDocuments(); Type FindFileDocumentType(string docName); void ShowMessages(string type); void AddMessage(string type, string message); IPlugin GetPlugin(Type type); ToolWindow GetToolWindow(Type type); List<Type> GetPluginImplementations(Type interfaceType); int Execute(string logtype, string args); int Execute(string logtype, string args, StringBuilder output); void OnFindInFilesStarted(object sender, string message); void OnFindInFilesResult(object sender, FindInFilesResultEventArgs args); void OnFindInFilesStopped(object sender, string message); void OnGoToNextLocation(); void OnGoToPreviousLocation(); } }
namespace SocialNetwork.Core.Migrations { using System; using System.Data.Entity.Migrations; public partial class db_migration : DbMigration { public override void Up() { CreateTable( "dbo.FriendShips", c => new { Id = c.Int(nullable: false, identity: true), RequestDate = c.DateTime(nullable: false), Message = c.String(), User1Id = c.Int(nullable: false), User2Id = c.Int(nullable: false), IsConfirmed = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.User1Id) .ForeignKey("dbo.Users", t => t.User2Id) .Index(t => t.User1Id) .Index(t => t.User2Id); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), Email = c.String(nullable: false, maxLength: 50), Password = c.String(nullable: false, maxLength: 50), FirstName = c.String(nullable: false, maxLength: 50), LastName = c.String(nullable: false, maxLength: 50), MiddleName = c.String(maxLength: 50), Birthday = c.DateTime(nullable: false), Avatar = c.Binary(), Mobile = c.String(maxLength: 20), Sex = c.Boolean(nullable: false), Website = c.String(maxLength: 100), Skype = c.String(maxLength: 50), CurrentCity = c.String(maxLength: 50, fixedLength: true), Activies = c.String(maxLength: 1000), Interests = c.String(maxLength: 1000), FavoriteMusic = c.String(maxLength: 1000), FavoriteMovies = c.String(maxLength: 1000), FavoriteBooks = c.String(maxLength: 1000), FavoriteGames = c.String(maxLength: 1000), FavoriteQuotes = c.String(maxLength: 1000), AboutMe = c.String(maxLength: 1000), IsBlocked = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Messages", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(maxLength: 50), MsgText = c.String(nullable: false), PostedDate = c.DateTime(nullable: false), IsRead = c.Boolean(nullable: false), User1Id = c.Int(nullable: false), User2Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.User1Id) .ForeignKey("dbo.Users", t => t.User2Id) .Index(t => t.User1Id) .Index(t => t.User2Id); CreateTable( "dbo.UserRole", c => new { Id = c.Int(nullable: false, identity: true), RoleId = c.Int(nullable: false), UserId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.Roles", c => new { Id = c.Int(nullable: false, identity: true), RoleName = c.String(nullable: false, maxLength: 256), Description = c.String(maxLength: 256), }) .PrimaryKey(t => t.Id); Sql(@" CREATE TRIGGER [DELETE_Users] ON [dbo].[Users] INSTEAD OF DELETE AS BEGIN SET NOCOUNT ON; DELETE FROM [Messages] WHERE User1Id IN (SELECT Id FROM DELETED) DELETE FROM [Messages] WHERE User2Id IN (SELECT Id FROM DELETED) DELETE FROM [FriendShips] WHERE User1Id IN (SELECT Id FROM DELETED) DELETE FROM [FriendShips] WHERE User2Id IN (SELECT Id FROM DELETED) DELETE FROM [Users] WHERE Id IN (SELECT Id FROM DELETED) END"); Sql(@" CREATE PROCEDURE [dbo].[DropAllTables] AS BEGIN IF object_id('[dbo].[UserRole]','U') IS NOT NULL BEGIN ALTER TABLE [dbo].[UserRole] DROP CONSTRAINT [FK_UserRole_ToRole] ALTER TABLE [dbo].[UserRole] DROP CONSTRAINT [FK_UserRole_ToUser] DROP TABLE [dbo].[UserRole] END IF object_id('[dbo].[Roles]','U') IS NOT NULL BEGIN DROP TABLE [dbo].[Roles] END IF object_id('[dbo].[Messages]','U') IS NOT NULL BEGIN ALTER TABLE [dbo].[Messages] DROP CONSTRAINT [FK_Messages_ToUsers1] ALTER TABLE [dbo].[Messages] DROP CONSTRAINT [FK_Messages_ToUsers2] DROP TABLE [dbo].[Messages] END IF object_id('[dbo].[FriendShips]','U') IS NOT NULL BEGIN ALTER TABLE [dbo].[FriendShips] DROP CONSTRAINT [FK_FriendShips_ToUsers1] ALTER TABLE [dbo].[FriendShips] DROP CONSTRAINT [FK_FriendShips_ToUsers2] DROP TABLE [dbo].[FriendShips] END IF object_id('[dbo].[Users]','U') IS NOT NULL BEGIN DROP TABLE [dbo].[Users] END END"); Sql(@" IF NOT EXISTS (SELECT * FROM [dbo].[Roles]) BEGIN SET IDENTITY_INSERT [dbo].[Roles] ON INSERT INTO [dbo].[Roles] ([Id], [RoleName], [Description]) VALUES (1, N'admin', N'This is admin.') INSERT INTO [dbo].[Roles] ([Id], [RoleName], [Description]) VALUES (2, N'user', N'This is user.') SET IDENTITY_INSERT [dbo].[Roles] OFF END"); Sql(@" IF NOT EXISTS (SELECT * FROM [dbo].[Users]) BEGIN insert into [dbo].[Users] ([Email], [Password], [FirstName], [LastName], [Birthday], [Sex], [IsBlocked]) values ('admin', '21232f297a57a5a743894a0e4a801fc3', 'admin', 'admin', '1900/01/01', 0, 0) insert into [dbo].[UserRole] ([UserId], [RoleId]) values ((select [Id] from [dbo].[Users] where email='admin'), (select [Id] from [dbo].[Roles] where RoleName='admin')) END"); Sql(@" CREATE TABLE [dbo].[ELMAH_Error] ( [ErrorId] UNIQUEIDENTIFIER NOT NULL, [Application] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Host] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Type] NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Source] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Message] NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [User] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [Sequence] INT IDENTITY (1, 1) NOT NULL, [AllXml] NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]"); Sql(@" ALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY]"); Sql(@" ALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT [DF_ELMAH_Error_ErrorId] DEFAULT (NEWID()) FOR [ErrorId]"); Sql(@" CREATE NONCLUSTERED INDEX [IX_ELMAH_Error_App_Time_Seq] ON [dbo].[ELMAH_Error] ( [Application] ASC, [TimeUtc] DESC, [Sequence] DESC ) ON [PRIMARY]"); Sql(@" CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml] ( @Application NVARCHAR(60), @ErrorId UNIQUEIDENTIFIER ) AS SET QUOTED_IDENTIFIER ON SET ANSI_NULLS ON SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @Application SET QUOTED_IDENTIFIER OFF SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_NULLS ON"); Sql(@" CREATE PROCEDURE [dbo].[ELMAH_GetErrorsXml] ( @Application NVARCHAR(60), @PageIndex INT = 0, @PageSize INT = 15, @TotalCount INT OUTPUT ) AS SET NOCOUNT ON DECLARE @FirstTimeUTC DATETIME DECLARE @FirstSequence INT DECLARE @StartRow INT DECLARE @StartRowIndex INT SELECT @TotalCount = COUNT(1) FROM [ELMAH_Error] WHERE [Application] = @Application -- Get the ID of the first error for the requested page SET @StartRowIndex = @PageIndex * @PageSize + 1 IF @StartRowIndex <= @TotalCount BEGIN SET ROWCOUNT @StartRowIndex SELECT @FirstTimeUTC = [TimeUtc], @FirstSequence = [Sequence] FROM [ELMAH_Error] WHERE [Application] = @Application ORDER BY [TimeUtc] DESC, [Sequence] DESC END ELSE BEGIN SET @PageSize = 0 END -- Now set the row count to the requested page size and get -- all records below it for the pertaining application. SET ROWCOUNT @PageSize SELECT errorId = [ErrorId], application = [Application], host = [Host], type = [Type], source = [Source], message = [Message], [user] = [User], statusCode = [StatusCode], time = CONVERT(VARCHAR(50), [TimeUtc], 126) + 'Z' FROM [ELMAH_Error] error WHERE [Application] = @Application AND [TimeUtc] <= @FirstTimeUTC AND [Sequence] <= @FirstSequence ORDER BY [TimeUtc] DESC, [Sequence] DESC FOR XML AUTO SET QUOTED_IDENTIFIER OFF SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_NULLS ON"); Sql(@" CREATE PROCEDURE [dbo].[ELMAH_LogError] ( @ErrorId UNIQUEIDENTIFIER, @Application NVARCHAR(60), @Host NVARCHAR(30), @Type NVARCHAR(100), @Source NVARCHAR(60), @Message NVARCHAR(500), @User NVARCHAR(50), @AllXml NTEXT, @StatusCode INT, @TimeUtc DATETIME ) AS SET NOCOUNT ON INSERT INTO [ELMAH_Error] ( [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [AllXml], [StatusCode], [TimeUtc] ) VALUES ( @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @AllXml, @StatusCode, @TimeUtc ) SET QUOTED_IDENTIFIER OFF SET ANSI_NULLS ON"); } public override void Down() { DropIndex("dbo.UserRole", new[] { "UserId" }); DropIndex("dbo.UserRole", new[] { "RoleId" }); DropIndex("dbo.Messages", new[] { "User2Id" }); DropIndex("dbo.Messages", new[] { "User1Id" }); DropIndex("dbo.FriendShips", new[] { "User2Id" }); DropIndex("dbo.FriendShips", new[] { "User1Id" }); DropForeignKey("dbo.UserRole", "UserId", "dbo.Users"); DropForeignKey("dbo.UserRole", "RoleId", "dbo.Roles"); DropForeignKey("dbo.Messages", "User2Id", "dbo.Users"); DropForeignKey("dbo.Messages", "User1Id", "dbo.Users"); DropForeignKey("dbo.FriendShips", "User2Id", "dbo.Users"); DropForeignKey("dbo.FriendShips", "User1Id", "dbo.Users"); DropTable("dbo.Roles"); DropTable("dbo.UserRole"); DropTable("dbo.Messages"); DropTable("dbo.Users"); DropTable("dbo.FriendShips"); /* TODO: Drop all procedures, triggers and elmah tables*/ } } }
using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using MonotonicAppendingInt64Buffer = Lucene.Net.Util.Packed.MonotonicAppendingInt64Buffer; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; /// <summary> /// <see cref="DocIdSet"/> implementation based on pfor-delta encoding. /// <para>This implementation is inspired from LinkedIn's Kamikaze /// (http://data.linkedin.com/opensource/kamikaze) and Daniel Lemire's JavaFastPFOR /// (https://github.com/lemire/JavaFastPFOR).</para> /// <para>On the contrary to the original PFOR paper, exceptions are encoded with /// FOR instead of Simple16.</para> /// </summary> public sealed class PForDeltaDocIdSet : DocIdSet { internal const int BLOCK_SIZE = 128; internal const int MAX_EXCEPTIONS = 24; // no more than 24 exceptions per block internal static readonly PackedInt32s.IDecoder[] DECODERS = new PackedInt32s.IDecoder[32]; internal static readonly int[] ITERATIONS = new int[32]; internal static readonly int[] BYTE_BLOCK_COUNTS = new int[32]; internal static readonly int MAX_BYTE_BLOCK_COUNT; internal static readonly MonotonicAppendingInt64Buffer SINGLE_ZERO_BUFFER = new MonotonicAppendingInt64Buffer(0, 64, PackedInt32s.COMPACT); internal static readonly PForDeltaDocIdSet EMPTY = new PForDeltaDocIdSet(null, 0, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER); internal static readonly int LAST_BLOCK = 1 << 5; // flag to indicate the last block internal static readonly int HAS_EXCEPTIONS = 1 << 6; internal static readonly int UNARY = 1 << 7; static PForDeltaDocIdSet() { SINGLE_ZERO_BUFFER.Add(0); SINGLE_ZERO_BUFFER.Freeze(); int maxByteBLockCount = 0; for (int i = 1; i < ITERATIONS.Length; ++i) { DECODERS[i] = PackedInt32s.GetDecoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, i); Debug.Assert(BLOCK_SIZE % DECODERS[i].ByteValueCount == 0); ITERATIONS[i] = BLOCK_SIZE / DECODERS[i].ByteValueCount; BYTE_BLOCK_COUNTS[i] = ITERATIONS[i] * DECODERS[i].ByteBlockCount; maxByteBLockCount = Math.Max(maxByteBLockCount, DECODERS[i].ByteBlockCount); } MAX_BYTE_BLOCK_COUNT = maxByteBLockCount; } /// <summary> /// A builder for <see cref="PForDeltaDocIdSet"/>. </summary> public class Builder { internal readonly GrowableByteArrayDataOutput data; internal readonly int[] buffer = new int[BLOCK_SIZE]; internal readonly int[] exceptionIndices = new int[BLOCK_SIZE]; internal readonly int[] exceptions = new int[BLOCK_SIZE]; internal int bufferSize; internal int previousDoc; internal int cardinality; internal int indexInterval; internal int numBlocks; // temporary variables used when compressing blocks internal readonly int[] freqs = new int[32]; internal int bitsPerValue; internal int numExceptions; internal int bitsPerException; /// <summary> /// Sole constructor. </summary> public Builder() { data = new GrowableByteArrayDataOutput(128); bufferSize = 0; previousDoc = -1; indexInterval = 2; cardinality = 0; numBlocks = 0; } /// <summary> /// Set the index interval. Every <paramref name="indexInterval"/>-th block will /// be stored in the index. Set to <see cref="int.MaxValue"/> to disable indexing. /// </summary> public virtual Builder SetIndexInterval(int indexInterval) { if (indexInterval < 1) { throw new System.ArgumentException("indexInterval must be >= 1"); } this.indexInterval = indexInterval; return this; } /// <summary> /// Add a document to this builder. Documents must be added in order. </summary> public virtual Builder Add(int doc) { if (doc <= previousDoc) { throw new System.ArgumentException("Doc IDs must be provided in order, but previousDoc=" + previousDoc + " and doc=" + doc); } buffer[bufferSize++] = doc - previousDoc - 1; if (bufferSize == BLOCK_SIZE) { EncodeBlock(); bufferSize = 0; } previousDoc = doc; ++cardinality; return this; } /// <summary> /// Convenience method to add the content of a <see cref="DocIdSetIterator"/> to this builder. </summary> public virtual Builder Add(DocIdSetIterator it) { for (int doc = it.NextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.NextDoc()) { Add(doc); } return this; } internal virtual void ComputeFreqs() { Arrays.Fill(freqs, 0); for (int i = 0; i < bufferSize; ++i) { ++freqs[32 - Number.NumberOfLeadingZeros(buffer[i])]; } } internal virtual int PforBlockSize(int bitsPerValue, int numExceptions, int bitsPerException) { PackedInt32s.Format format = PackedInt32s.Format.PACKED; long blockSize = 1 + format.ByteCount(PackedInt32s.VERSION_CURRENT, BLOCK_SIZE, bitsPerValue); // header: number of bits per value if (numExceptions > 0) { blockSize += 2 + numExceptions + format.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException); // indices of the exceptions - 2 additional bytes in case of exceptions: numExceptions and bitsPerException } if (bufferSize < BLOCK_SIZE) { blockSize += 1; // length of the block } return (int)blockSize; } internal virtual int UnaryBlockSize() { int deltaSum = 0; for (int i = 0; i < BLOCK_SIZE; ++i) { deltaSum += 1 + buffer[i]; } int blockSize = (int)((uint)(deltaSum + 0x07) >> 3); // round to the next byte ++blockSize; // header if (bufferSize < BLOCK_SIZE) { blockSize += 1; // length of the block } return blockSize; } internal virtual int ComputeOptimalNumberOfBits() { ComputeFreqs(); bitsPerValue = 31; numExceptions = 0; while (bitsPerValue > 0 && freqs[bitsPerValue] == 0) { --bitsPerValue; } int actualBitsPerValue = bitsPerValue; int blockSize = PforBlockSize(bitsPerValue, numExceptions, bitsPerException); // Now try different values for bitsPerValue and pick the best one for (int bitsPerValue = this.bitsPerValue - 1, numExceptions = freqs[this.bitsPerValue]; bitsPerValue >= 0 && numExceptions <= MAX_EXCEPTIONS; numExceptions += freqs[bitsPerValue--]) { int newBlockSize = PforBlockSize(bitsPerValue, numExceptions, actualBitsPerValue - bitsPerValue); if (newBlockSize < blockSize) { this.bitsPerValue = bitsPerValue; this.numExceptions = numExceptions; blockSize = newBlockSize; } } this.bitsPerException = actualBitsPerValue - bitsPerValue; Debug.Assert(bufferSize < BLOCK_SIZE || numExceptions < bufferSize); return blockSize; } internal virtual void PforEncode() { if (numExceptions > 0) { int mask = (1 << bitsPerValue) - 1; int ex = 0; for (int i = 0; i < bufferSize; ++i) { if (buffer[i] > mask) { exceptionIndices[ex] = i; exceptions[ex++] = (int)((uint)buffer[i] >> bitsPerValue); buffer[i] &= mask; } } Debug.Assert(ex == numExceptions); Arrays.Fill(exceptions, numExceptions, BLOCK_SIZE, 0); } if (bitsPerValue > 0) { PackedInt32s.IEncoder encoder = PackedInt32s.GetEncoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, bitsPerValue); int numIterations = ITERATIONS[bitsPerValue]; encoder.Encode(buffer, 0, data.Bytes, data.Length, numIterations); data.Length += encoder.ByteBlockCount * numIterations; } if (numExceptions > 0) { Debug.Assert(bitsPerException > 0); data.WriteByte((byte)(sbyte)numExceptions); data.WriteByte((byte)(sbyte)bitsPerException); PackedInt32s.IEncoder encoder = PackedInt32s.GetEncoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, bitsPerException); int numIterations = (numExceptions + encoder.ByteValueCount - 1) / encoder.ByteValueCount; encoder.Encode(exceptions, 0, data.Bytes, data.Length, numIterations); data.Length += (int)PackedInt32s.Format.PACKED.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException); for (int i = 0; i < numExceptions; ++i) { data.WriteByte((byte)(sbyte)exceptionIndices[i]); } } } internal virtual void UnaryEncode() { int current = 0; for (int i = 0, doc = -1; i < BLOCK_SIZE; ++i) { doc += 1 + buffer[i]; while (doc >= 8) { data.WriteByte((byte)(sbyte)current); current = 0; doc -= 8; } current |= 1 << doc; } if (current != 0) { data.WriteByte((byte)(sbyte)current); } } internal virtual void EncodeBlock() { int originalLength = data.Length; Arrays.Fill(buffer, bufferSize, BLOCK_SIZE, 0); int unaryBlockSize = UnaryBlockSize(); int pforBlockSize = ComputeOptimalNumberOfBits(); int blockSize; if (pforBlockSize <= unaryBlockSize) { // use pfor blockSize = pforBlockSize; data.Bytes = ArrayUtil.Grow(data.Bytes, data.Length + blockSize + MAX_BYTE_BLOCK_COUNT); int token = bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0; token |= bitsPerValue; if (numExceptions > 0) { token |= HAS_EXCEPTIONS; } data.WriteByte((byte)(sbyte)token); PforEncode(); } else { // use unary blockSize = unaryBlockSize; int token = UNARY | (bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0); data.WriteByte((byte)(sbyte)token); UnaryEncode(); } if (bufferSize < BLOCK_SIZE) { data.WriteByte((byte)(sbyte)bufferSize); } ++numBlocks; Debug.Assert(data.Length - originalLength == blockSize, (data.Length - originalLength) + " <> " + blockSize); } /// <summary> /// Build the <see cref="PForDeltaDocIdSet"/> instance. </summary> public virtual PForDeltaDocIdSet Build() { Debug.Assert(bufferSize < BLOCK_SIZE); if (cardinality == 0) { Debug.Assert(previousDoc == -1); return EMPTY; } EncodeBlock(); var dataArr = Arrays.CopyOf(data.Bytes, data.Length + MAX_BYTE_BLOCK_COUNT); int indexSize = (numBlocks - 1) / indexInterval + 1; MonotonicAppendingInt64Buffer docIDs, offsets; if (indexSize <= 1) { docIDs = offsets = SINGLE_ZERO_BUFFER; } else { const int pageSize = 128; int initialPageCount = (indexSize + pageSize - 1) / pageSize; docIDs = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT); offsets = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT); // Now build the index Iterator it = new Iterator(dataArr, cardinality, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER); for (int k = 0; k < indexSize; ++k) { docIDs.Add(it.DocID + 1); offsets.Add(it.offset); for (int i = 0; i < indexInterval; ++i) { it.SkipBlock(); if (it.DocID == DocIdSetIterator.NO_MORE_DOCS) { goto indexBreak; } } //indexContinue: ; } indexBreak: docIDs.Freeze(); offsets.Freeze(); } return new PForDeltaDocIdSet(dataArr, cardinality, indexInterval, docIDs, offsets); } } internal readonly byte[] data; internal readonly MonotonicAppendingInt64Buffer docIDs, offsets; // for the index internal readonly int cardinality, indexInterval; internal PForDeltaDocIdSet(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer docIDs, MonotonicAppendingInt64Buffer offsets) { this.data = data; this.cardinality = cardinality; this.indexInterval = indexInterval; this.docIDs = docIDs; this.offsets = offsets; } public override bool IsCacheable { get { return true; } } public override DocIdSetIterator GetIterator() { if (data == null) { return null; } else { return new Iterator(data, cardinality, indexInterval, docIDs, offsets); } } internal class Iterator : DocIdSetIterator { // index internal readonly int indexInterval; internal readonly MonotonicAppendingInt64Buffer docIDs, offsets; internal readonly int cardinality; internal readonly byte[] data; internal int offset; // offset in data internal readonly int[] nextDocs; internal int i; // index in nextDeltas internal readonly int[] nextExceptions; internal int blockIdx; internal int docID; internal Iterator(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer docIDs, MonotonicAppendingInt64Buffer offsets) { this.data = data; this.cardinality = cardinality; this.indexInterval = indexInterval; this.docIDs = docIDs; this.offsets = offsets; offset = 0; nextDocs = new int[BLOCK_SIZE]; Arrays.Fill(nextDocs, -1); i = BLOCK_SIZE; nextExceptions = new int[BLOCK_SIZE]; blockIdx = -1; docID = -1; } public override int DocID { get { return docID; } } internal virtual void PforDecompress(byte token) { int bitsPerValue = token & 0x1F; if (bitsPerValue == 0) { Arrays.Fill(nextDocs, 0); } else { DECODERS[bitsPerValue].Decode(data, offset, nextDocs, 0, ITERATIONS[bitsPerValue]); offset += BYTE_BLOCK_COUNTS[bitsPerValue]; } if ((token & HAS_EXCEPTIONS) != 0) { // there are exceptions int numExceptions = data[offset++]; int bitsPerException = data[offset++]; int numIterations = (numExceptions + DECODERS[bitsPerException].ByteValueCount - 1) / DECODERS[bitsPerException].ByteValueCount; DECODERS[bitsPerException].Decode(data, offset, nextExceptions, 0, numIterations); offset += (int)PackedInt32s.Format.PACKED.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException); for (int i = 0; i < numExceptions; ++i) { nextDocs[data[offset++]] |= nextExceptions[i] << bitsPerValue; } } for (int previousDoc = docID, i = 0; i < BLOCK_SIZE; ++i) { int doc = previousDoc + 1 + nextDocs[i]; previousDoc = nextDocs[i] = doc; } } internal virtual void UnaryDecompress(byte token) { Debug.Assert((token & HAS_EXCEPTIONS) == 0); int docID = this.docID; for (int i = 0; i < BLOCK_SIZE; ) { var b = data[offset++]; for (int bitList = BitUtil.BitList(b); bitList != 0; ++i, bitList = (int)((uint)bitList >> 4)) { nextDocs[i] = docID + (bitList & 0x0F); } docID += 8; } } internal virtual void DecompressBlock() { var token = data[offset++]; if ((token & UNARY) != 0) { UnaryDecompress(token); } else { PforDecompress(token); } if ((token & LAST_BLOCK) != 0) { int blockSize = data[offset++]; Arrays.Fill(nextDocs, blockSize, BLOCK_SIZE, NO_MORE_DOCS); } ++blockIdx; } internal virtual void SkipBlock() { Debug.Assert(i == BLOCK_SIZE); DecompressBlock(); docID = nextDocs[BLOCK_SIZE - 1]; } public override int NextDoc() { if (i == BLOCK_SIZE) { DecompressBlock(); i = 0; } return docID = nextDocs[i++]; } internal virtual int ForwardBinarySearch(int target) { // advance forward and double the window at each step int indexSize = (int)docIDs.Count; int lo = Math.Max(blockIdx / indexInterval, 0), hi = lo + 1; Debug.Assert(blockIdx == -1 || docIDs.Get(lo) <= docID); Debug.Assert(lo + 1 == docIDs.Count || docIDs.Get(lo + 1) > docID); while (true) { if (hi >= indexSize) { hi = indexSize - 1; break; } else if (docIDs.Get(hi) >= target) { break; } int newLo = hi; hi += (hi - lo) << 1; lo = newLo; } // we found a window containing our target, let's binary search now while (lo <= hi) { int mid = (int)((uint)(lo + hi) >> 1); int midDocID = (int)docIDs.Get(mid); if (midDocID <= target) { lo = mid + 1; } else { hi = mid - 1; } } Debug.Assert(docIDs.Get(hi) <= target); Debug.Assert(hi + 1 == docIDs.Count || docIDs.Get(hi + 1) > target); return hi; } public override int Advance(int target) { Debug.Assert(target > docID); if (nextDocs[BLOCK_SIZE - 1] < target) { // not in the next block, now use the index int index = ForwardBinarySearch(target); int offset = (int)offsets.Get(index); if (offset > this.offset) { this.offset = offset; docID = (int)docIDs.Get(index) - 1; blockIdx = index * indexInterval - 1; while (true) { DecompressBlock(); if (nextDocs[BLOCK_SIZE - 1] >= target) { break; } docID = nextDocs[BLOCK_SIZE - 1]; } i = 0; } } return SlowAdvance(target); } public override long GetCost() { return cardinality; } } /// <summary> /// Return the number of documents in this <see cref="DocIdSet"/> in constant time. </summary> public int Cardinality() { return cardinality; } /// <summary> /// Return the memory usage of this instance. </summary> public long RamBytesUsed() { return RamUsageEstimator.AlignObjectSize(3 * RamUsageEstimator.NUM_BYTES_OBJECT_REF) + docIDs.RamBytesUsed() + offsets.RamBytesUsed(); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- /* ================================================================================ The DOFPostEffect API ================================================================================ DOFPostEffect::setFocalDist( %dist ) @summary This method is for manually controlling the focus distance. It will have no effect if auto focus is currently enabled. Makes use of the parameters set by setFocusParams. @param dist float distance in meters -------------------------------------------------------------------------------- DOFPostEffect::setAutoFocus( %enabled ) @summary This method sets auto focus enabled or disabled. Makes use of the parameters set by setFocusParams. When auto focus is enabled it determines the focal depth by performing a raycast at the screen-center. @param enabled bool -------------------------------------------------------------------------------- DOFPostEffect::setFocusParams( %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope ) Set the parameters that control how the near and far equations are calculated from the focal distance. If you are not using auto focus you will need to call setFocusParams PRIOR to calling setFocalDist. @param nearBlurMax float between 0.0 and 1.0 The max allowed value of near blur. @param farBlurMax float between 0.0 and 1.0 The max allowed value of far blur. @param minRange/maxRange float in meters The distance range around the focal distance that remains in focus is a lerp between the min/maxRange using the normalized focal distance as the parameter. The point is to allow the focal range to expand as you focus farther away since this is visually appealing. Note: since min/maxRange are lerped by the "normalized" focal distance it is dependant on the visible distance set in your level. @param nearSlope float less than zero The slope of the near equation. A small number causes bluriness to increase gradually at distances closer than the focal distance. A large number causes bluriness to increase quickly. @param farSlope float greater than zero The slope of the far equation. A small number causes bluriness to increase gradually at distances farther than the focal distance. A large number causes bluriness to increase quickly. Note: To rephrase, the min/maxRange parameters control how much area around the focal distance is completely in focus where the near/farSlope parameters control how quickly or slowly bluriness increases at distances outside of that range. ================================================================================ Examples ================================================================================ Example1: Turn on DOF while zoomed in with a weapon. NOTE: These are not real callbacks! Hook these up to your code where appropriate! function onSniperZoom() { // Parameterize how you want DOF to look. DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 ); // Turn on auto focus DOFPostEffect.setAutoFocus( true ); // Turn on the PostEffect DOFPostEffect.enable(); } function onSniperUnzoom() { // Turn off the PostEffect DOFPostEffect.disable(); } Example2: Manually control DOF with the mouse wheel. // Somewhere on startup... // Parameterize how you want DOF to look. DOFPostEffect.setFocusParams( 0.3, 0.3, 50, 500, -5, 5 ); // Turn off auto focus DOFPostEffect.setAutoFocus( false ); // Turn on the PostEffect DOFPostEffect.enable(); NOTE: These are not real callbacks! Hook these up to your code where appropriate! function onMouseWheelUp() { // Since setFocalDist is really just a wrapper to assign to the focalDist // dynamic field we can shortcut and increment it directly. DOFPostEffect.focalDist += 8; } function onMouseWheelDown() { DOFPostEffect.focalDist -= 8; } */ /// This method is for manually controlling the focal distance. It will have no /// effect if auto focus is currently enabled. Makes use of the parameters set by /// setFocusParams. function DOFPostEffect::setFocalDist( %this, %dist ) { %this.focalDist = %dist; } /// This method sets auto focus enabled or disabled. Makes use of the parameters set /// by setFocusParams. When auto focus is enabled it determine the focal depth /// by performing a raycast at the screen-center. function DOFPostEffect::setAutoFocus( %this, %enabled ) { %this.autoFocusEnabled = %enabled; } /// Set the parameters that control how the near and far equations are calculated /// from the focal distance. If you are not using auto focus you will need to call /// setFocusParams PRIOR to calling setFocalDist. function DOFPostEffect::setFocusParams( %this, %nearBlurMax, %farBlurMax, %minRange, %maxRange, %nearSlope, %farSlope ) { %this.nearBlurMax = %nearBlurMax; %this.farBlurMax = %farBlurMax; %this.minRange = %minRange; %this.maxRange = %maxRange; %this.nearSlope = %nearSlope; %this.farSlope = %farSlope; } /* More information... This DOF technique is based on this paper: http://http.developer.nvidia.com/GPUGems3/gpugems3_ch28.html ================================================================================ 1. Overview of how we represent "Depth of Field" ================================================================================ DOF is expressed as an amount of bluriness per pixel according to its depth. We represented this by a piecewise linear curve depicted below. Note: we also refer to "bluriness" as CoC ( circle of confusion ) which is the term used in the basis paper and in photography. X-axis (depth) x = 0.0----------------------------------------------x = 1.0 Y-axis (bluriness) y = 1.0 | | ____(x1,y1) (x4,y4)____ | (ns,nb)\ <--Line1 line2---> /(fe,fb) | \ / | \(x2,y2) (x3,y3)/ | (ne,0)------(fs,0) y = 0.0 I have labeled the "corners" of this graph with (Xn,Yn) to illustrate that this is in fact a collection of line segments where the x/y of each point corresponds to the key below. key: ns - (n)ear blur (s)tart distance nb - (n)ear (b)lur amount (max value) ne - (n)ear blur (e)nd distance fs - (f)ar blur (s)tart distance fe - (f)ar blur (e)nd distance fb - (f)ar (b)lur amount (max value) Of greatest importance in this graph is Line1 and Line2. Where... L1 { (x1,y1), (x2,y2) } L2 { (x3,y3), (x4,y4) } Line one represents the amount of "near" blur given a pixels depth and line two represents the amount of "far" blur at that depth. Both these equations are evaluated for each pixel and then the larger of the two is kept. Also the output blur (for each equation) is clamped between 0 and its maximum allowable value. Therefore, to specify a DOF "qualify" you need to specify the near-blur-line, far-blur-line, and maximum near and far blur value. ================================================================================ 2. Abstracting a "focal depth" ================================================================================ Although the shader(s) work in terms of a near and far equation it is more useful to express DOF as an adjustable focal depth and derive the other parameters "under the hood". Given a maximum near/far blur amount and a near/far slope we can calculate the near/far equations for any focal depth. We extend this to also support a range of depth around the focal depth that is also in focus and for that range to shrink or grow as the focal depth moves closer or farther. Keep in mind this is only one implementation and depending on the effect you desire you may which to express the relationship between focal depth and the shader paramaters different. */ //----------------------------------------------------------------------------- // GFXStateBlockData / ShaderData //----------------------------------------------------------------------------- singleton GFXStateBlockData( PFX_DefaultDOFStateBlock ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampPoint; samplerStates[1] = SamplerClampPoint; }; singleton GFXStateBlockData( PFX_DOFCalcCoCStateBlock ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampLinear; samplerStates[1] = SamplerClampLinear; }; singleton GFXStateBlockData( PFX_DOFDownSampleStateBlock ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampLinear; samplerStates[1] = SamplerClampPoint; }; singleton GFXStateBlockData( PFX_DOFBlurStateBlock ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampLinear; }; singleton GFXStateBlockData( PFX_DOFFinalStateBlock ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampLinear; samplerStates[1] = SamplerClampLinear; samplerStates[2] = SamplerClampLinear; samplerStates[3] = SamplerClampPoint; blendDefined = true; blendEnable = true; blendDest = GFXBlendInvSrcAlpha; blendSrc = GFXBlendOne; }; singleton ShaderData( PFX_DOFDownSampleShader ) { DXVertexShaderFile = "shaders/common/postFx/dof/DOF_DownSample_V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/dof/DOF_DownSample_P.hlsl"; pixVersion = 3.0; }; singleton ShaderData( PFX_DOFBlurYShader ) { DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Gausian_V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Gausian_P.hlsl"; pixVersion = 2.0; defines = "BLUR_DIR=float2(0.0,1.0)"; }; singleton ShaderData( PFX_DOFBlurXShader : PFX_DOFBlurYShader ) { defines = "BLUR_DIR=float2(1.0,0.0)"; }; singleton ShaderData( PFX_DOFCalcCoCShader ) { DXVertexShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl"; pixVersion = 3.0; }; singleton ShaderData( PFX_DOFSmallBlurShader ) { DXVertexShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl"; pixVersion = 3.0; }; singleton ShaderData( PFX_DOFFinalShader ) { DXVertexShaderFile = "shaders/common/postFx/dof/DOF_Final_V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/dof/DOF_Final_P.hlsl"; pixVersion = 3.0; }; //----------------------------------------------------------------------------- // PostEffects //----------------------------------------------------------------------------- function DOFPostEffect::onAdd( %this ) { // The weighted distribution of CoC value to the three blur textures // in the order small, medium, large. Most likely you will not need to // change this value. %this.setLerpDist( 0.2, 0.3, 0.5 ); // Fill out some default values but DOF really should not be turned on // without actually specifying your own parameters! %this.autoFocusEnabled = false; %this.focalDist = 0.0; %this.nearBlurMax = 0.5; %this.farBlurMax = 0.5; %this.minRange = 50; %this.maxRange = 500; %this.nearSlope = -5.0; %this.farSlope = 5.0; } function DOFPostEffect::setLerpDist( %this, %d0, %d1, %d2 ) { %this.lerpScale = -1.0 / %d0 SPC -1.0 / %d1 SPC -1.0 / %d2 SPC 1.0 / %d2; %this.lerpBias = 1.0 SPC ( 1.0 - %d2 ) / %d1 SPC 1.0 / %d2 SPC ( %d2 - 1.0 ) / %d2; } singleton PostEffect( DOFPostEffect ) { renderTime = "PFXAfterBin"; renderBin = "GlowBin"; renderPriority = 0.1; shader = PFX_DOFDownSampleShader; stateBlock = PFX_DOFDownSampleStateBlock; texture[0] = "$backBuffer"; texture[1] = "#prepass"; target = "#shrunk"; targetScale = "0.25 0.25"; isEnabled = false; }; singleton PostEffect( DOFBlurY ) { shader = PFX_DOFBlurYShader; stateBlock = PFX_DOFBlurStateBlock; texture[0] = "#shrunk"; target = "$outTex"; }; DOFPostEffect.add( DOFBlurY ); singleton PostEffect( DOFBlurX ) { shader = PFX_DOFBlurXShader; stateBlock = PFX_DOFBlurStateBlock; texture[0] = "$inTex"; target = "#largeBlur"; }; DOFPostEffect.add( DOFBlurX ); singleton PostEffect( DOFCalcCoC ) { shader = PFX_DOFCalcCoCShader; stateBlock = PFX_DOFCalcCoCStateBlock; texture[0] = "#shrunk"; texture[1] = "#largeBlur"; target = "$outTex"; }; DOFPostEffect.add( DOFCalcCoc ); singleton PostEffect( DOFSmallBlur ) { shader = PFX_DOFSmallBlurShader; stateBlock = PFX_DefaultDOFStateBlock; texture[0] = "$inTex"; target = "$outTex"; }; DOFPostEffect.add( DOFSmallBlur ); singleton PostEffect( DOFFinalPFX ) { shader = PFX_DOFFinalShader; stateBlock = PFX_DOFFinalStateBlock; texture[0] = "$backBuffer"; texture[1] = "$inTex"; texture[2] = "#largeBlur"; texture[3] = "#prepass"; target = "$backBuffer"; }; DOFPostEffect.add( DOFFinalPFX ); //----------------------------------------------------------------------------- // Scripts //----------------------------------------------------------------------------- function DOFPostEffect::setShaderConsts( %this ) { if ( %this.autoFocusEnabled ) %this.autoFocus(); %fd = %this.focalDist / $Param::FarDist; %range = mLerp( %this.minRange, %this.maxRange, %fd ) / $Param::FarDist * 0.5; // We work in "depth" space rather than real-world units for the // rest of this method... // Given the focal distance and the range around it we want in focus // we can determine the near-end-distance and far-start-distance %ned = getMax( %fd - %range, 0.0 ); %fsd = getMin( %fd + %range, 1.0 ); // near slope %nsl = %this.nearSlope; // Given slope of near blur equation and the near end dist and amount (x2,y2) // solve for the y-intercept // y = mx + b // so... // y - mx = b %b = 0.0 - %nsl * %ned; %eqNear = %nsl SPC %b SPC 0.0; // Do the same for the far blur equation... %fsl = %this.farSlope; %b = 0.0 - %fsl * %fsd; %eqFar = %fsl SPC %b SPC 1.0; %this.setShaderConst( "$dofEqWorld", %eqNear ); DOFFinalPFX.setShaderConst( "$dofEqFar", %eqFar ); %this.setShaderConst( "$maxWorldCoC", %this.nearBlurMax ); DOFFinalPFX.setShaderConst( "$maxFarCoC", %this.farBlurMax ); DOFFinalPFX.setShaderConst( "$dofLerpScale", %this.lerpScale ); DOFFinalPFX.setShaderConst( "$dofLerpBias", %this.lerpBias ); } function DOFPostEffect::autoFocus( %this ) { if ( !isObject( ServerConnection ) || !isObject( ServerConnection.getCameraObject() ) ) { return; } %mask = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType; %control = ServerConnection.getCameraObject(); %fvec = %control.getEyeVector(); %start = %control.getEyePoint(); %end = VectorAdd( %start, VectorScale( %fvec, $Param::FarDist ) ); // Use the client container for this ray cast. %result = containerRayCast( %start, %end, %mask, %control, true ); %hitPos = getWords( %result, 1, 3 ); if ( %hitPos $= "" ) %focDist = $Param::FarDist; else %focDist = VectorDist( %hitPos, %start ); // For debuging //$DOF::debug_dist = %focDist; //$DOF::debug_depth = %focDist / $Param::FarDist; //echo( "F: " @ %focDist SPC "D: " @ %delta ); %this.focalDist = %focDist; } // For debugging /* function reloadDOF() { exec( "./dof.cs" ); DOFPostEffect.reload(); DOFPostEffect.disable(); DOFPostEffect.enable(); } function dofMetricsCallback() { return " | DOF |" @ " Dist: " @ $DOF::debug_dist @ " Depth: " @ $DOF::debug_depth; } */
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum EAxisState { GreaterThan, LessThan } [System.Serializable] public struct InputMapping { [Tooltip("Name of the button when referred to in the script. The action.")] public string name; [Tooltip("Default key for the action. Use the Unity KeyCode name. (If KeyCode.W enter W)\nIf an Axis, the positive key. (For keyboard control)")] public string positiveKeyName; [Tooltip("If an Axis, the negative key. (For keyboard control)")] public string negativeKeyName; [Tooltip("Default joypad button for the action. Use b.buttonName (same name as entered in Unity's input manager) to use a joystick button. Use a.axisName (same name as entered in Unity's input manager) to use a joystick axis.")] public string buttonName; [Tooltip("Is positive state greater or less than 0? (For joypad control)\nCan be used with GetButton with an axis Down = LeftStickVertical(LessThan)")] public EAxisState axisPositiveState; [Tooltip("Does this action use an axis.")] public bool isAxis; private bool m_isPressed; public bool IsPressed { get { return m_isPressed; } } public void Press() { m_isPressed = true; } public void UnPress() { m_isPressed = false; } } public class InputManager : Singleton<InputManager> { [Header("Input Mappings")] [SerializeField, Tooltip("The inputs that are needed for the game.")] private InputMapping[] m_inputMappings; public InputMapping[] mappings { get; private set; } private Dictionary<string, InputMapping> m_inputs = new Dictionary<string, InputMapping>(); [Header("Controller Input Names")] [SerializeField, Tooltip("All the button names from Unity's Input Manager.")] private string[] m_controllerButtonNames; [SerializeField, Tooltip("All the axis names from Unity's Input Manager.")] private string[] m_controllerAxisNames; private bool m_reassignInput = false; private bool m_reassignAxis = false; private bool m_reassigningPositive = true; private string m_inputToReassign = ""; private bool m_reassigningKeys = false; [SerializeField, Tooltip("Time to waitbetween selecting to reassign and actually reassigning.")] private float m_reasignDelay = 1.0f; private float m_reasignWaitTime = 0; void Start () { for(int i = 0; i < m_inputMappings.Length; i++) { m_inputs.Add(m_inputMappings[i].name, m_inputMappings[i]); // Add inputs to the dictionary } } void Update () { if(m_reassignInput || m_reassignAxis) // If an input is being reassigned { if (m_reasignWaitTime > m_reasignDelay) DetectNewInput(); else m_reasignWaitTime += Time.deltaTime; } } #region Input Reassigning public void UI_ReassignInput(string inputNameAndDevice) { if (m_reassignInput || m_reassignAxis) return; string[] newInput = inputNameAndDevice.Split(' '); m_inputToReassign = newInput[0]; switch (newInput[1]) { case "Keyboard": m_reassigningKeys = true; break; case "Controller": m_reassigningKeys = false; break; default: Debug.LogError("Unknown Device. [UI_ReassignInput], InputManager"); break; } m_reassignInput = true; m_reasignWaitTime = 0; FindObjectOfType<MenuManager>().isActive = false; } public void UI_ReasignAxis(string inputNameAndStateAndDevice) { if (m_reassignInput || m_reassignAxis) return; string[] newInput = inputNameAndStateAndDevice.Split(' '); m_inputToReassign = newInput[0]; switch(newInput[1]) { case "False": m_reassigningPositive = false; break; case "True": m_reassigningPositive = true; break; default: Debug.LogError("Error Reading 'State'. [UI_ReasignAxis], InputManager"); break; } switch(newInput[2]) { case "Keyboard": m_reassigningKeys = true; break; case "Controller": m_reassigningKeys = false; break; default: Debug.LogError("Unknown Device. [UI_ReasignAxis], InputManager"); break; } m_reassignAxis = true; m_reasignWaitTime = 0; FindObjectOfType<MenuManager>().isActive = false; } public string UI_GetInputName(string inputNameAndDeviceAndNegative) { InputMapping mapping; bool checkingKeys = false; bool isNegative = false; string[] input = inputNameAndDeviceAndNegative.Split(' '); switch (input[1]) { case "Keyboard": checkingKeys = true; break; case "Controller": checkingKeys = false; break; default: Debug.LogError("Unknown Device. [UI_GetInputName], InputManager"); break; } switch(input[2]) { case "True": isNegative = true; break; case "False": isNegative = false; break; default: Debug.LogError("Error Reading 'IsNegative'. [UI_GetInputName], InputManager"); break; } if (m_inputs.TryGetValue(input[0], out mapping)) { if (checkingKeys) { if (isNegative) return mapping.negativeKeyName; else return mapping.positiveKeyName; } else return mapping.buttonName; } else { Debug.LogError("Input name not valid. [UI_GetInputName, InputManager]"); return ""; } } private void DetectNewInput() { if (m_reassigningKeys) { foreach (KeyCode k in System.Enum.GetValues(typeof(KeyCode))) { if (Input.GetKeyDown(k)) { InputMapping oldMapping = m_inputs[m_inputToReassign]; m_inputs.Remove(m_inputToReassign); InputMapping newMapping = new InputMapping(); newMapping.name = m_inputToReassign; if (m_reassignAxis) { if (m_reassigningPositive) { newMapping.positiveKeyName = k.ToString(); newMapping.negativeKeyName = oldMapping.negativeKeyName; } else { newMapping.positiveKeyName = oldMapping.positiveKeyName; newMapping.negativeKeyName = k.ToString(); } } else { newMapping.positiveKeyName = k.ToString(); newMapping.negativeKeyName = oldMapping.negativeKeyName; } newMapping.buttonName = oldMapping.buttonName; newMapping.axisPositiveState = oldMapping.axisPositiveState; m_inputToReassign = ""; m_reassignInput = false; m_reassignAxis = false; m_inputs.Add(newMapping.name, newMapping); // Add inputs to the dictionary FindObjectOfType<MenuManager>().isActive = true; return; } } } else { foreach (string s in m_controllerButtonNames) { if (Input.GetButtonDown(s)) { InputMapping oldMapping = m_inputs[m_inputToReassign]; m_inputs.Remove(m_inputToReassign); InputMapping newMapping = new InputMapping(); newMapping.name = m_inputToReassign; newMapping.positiveKeyName = oldMapping.positiveKeyName; newMapping.negativeKeyName = oldMapping.negativeKeyName; newMapping.buttonName = /*"b." + */s; newMapping.axisPositiveState = oldMapping.axisPositiveState; m_inputToReassign = ""; m_reassignInput = false; m_reassignAxis = false; m_inputs.Add(newMapping.name, newMapping); // Add inputs to the dictionary FindObjectOfType<MenuManager>().isActive = true; return; } } foreach (string s in m_controllerAxisNames) { if (Mathf.Abs(Input.GetAxis(s)) > 0) { InputMapping oldMapping = m_inputs[m_inputToReassign]; m_inputs.Remove(m_inputToReassign); InputMapping newMapping = new InputMapping(); newMapping.name = m_inputToReassign; newMapping.positiveKeyName = oldMapping.positiveKeyName; newMapping.negativeKeyName = oldMapping.negativeKeyName; newMapping.buttonName = /*"a." + */s; newMapping.axisPositiveState = EAxisState.GreaterThan; m_inputToReassign = ""; m_reassignInput = false; m_reassignAxis = false; m_inputs.Add(newMapping.name, newMapping); // Add inputs to the dictionary FindObjectOfType<MenuManager>().isActive = true; return; } else if (Mathf.Abs(Input.GetAxis(s)) < 0) { InputMapping oldMapping = m_inputs[m_inputToReassign]; m_inputs.Remove(m_inputToReassign); InputMapping newMapping = new InputMapping(); newMapping.name = m_inputToReassign; newMapping.positiveKeyName = oldMapping.positiveKeyName; newMapping.negativeKeyName = oldMapping.negativeKeyName; newMapping.buttonName = /*"a." + */s; if (!m_reassignAxis) newMapping.axisPositiveState = EAxisState.LessThan; else newMapping.axisPositiveState = EAxisState.GreaterThan; m_inputToReassign = ""; m_reassignInput = false; m_reassignAxis = false; m_inputs.Add(newMapping.name, newMapping); // Add inputs to the dictionary FindObjectOfType<MenuManager>().isActive = true; return; } } } } #endregion Input Reassigning #region Input State /// <summary> /// Returns on every frame (auto-fire) /// </summary> /// <param name="inputName">Name of the action</param> /// <returns>Bool</returns> public bool GetButton(string inputName) { InputMapping input; if (m_inputs.TryGetValue(inputName, out input)) { foreach(InputMapping i in m_inputMappings) { if(i.name == inputName) { if (!input.isAxis) { if (input.positiveKeyName != "") { if ((Input.GetKeyDown((KeyCode)System.Enum.Parse(typeof(KeyCode), input.positiveKeyName)))) { i.Press(); return true; } } if ((Input.GetAxis(input.buttonName) < 0 && input.axisPositiveState == EAxisState.GreaterThan) || (Input.GetAxis(input.buttonName) > 0 && input.axisPositiveState == EAxisState.LessThan) || (Input.GetButton(input.buttonName))) { i.Press(); return true; } else { return false; } } else { if (Mathf.Abs(GetAxis(input.buttonName)) > 0) { i.Press(); return true; } } } } } return false; } /// <summary> /// Returns on the frame the input is pressed /// </summary> /// <param name="inputName">Name of the action</param> /// <returns>Bool</returns> public bool GetButtonDown(string inputName) { InputMapping input; if (m_inputs.TryGetValue(inputName, out input)) { foreach (InputMapping i in m_inputMappings) { if (i.name == inputName) { if(!i.IsPressed) { if (!input.isAxis) { if (input.positiveKeyName != "") { if ((Input.GetKeyDown((KeyCode)System.Enum.Parse(typeof(KeyCode), input.positiveKeyName)))) { i.Press(); return true; } } if ((Input.GetAxis(input.buttonName) < 0 && input.axisPositiveState == EAxisState.GreaterThan) || (Input.GetAxis(input.buttonName) > 0 && input.axisPositiveState == EAxisState.LessThan) || (Input.GetButtonDown(input.buttonName))) { i.Press(); return true; } else { return false; } } else { if (Mathf.Abs(GetAxis(input.buttonName)) > 0) { i.Press(); return true; } } } } } } return false; } /// <summary> /// Returns on the frame the input is released /// </summary> /// <param name="inputName">Name of the action</param> /// <returns>Bool</returns> public bool GetButtonUp(string inputName) { InputMapping input; if (m_inputs.TryGetValue(inputName, out input)) { foreach (InputMapping i in m_inputMappings) { if (i.name == inputName) { if (i.IsPressed) { if (!input.isAxis) { if (input.positiveKeyName != "") { if ((Input.GetKeyDown((KeyCode)System.Enum.Parse(typeof(KeyCode), input.positiveKeyName)))) { i.UnPress(); return true; } } if ((Input.GetAxis(input.buttonName) < 0 && input.axisPositiveState == EAxisState.GreaterThan) || (Input.GetAxis(input.buttonName) > 0 && input.axisPositiveState == EAxisState.LessThan) || (Input.GetButtonDown(input.buttonName))) { i.UnPress(); return true; } else { return false; } } else { if (Mathf.Abs(GetAxis(input.buttonName)) == 0) { i.UnPress(); return true; } } } } } } return false; } /// <summary> /// Returns the state of the axis between -1 and 1 /// </summary> /// <param name="axisName">Name of the action</param> /// <returns>Float</returns> public float GetAxis(string axisName) { InputMapping input; if (m_inputs.TryGetValue(axisName, out input)) { if (input.isAxis) { float output = 0.0f; bool keypressed = false; if (input.positiveKeyName != "") { if (Input.GetKey((KeyCode)System.Enum.Parse(typeof(KeyCode), input.positiveKeyName))) { output += 1.0f; keypressed = true; } } if (input.negativeKeyName != "") { if (Input.GetKey((KeyCode)System.Enum.Parse(typeof(KeyCode), input.negativeKeyName))) { output += -1.0f; keypressed = true; } } if(keypressed) { return output; } return Input.GetAxis(input.buttonName); } else { Debug.LogError(axisName + " is not an axis, you will never get -1. Did you mean to use GetButton()?"); if (Input.GetButton(axisName)) { return 1.0f; } else { return 0.0f; } } } return 0.0f; } #endregion Input State }
/* **************************************************************************** * * 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. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Runtime { /// <summary> /// Singleton for each language. /// </summary> internal sealed class LanguageConfiguration { private readonly AssemblyQualifiedTypeName _providerName; private readonly string _displayName; private readonly IDictionary<string, object> _options; private LanguageContext _context; public LanguageContext LanguageContext { get { return _context; } } public AssemblyQualifiedTypeName ProviderName { get { return _providerName; } } public string DisplayName { get { return _displayName; } } public LanguageConfiguration(AssemblyQualifiedTypeName providerName, string displayName, IDictionary<string, object> options) { _providerName = providerName; _displayName = displayName; _options = options; } /// <summary> /// Must not be called under a lock as it can potentially call a user code. /// </summary> /// <exception cref="InvalidImplementationException">The language context's implementation failed to instantiate.</exception> internal LanguageContext LoadLanguageContext(ScriptDomainManager domainManager, out bool alreadyLoaded) { if (_context == null) { // Let assembly load errors bubble out var assembly = domainManager.Platform.LoadAssembly(_providerName.AssemblyName.FullName); Type type = assembly.GetType(_providerName.TypeName); if (type == null) { throw new InvalidOperationException( String.Format( "Failed to load language '{0}': assembly '{1}' does not contain type '{2}'", _displayName, #if FEATURE_FILESYSTEM assembly.Location, #else assembly.FullName, #endif _providerName.TypeName )); } if (!type.GetTypeInfo().IsSubclassOf(typeof(LanguageContext))) { throw new InvalidOperationException( String.Format( "Failed to load language '{0}': type '{1}' is not a valid language provider because it does not inherit from LanguageContext", _displayName, type )); } LanguageContext context; try { context = (LanguageContext)Activator.CreateInstance(type, new object[] { domainManager, _options }); } catch (TargetInvocationException e) { throw new TargetInvocationException( String.Format("Failed to load language '{0}': {1}", _displayName, e.InnerException.Message), e.InnerException ); } catch (Exception e) { throw new InvalidImplementationException(Strings.InvalidCtorImplementation(type, e.Message), e); } alreadyLoaded = Interlocked.CompareExchange(ref _context, context, null) != null; } else { alreadyLoaded = true; } return _context; } } public sealed class DlrConfiguration { private bool _frozen; private readonly bool _debugMode; private readonly bool _privateBinding; private readonly IDictionary<string, object> _options; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer FileExtensionComparer = StringComparer.OrdinalIgnoreCase; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer LanguageNameComparer = StringComparer.OrdinalIgnoreCase; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer OptionNameComparer = StringComparer.Ordinal; private readonly Dictionary<string, LanguageConfiguration> _languageNames; private readonly Dictionary<string, LanguageConfiguration> _languageExtensions; private readonly Dictionary<AssemblyQualifiedTypeName, LanguageConfiguration> _languageConfigurations; private readonly Dictionary<Type, LanguageConfiguration> _loadedProviderTypes; public DlrConfiguration(bool debugMode, bool privateBinding, IDictionary<string, object> options) { ContractUtils.RequiresNotNull(options, "options"); _debugMode = debugMode; _privateBinding = privateBinding; _options = options; _languageNames = new Dictionary<string, LanguageConfiguration>(LanguageNameComparer); _languageExtensions = new Dictionary<string, LanguageConfiguration>(FileExtensionComparer); _languageConfigurations = new Dictionary<AssemblyQualifiedTypeName, LanguageConfiguration>(); _loadedProviderTypes = new Dictionary<Type, LanguageConfiguration>(); } /// <summary> /// Whether the application is in debug mode. /// This means: /// /// 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). /// 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). /// 3) JIT optimization is disabled for all methods /// 4) Languages may disable optimizations based on this value. /// </summary> public bool DebugMode { get { return _debugMode; } } /// <summary> /// Ignore CLR visibility checks. /// </summary> public bool PrivateBinding { get { return _privateBinding; } } internal IDictionary<string, object> Options { get { return _options; } } internal IDictionary<AssemblyQualifiedTypeName, LanguageConfiguration> Languages { get { return _languageConfigurations; } } public void AddLanguage(string languageTypeName, string displayName, IList<string> names, IList<string> fileExtensions, IDictionary<string, object> options) { AddLanguage(languageTypeName, displayName, names, fileExtensions, options, null); } internal void AddLanguage(string languageTypeName, string displayName, IList<string> names, IList<string> fileExtensions, IDictionary<string, object> options, string paramName) { ContractUtils.Requires(!_frozen, "Configuration cannot be modified once the runtime is initialized"); ContractUtils.Requires( names.TrueForAll((id) => !String.IsNullOrEmpty(id) && !_languageNames.ContainsKey(id)), paramName ?? "names", "Language name should not be null, empty or duplicated between languages" ); ContractUtils.Requires( fileExtensions.TrueForAll((ext) => !String.IsNullOrEmpty(ext) && !_languageExtensions.ContainsKey(ext)), paramName ?? "fileExtensions", "File extension should not be null, empty or duplicated between languages" ); ContractUtils.RequiresNotNull(displayName, paramName ?? "displayName"); if (string.IsNullOrEmpty(displayName)) { ContractUtils.Requires(names.Count > 0, paramName ?? "displayName", "Must have a non-empty display name or a a non-empty list of language names"); displayName = names[0]; } var aqtn = AssemblyQualifiedTypeName.ParseArgument(languageTypeName, paramName ?? "languageTypeName"); if (_languageConfigurations.ContainsKey(aqtn)) { throw new ArgumentException(string.Format("Duplicate language with type name '{0}'", aqtn), "languageTypeName"); } // Add global language options first, they can be rewritten by language specific ones: var mergedOptions = new Dictionary<string, object>(_options); // Replace global options with language-specific options foreach (var option in options) { mergedOptions[option.Key] = option.Value; } var config = new LanguageConfiguration(aqtn, displayName, mergedOptions); _languageConfigurations.Add(aqtn, config); // allow duplicate ids in identifiers and extensions lists: foreach (var name in names) { _languageNames[name] = config; } foreach (var ext in fileExtensions) { _languageExtensions[NormalizeExtension(ext)] = config; } } internal static string NormalizeExtension(string extension) { return extension[0] == '.' ? extension : "." + extension; } internal void Freeze() { Debug.Assert(!_frozen); _frozen = true; } internal bool TryLoadLanguage(ScriptDomainManager manager, AssemblyQualifiedTypeName providerName, out LanguageContext language) { Assert.NotNull(manager); LanguageConfiguration config; if (_languageConfigurations.TryGetValue(providerName, out config)) { language = LoadLanguageContext(manager, config); return true; } language = null; return false; } internal bool TryLoadLanguage(ScriptDomainManager manager, string str, bool isExtension, out LanguageContext language) { Assert.NotNull(manager, str); var dict = (isExtension) ? _languageExtensions : _languageNames; LanguageConfiguration config; if (dict.TryGetValue(str, out config)) { language = LoadLanguageContext(manager, config); return true; } language = null; return false; } private LanguageContext LoadLanguageContext(ScriptDomainManager manager, LanguageConfiguration config) { bool alreadyLoaded; var language = config.LoadLanguageContext(manager, out alreadyLoaded); if (!alreadyLoaded) { // Checks whether a single language is not registered under two different AQTNs. // We can only do it now because there is no way how to ensure that two AQTNs don't refer to the same type w/o loading the type. // The check takes place after config.LoadLanguageContext is called to avoid calling user code while holding a lock. lock (_loadedProviderTypes) { LanguageConfiguration existingConfig; Type type = language.GetType(); if (_loadedProviderTypes.TryGetValue(type, out existingConfig)) { throw new InvalidOperationException(String.Format("Language implemented by type '{0}' has already been loaded using name '{1}'", config.ProviderName, existingConfig.ProviderName)); } _loadedProviderTypes.Add(type, config); } } return language; } public string[] GetLanguageNames(LanguageContext context) { ContractUtils.RequiresNotNull(context, "context"); List<string> result = new List<string>(); foreach (var entry in _languageNames) { if (entry.Value.LanguageContext == context) { result.Add(entry.Key); } } return result.ToArray(); } internal string[] GetLanguageNames(LanguageConfiguration config) { List<string> result = new List<string>(); foreach (var entry in _languageNames) { if (entry.Value == config) { result.Add(entry.Key); } } return result.ToArray(); } public string[] GetLanguageNames() { return ArrayUtils.MakeArray<string>(_languageNames.Keys); } public string[] GetFileExtensions(LanguageContext context) { var result = new List<string>(); foreach (var entry in _languageExtensions) { if (entry.Value.LanguageContext == context) { result.Add(entry.Key); } } return result.ToArray(); } internal string[] GetFileExtensions(LanguageConfiguration config) { var result = new List<string>(); foreach (var entry in _languageExtensions) { if (entry.Value == config) { result.Add(entry.Key); } } return result.ToArray(); } public string[] GetFileExtensions() { return ArrayUtils.MakeArray<string>(_languageExtensions.Keys); } internal LanguageConfiguration GetLanguageConfig(LanguageContext context) { foreach (var config in _languageConfigurations.Values) { if (config.LanguageContext == context) { return config; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal partial class CMemberLookupResults { public partial class CMethodIterator { private SymbolLoader _pSymbolLoader; private CSemanticChecker _pSemanticChecker; // Inputs. private AggregateType _pCurrentType; private MethodOrPropertySymbol _pCurrentSym; private Declaration _pContext; private TypeArray _pContainingTypes; private CType _pQualifyingType; private Name _pName; private int _nArity; private symbmask_t _mask; private EXPRFLAG _flags; // Internal state. private int _nCurrentTypeCount; private bool _bIsCheckingInstanceMethods; private bool _bAtEnd; private bool _bAllowBogusAndInaccessible; // Flags for the current sym. private bool _bCurrentSymIsBogus; private bool _bCurrentSymIsInaccessible; // if Extension can be part of the results that are returned by the iterator // this may be false if an applicable instance method was found by bindgrptoArgs private bool _bcanIncludeExtensionsInResults; // we have found a applicable extension and only continue to the end of the current // Namespace's extension methodlist private bool _bEndIterationAtCurrentExtensionList; public CMethodIterator(CSemanticChecker checker, SymbolLoader symLoader, Name name, TypeArray containingTypes, CType @object, CType qualifyingType, Declaration context, bool allowBogusAndInaccessible, bool allowExtensionMethods, int arity, EXPRFLAG flags, symbmask_t mask) { Debug.Assert(name != null); Debug.Assert(symLoader != null); Debug.Assert(checker != null); Debug.Assert(containingTypes != null); _pSemanticChecker = checker; _pSymbolLoader = symLoader; _pCurrentType = null; _pCurrentSym = null; _pName = name; _pContainingTypes = containingTypes; _pQualifyingType = qualifyingType; _pContext = context; _bAllowBogusAndInaccessible = allowBogusAndInaccessible; _nArity = arity; _flags = flags; _mask = mask; _nCurrentTypeCount = 0; _bIsCheckingInstanceMethods = true; _bAtEnd = false; _bCurrentSymIsBogus = false; _bCurrentSymIsInaccessible = false; _bcanIncludeExtensionsInResults = allowExtensionMethods; _bEndIterationAtCurrentExtensionList = false; } public MethodOrPropertySymbol GetCurrentSymbol() { return _pCurrentSym; } public AggregateType GetCurrentType() { return _pCurrentType; } public bool IsCurrentSymbolInaccessible() { return _bCurrentSymIsInaccessible; } public bool IsCurrentSymbolBogus() { return _bCurrentSymIsBogus; } public bool MoveNext(bool canIncludeExtensionsInResults, bool endatCurrentExtensionList) { if (_bcanIncludeExtensionsInResults) { _bcanIncludeExtensionsInResults = canIncludeExtensionsInResults; } if (!_bEndIterationAtCurrentExtensionList) { _bEndIterationAtCurrentExtensionList = endatCurrentExtensionList; } if (_bAtEnd) { return false; } if (_pCurrentType == null) // First guy. { if (_pContainingTypes.Count == 0) { // No instance methods, only extensions. _bIsCheckingInstanceMethods = false; _bAtEnd = true; return false; } else { if (!FindNextTypeForInstanceMethods()) { // No instance or extensions. _bAtEnd = true; return false; } } } if (!FindNextMethod()) { _bAtEnd = true; return false; } return true; } public bool AtEnd() { return _pCurrentSym == null; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } public bool CanUseCurrentSymbol() { _bCurrentSymIsInaccessible = false; _bCurrentSymIsBogus = false; // Make sure that whether we're seeing a ctor is consistent with the flag. // The only properties we handle are indexers. if (_mask == symbmask_t.MASK_MethodSymbol && ( 0 == (_flags & EXPRFLAG.EXF_CTOR) != !_pCurrentSym.AsMethodSymbol().IsConstructor() || 0 == (_flags & EXPRFLAG.EXF_OPERATOR) != !_pCurrentSym.AsMethodSymbol().isOperator) || _mask == symbmask_t.MASK_PropertySymbol && !_pCurrentSym.AsPropertySymbol().isIndexer()) { // Get the next symbol. return false; } // If our arity is non-0, we must match arity with this symbol. if (_nArity > 0) { if (_mask == symbmask_t.MASK_MethodSymbol && _pCurrentSym.AsMethodSymbol().typeVars.Count != _nArity) { return false; } } // If this guy's not callable, no good. if (!ExpressionBinder.IsMethPropCallable(_pCurrentSym, (_flags & EXPRFLAG.EXF_USERCALLABLE) != 0)) { return false; } // Check access. if (!GetSemanticChecker().CheckAccess(_pCurrentSym, _pCurrentType, _pContext, _pQualifyingType)) { // Sym is not accessible. However, if we're allowing inaccessible, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsInaccessible = true; } else { return false; } } // Check bogus. if (GetSemanticChecker().CheckBogus(_pCurrentSym)) { // Sym is bogus, but if we're allow it, then let it through and mark it. if (_bAllowBogusAndInaccessible) { _bCurrentSymIsBogus = true; } else { return false; } } // if we are done checking all the instance types ensure that currentsym is an // extension method and not a simple static method if (!_bIsCheckingInstanceMethods) { if (!_pCurrentSym.AsMethodSymbol().IsExtension()) { return false; } } return true; } private bool FindNextMethod() { while (true) { if (_pCurrentSym == null) { _pCurrentSym = GetSymbolLoader().LookupAggMember( _pName, _pCurrentType.getAggregate(), _mask).AsMethodOrPropertySymbol(); } else { _pCurrentSym = GetSymbolLoader().LookupNextSym( _pCurrentSym, _pCurrentType.getAggregate(), _mask).AsMethodOrPropertySymbol(); } // If we couldn't find a sym, we look up the type chain and get the next type. if (_pCurrentSym == null) { if (_bIsCheckingInstanceMethods) { if (!FindNextTypeForInstanceMethods() && _bcanIncludeExtensionsInResults) { // We didn't find any more instance methods, set us into extension mode. _bIsCheckingInstanceMethods = false; } else if (_pCurrentType == null && !_bcanIncludeExtensionsInResults) { return false; } else { // Found an instance method. continue; } } continue; } // Note that we do not filter the current symbol for the user. They must do that themselves. // This is because for instance, BindGrpToArgs wants to filter on arguments before filtering // on bogosity. // If we're here, we're good to go. break; } return true; } private bool FindNextTypeForInstanceMethods() { // Otherwise, search through other types listed as well as our base class. if (_pContainingTypes.Count > 0) { if (_nCurrentTypeCount >= _pContainingTypes.Count) { // No more types to check. _pCurrentType = null; } else { _pCurrentType = _pContainingTypes[_nCurrentTypeCount++].AsAggregateType(); } } else { // We have no more types to consider, so check out the base class. _pCurrentType = _pCurrentType.GetBaseClass(); } return _pCurrentType != null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Security; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile : IDisposable { private readonly SafeMemoryMappedFileHandle _handle; private readonly bool _leaveOpen; private readonly FileStream _fileStream; internal const int DefaultSize = 0; // Private constructors to be used by the factory methods. [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); _handle = handle; _leaveOpen = true; // No FileStream to dispose of in this case. } [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) { Debug.Assert(handle != null && !handle.IsClosed && !handle.IsInvalid, "handle is null, closed, or invalid"); Debug.Assert(fileStream != null, "fileStream is null"); _handle = handle; _fileStream = fileStream; _leaveOpen = leaveOpen; } // Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call // will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory // mapped file created without an ACL will use a default ACL taken from the primary or impersonation token // of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but // the first override of this method. Note: having ReadWrite access to the object does not mean that we // have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages // when a view is created. public static MemoryMappedFile OpenExisting(string mapName) { return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None); } public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights) { return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0) { throw new ArgumentOutOfRangeException("desiredAccessRights"); } SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, desiredAccessRights, false); return new MemoryMappedFile(handle); } // Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing // file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to // the capacity will make the capacity of the memory mapped file match the size of the file. Specifying // a value larger than the size of the file will enlarge the new file to this size. Note that in such a // case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system // page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default, // the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be // changed by the leaveOpen boolean argument. public static MemoryMappedFile CreateFromFile(String path) { return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode) { return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName) { return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity) { return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(String path, FileMode mode, String mapName, Int64 capacity, MemoryMappedFileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (mode == FileMode.Append) { throw new ArgumentException(SR.Argument_NewMMFAppendModeNotAllowed, "mode"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } bool existed = File.Exists(path); FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.None, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_EmptyFile); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { CleanupFile(fileStream, existed, path); throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = null; try { handle = CreateCore(fileStream.SafeFileHandle, mapName, HandleInheritability.None, access, MemoryMappedFileOptions.None, capacity); } catch { CleanupFile(fileStream, existed, path); throw; } Debug.Assert(handle != null && !handle.IsInvalid); return new MemoryMappedFile(handle, fileStream, false); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { if (fileStream == null) { throw new ArgumentNullException("fileStream", SR.ArgumentNull_FileStream); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (capacity == 0 && fileStream.Length == 0) { throw new ArgumentException(SR.Argument_EmptyFile); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile fileStream.Flush(); if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = CreateCore(fileStream.SafeFileHandle, mapName, inheritability, access, MemoryMappedFileOptions.None, capacity); return new MemoryMappedFile(handle, fileStream, leaveOpen); } // Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal // for IPC, when mapName != null. public static MemoryMappedFile CreateNew(String mapName, Int64 capacity) { return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access) { return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity); return new MemoryMappedFile(handle); } // Factory Method Group #4: Creates a new empty memory mapped file or opens an existing // memory mapped file if one exists with the same name. The capacity, options, and // memoryMappedFileSecurity arguments will be ignored in the case of the later. // This is ideal for P2P style IPC. public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity) { return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access) { return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, access, true); } else { handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity); } return new MemoryMappedFile(handle); } // Creates a new view in the form of a stream. public MemoryMappedViewStream CreateViewStream() { return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size) { return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewStream CreateViewStream(Int64 offset, Int64 size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewStream(view); } // Creates a new view in the form of an accessor. Accessors are for random access. public MemoryMappedViewAccessor CreateViewAccessor() { return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size) { return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewAccessor CreateViewAccessor(Int64 offset, Int64 size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewAccessor(view); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [SecuritySafeCritical] protected virtual void Dispose(bool disposing) { try { if (_handle != null && !_handle.IsClosed) { _handle.Dispose(); } } finally { if (_fileStream != null && _leaveOpen == false) { _fileStream.Dispose(); } } } public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle { [SecurityCritical] get { return _handle; } } // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use // FileAccess to determine whether they are writable and/or readable. internal static FileAccess GetFileAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.ReadExecute: return FileAccess.Read; case MemoryMappedFileAccess.Write: return FileAccess.Write; case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.CopyOnWrite: case MemoryMappedFileAccess.ReadWriteExecute: return FileAccess.ReadWrite; default: throw new ArgumentOutOfRangeException("access"); } } // clean up: close file handle and delete files we created private static void CleanupFile(FileStream fileStream, bool existed, String path) { fileStream.Dispose(); if (!existed) { File.Delete(path); } } } }
//------------------------------------------------------------------------------ // <copyright file="ServicePointManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net.Configuration; using System.Net.Sockets; using System.Net.Security; using System.Security; using System.Security.Permissions; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; // This turned to be a legacy type name that is simply forwarded to System.Security.Authentication.SslProtocols defined values. #if !FEATURE_PAL [Flags] public enum SecurityProtocolType { Ssl3 = System.Security.Authentication.SslProtocols.Ssl3, Tls = System.Security.Authentication.SslProtocols.Tls, Tls11 = System.Security.Authentication.SslProtocols.Tls11, Tls12 = System.Security.Authentication.SslProtocols.Tls12, } internal class CertPolicyValidationCallback { readonly ICertificatePolicy m_CertificatePolicy; readonly ExecutionContext m_Context; internal CertPolicyValidationCallback() { m_CertificatePolicy = new DefaultCertPolicy(); m_Context = null; } internal CertPolicyValidationCallback(ICertificatePolicy certificatePolicy) { m_CertificatePolicy = certificatePolicy; m_Context = ExecutionContext.Capture(); } internal ICertificatePolicy CertificatePolicy { get { return m_CertificatePolicy;} } internal bool UsesDefault { get { return m_Context == null;} } internal void Callback(object state) { CallbackContext context = (CallbackContext) state; context.result = context.policyWrapper.CheckErrors(context.hostName, context.certificate, context.chain, context.sslPolicyErrors); } internal bool Invoke(string hostName, ServicePoint servicePoint, X509Certificate certificate, WebRequest request, X509Chain chain, SslPolicyErrors sslPolicyErrors) { PolicyWrapper policyWrapper = new PolicyWrapper(m_CertificatePolicy, servicePoint, (WebRequest) request); if (m_Context == null) { return policyWrapper.CheckErrors(hostName, certificate, chain, sslPolicyErrors); } else { ExecutionContext execContext = m_Context.CreateCopy(); CallbackContext callbackContext = new CallbackContext(policyWrapper, hostName, certificate, chain, sslPolicyErrors); ExecutionContext.Run(execContext, Callback, callbackContext); return callbackContext.result; } } private class CallbackContext { internal CallbackContext(PolicyWrapper policyWrapper, string hostName, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { this.policyWrapper = policyWrapper; this.hostName = hostName; this.certificate = certificate; this.chain = chain; this.sslPolicyErrors = sslPolicyErrors; } internal readonly PolicyWrapper policyWrapper; internal readonly string hostName; internal readonly X509Certificate certificate; internal readonly X509Chain chain; internal readonly SslPolicyErrors sslPolicyErrors; internal bool result; } } internal class ServerCertValidationCallback { readonly RemoteCertificateValidationCallback m_ValidationCallback; readonly ExecutionContext m_Context; internal ServerCertValidationCallback(RemoteCertificateValidationCallback validationCallback) { m_ValidationCallback = validationCallback; m_Context = ExecutionContext.Capture(); } internal RemoteCertificateValidationCallback ValidationCallback { get { return m_ValidationCallback;} } internal void Callback(object state) { CallbackContext context = (CallbackContext) state; context.result = m_ValidationCallback(context.request, context.certificate, context.chain, context.sslPolicyErrors); } internal bool Invoke(object request, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (m_Context == null) { return m_ValidationCallback(request, certificate, chain, sslPolicyErrors); } else { ExecutionContext execContext = m_Context.CreateCopy(); CallbackContext callbackContext = new CallbackContext(request, certificate, chain, sslPolicyErrors); ExecutionContext.Run(execContext, Callback, callbackContext); return callbackContext.result; } } private class CallbackContext { internal readonly Object request; internal readonly X509Certificate certificate; internal readonly X509Chain chain; internal readonly SslPolicyErrors sslPolicyErrors; internal bool result; internal CallbackContext(Object request, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { this.request = request; this.certificate = certificate; this.chain = chain; this.sslPolicyErrors = sslPolicyErrors; } } } #endif // !FEATURE_PAL // // The ServicePointManager class hands out ServicePoints (may exist or be created // as needed) and makes sure they are garbage collected when they expire. // The ServicePointManager runs in its own thread so that it never // /// <devdoc> /// <para>Manages the collection of <see cref='System.Net.ServicePoint'/> instances.</para> /// </devdoc> /// public class ServicePointManager { /// <devdoc> /// <para> /// The number of non-persistent connections allowed on a <see cref='System.Net.ServicePoint'/>. /// </para> /// </devdoc> public const int DefaultNonPersistentConnectionLimit = 4; /// <devdoc> /// <para> /// The default number of persistent connections allowed on a <see cref='System.Net.ServicePoint'/>. /// </para> /// </devdoc> public const int DefaultPersistentConnectionLimit = 2; /// <devdoc> /// <para> /// The default number of persistent connections when running under ASP+. /// </para> /// </devdoc> private const int DefaultAspPersistentConnectionLimit = 10; internal static readonly string SpecialConnectGroupName = "/.NET/NetClasses/HttpWebRequest/CONNECT__Group$$/"; internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(IdleServicePointTimeoutCallback); // // data - only statics used // // // s_ServicePointTable - Uri of ServicePoint is the hash key // We provide our own comparer function that knows about Uris // //also used as a lock object private static Hashtable s_ServicePointTable = new Hashtable(10); // IIS6 has 120 sec for an idle connection timeout, we should have a little bit less. private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100 * 1000); private static int s_MaxServicePoints = 0; #if !FEATURE_PAL private static volatile CertPolicyValidationCallback s_CertPolicyValidationCallback = new CertPolicyValidationCallback(); private static volatile ServerCertValidationCallback s_ServerCertValidationCallback = null; private const string strongCryptoKeyUnversioned = @"SOFTWARE\Microsoft\.NETFramework"; private const string strongCryptoKeyVersionedPattern = strongCryptoKeyUnversioned + @"\v{0}"; private const string strongCryptoKeyPath = @"HKEY_LOCAL_MACHINE\" + strongCryptoKeyUnversioned; private const string strongCryptoValueName = "SchUseStrongCrypto"; private static string secureProtocolAppSetting = "System.Net.ServicePointManager.SecurityProtocol"; private static object disableStrongCryptoLock = new object(); private static volatile bool disableStrongCryptoInitialized = false; private static bool disableStrongCrypto = false; private static SecurityProtocolType s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; #endif // !FEATURE_PAL private static volatile Hashtable s_ConfigTable = null; private static volatile int s_ConnectionLimit = PersistentConnectionLimit; internal static volatile bool s_UseTcpKeepAlive = false; internal static volatile int s_TcpKeepAliveTime; internal static volatile int s_TcpKeepAliveInterval; // // InternalConnectionLimit - // set/get Connection Limit on demand, checking config beforehand // private static volatile bool s_UserChangedLimit; private static int InternalConnectionLimit { get { if (s_ConfigTable == null) { // init config s_ConfigTable = ConfigTable; } return s_ConnectionLimit; } set { if (s_ConfigTable == null) { // init config s_ConfigTable = ConfigTable; } s_UserChangedLimit = true; s_ConnectionLimit = value; } } // // PersistentConnectionLimit - // Determines the correct connection limit based on whether with running with ASP+ // The following order is followed generally for figuring what ConnectionLimit size to use // 1. If ServicePoint.ConnectionLimit is set, then take that value // 2. If ServicePoint has a specific config setting, then take that value // 3. If ServicePoint.DefaultConnectionLimit is set, then take that value // 4. If ServicePoint is localhost, then set to infinite (TO Should we change this value?) // 5. If ServicePointManager has a default config connection limit setting, then take that value // 6. If ServicePoint is running under ASP+, then set value to 10, else set it to 2 // private static int PersistentConnectionLimit { get { #if !FEATURE_PAL if (ComNetOS.IsAspNetServer) { return DefaultAspPersistentConnectionLimit; } else #endif { return DefaultPersistentConnectionLimit; } } } /* Consider Removing // // InternalServicePointCount - // Gets the active number of ServicePoints being used // internal static int InternalServicePointCount { get { return s_ServicePointTable.Count; } } */ [System.Diagnostics.Conditional("DEBUG")] internal static void DebugMembers(int requestHash) { try { foreach (WeakReference servicePointReference in s_ServicePointTable) { ServicePoint servicePoint; if (servicePointReference != null && servicePointReference.IsAlive) { servicePoint = (ServicePoint)servicePointReference.Target; } else { servicePoint = null; } if (servicePoint!=null) { servicePoint.DebugMembers(requestHash); } } } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } } } // // ConfigTable - // read ConfigTable from Config, or create // a default on failure // private static Hashtable ConfigTable { get { if (s_ConfigTable == null) { lock(s_ServicePointTable) { if (s_ConfigTable == null) { ConnectionManagementSectionInternal configSection = ConnectionManagementSectionInternal.GetSection(); Hashtable configTable = null; if (configSection != null) { configTable = configSection.ConnectionManagement; } if (configTable == null) { configTable = new Hashtable(); } // we piggy back loading the ConnectionLimit here if (configTable.ContainsKey("*") ) { int connectionLimit = (int) configTable["*"]; if ( connectionLimit < 1 ) { connectionLimit = PersistentConnectionLimit; } s_ConnectionLimit = connectionLimit; } s_ConfigTable = configTable; } } } return s_ConfigTable; } } internal static TimerThread.Callback IdleServicePointTimeoutDelegate { get { return s_IdleServicePointTimeoutDelegate; } } private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context) { ServicePoint servicePoint = (ServicePoint) context; if (Logging.On) Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_log_closed_idle, "ServicePoint", servicePoint.GetHashCode())); lock (s_ServicePointTable) { s_ServicePointTable.Remove(servicePoint.LookupString); } servicePoint.ReleaseAllConnectionGroups(); } // // constructors // private ServicePointManager() { } #if !FEATURE_PAL [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] public static SecurityProtocolType SecurityProtocol { get { EnsureStrongCryptoSettingsInitialized(); return s_SecurityProtocolType; } set { EnsureStrongCryptoSettingsInitialized(); ValidateSecurityProtocol(value); s_SecurityProtocolType = value; } } private static void ValidateSecurityProtocol(SecurityProtocolType value) { // Do not allow Ssl2 (and others) as explicit SSL version request SecurityProtocolType allowed = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if ((value & ~allowed) != 0) { throw new NotSupportedException(SR.GetString(SR.net_securityprotocolnotsupported)); } } #endif // !FEATURE_PAL // // accessors // /// <devdoc> /// <para>Gets or sets the maximum number of <see cref='System.Net.ServicePoint'/> instances that should be maintained at any /// time.</para> /// </devdoc> [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] public static int MaxServicePoints { get { return s_MaxServicePoints; } set { ExceptionHelper.WebPermissionUnrestricted.Demand(); if (!ValidationHelper.ValidateRange(value, 0, Int32.MaxValue)) { throw new ArgumentOutOfRangeException("value"); } s_MaxServicePoints = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static int DefaultConnectionLimit { get { return InternalConnectionLimit; } set { ExceptionHelper.WebPermissionUnrestricted.Demand(); if (value > 0) { InternalConnectionLimit = value; } else { throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_toosmall)); } } } /// <devdoc> /// <para>Gets or sets the maximum idle time in seconds of a <see cref='System.Net.ServicePoint'/>.</para> /// </devdoc> public static int MaxServicePointIdleTime { get { return s_ServicePointIdlingQueue.Duration; } set { ExceptionHelper.WebPermissionUnrestricted.Demand(); if ( !ValidationHelper.ValidateRange(value, Timeout.Infinite, Int32.MaxValue)) { throw new ArgumentOutOfRangeException("value"); } if (s_ServicePointIdlingQueue.Duration != value) { s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(value); } } } /// <devdoc> /// <para> /// Gets or sets indication whether use of the Nagling algorithm is desired. /// Changing this value does not affect existing <see cref='System.Net.ServicePoint'/> instances but only to new ones that are created from that moment on. /// </para> /// </devdoc> public static bool UseNagleAlgorithm { get { return SettingsSectionInternal.Section.UseNagleAlgorithm; } set { SettingsSectionInternal.Section.UseNagleAlgorithm = value; } } /// <devdoc> /// <para> /// Gets or sets indication whether 100-continue behaviour is desired. /// Changing this value does not affect existing <see cref='System.Net.ServicePoint'/> instances but only to new ones that are created from that moment on. /// </para> /// </devdoc> public static bool Expect100Continue { get { return SettingsSectionInternal.Section.Expect100Continue; } set { SettingsSectionInternal.Section.Expect100Continue = value; } } /// <devdoc> /// <para> /// Enables the use of DNS round robin access, meaning a different IP /// address may be used on each connection, when more than one IP is availble /// </para> /// </devdoc> public static bool EnableDnsRoundRobin { get { return SettingsSectionInternal.Section.EnableDnsRoundRobin; } set { SettingsSectionInternal.Section.EnableDnsRoundRobin = value; } } /// <devdoc> /// <para> /// Causes us to go back and reresolve addresses through DNS, even when /// there were no recorded failures. -1 is infinite. Time should be in ms /// </para> /// </devdoc> public static int DnsRefreshTimeout { get { return SettingsSectionInternal.Section.DnsRefreshTimeout; } set { if(value < -1){ SettingsSectionInternal.Section.DnsRefreshTimeout = -1; } else{ SettingsSectionInternal.Section.DnsRefreshTimeout = value; } } } #if !FEATURE_PAL /// <devdoc> /// <para> /// Defines the s_Policy for how to deal with server certificates. /// </para> /// </devdoc> [Obsolete("CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static ICertificatePolicy CertificatePolicy { get { return GetLegacyCertificatePolicy(); } set { //Prevent for an applet to override default Certificate Policy ExceptionHelper.UnmanagedPermission.Demand(); s_CertPolicyValidationCallback = new CertPolicyValidationCallback(value); } } internal static ICertificatePolicy GetLegacyCertificatePolicy(){ if (s_CertPolicyValidationCallback == null) return null; else return s_CertPolicyValidationCallback.CertificatePolicy; } internal static CertPolicyValidationCallback CertPolicyValidationCallback { get { return s_CertPolicyValidationCallback; } } public static RemoteCertificateValidationCallback ServerCertificateValidationCallback { get { if (s_ServerCertValidationCallback == null) return null; else return s_ServerCertValidationCallback.ValidationCallback; } set { // Prevent an applet from overriding the default Certificate Policy ExceptionHelper.InfrastructurePermission.Demand(); if (value == null) { s_ServerCertValidationCallback = null; } else { s_ServerCertValidationCallback = new ServerCertValidationCallback(value); } } } internal static ServerCertValidationCallback ServerCertValidationCallback { get { return s_ServerCertValidationCallback; } } internal static bool DisableStrongCrypto { get { EnsureStrongCryptoSettingsInitialized(); return (bool)disableStrongCrypto; } } [RegistryPermission(SecurityAction.Assert, Read = strongCryptoKeyPath)] private static void EnsureStrongCryptoSettingsInitialized() { if (disableStrongCryptoInitialized) { return; } lock (disableStrongCryptoLock) { if (disableStrongCryptoInitialized) { return; } bool disableStrongCryptoInternal = true; try { string strongCryptoKey = String.Format(CultureInfo.InvariantCulture, strongCryptoKeyVersionedPattern, Environment.Version.ToString(3)); // We read reflected keys on WOW64. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(strongCryptoKey)) { try { object schUseStrongCryptoKeyValue = key.GetValue(strongCryptoValueName, null); // Setting the value to 1 will enable the MSRC behavior. // All other values are ignored. if ((schUseStrongCryptoKeyValue != null) && (key.GetValueKind(strongCryptoValueName) == RegistryValueKind.DWord)) { disableStrongCryptoInternal = ((int)schUseStrongCryptoKeyValue) != 1; } } catch (UnauthorizedAccessException) { } catch (IOException) { } } } catch (SecurityException) { } catch (ObjectDisposedException) { } if (disableStrongCryptoInternal) { // Revert the SecurityProtocol selection to the legacy combination. s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; } else { s_SecurityProtocolType = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // Attempt to read this from the AppSettings config section string appSetting = ConfigurationManager.AppSettings[secureProtocolAppSetting]; SecurityProtocolType value; try { value = (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), appSetting); ValidateSecurityProtocol(value); s_SecurityProtocolType = value; } catch (ArgumentNullException) { } catch (ArgumentException) { } catch (NotSupportedException) { } } disableStrongCrypto = disableStrongCryptoInternal; disableStrongCryptoInitialized = true; } } #endif // !FEATURE_PAL public static bool CheckCertificateRevocationList { get { return SettingsSectionInternal.Section.CheckCertificateRevocationList; } set { //Prevent an applet to override default certificate checking ExceptionHelper.UnmanagedPermission.Demand(); SettingsSectionInternal.Section.CheckCertificateRevocationList = value; } } public static EncryptionPolicy EncryptionPolicy { get { return SettingsSectionInternal.Section.EncryptionPolicy; } } internal static bool CheckCertificateName { get { return SettingsSectionInternal.Section.CheckCertificateName; } } // // class methods // // // MakeQueryString - Just a short macro to handle creating the query // string that we search for host ports in the host list // internal static string MakeQueryString(Uri address) { if (address.IsDefaultPort) return address.Scheme + "://" + address.DnsSafeHost; else return address.Scheme + "://" + address.DnsSafeHost + ":" + address.Port.ToString(); } internal static string MakeQueryString(Uri address1, bool isProxy) { if (isProxy) { return MakeQueryString(address1) + "://proxy"; } else { return MakeQueryString(address1); } } // // FindServicePoint - Query using an Uri string for a given ServerPoint Object // /// <devdoc> /// <para>Finds an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the /// specified Uniform Resource Identifier.</para> /// </devdoc> public static ServicePoint FindServicePoint(Uri address) { return FindServicePoint(address, null); } /// <devdoc> /// <para>Finds an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the /// specified Uniform Resource Identifier.</para> /// </devdoc> public static ServicePoint FindServicePoint(string uriString, IWebProxy proxy) { Uri uri = new Uri(uriString); return FindServicePoint(uri, proxy); } // // FindServicePoint - Query using an Uri for a given server point // /// <devdoc> /// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/> /// instance.</para> /// </devdoc> public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) { ProxyChain chain; HttpAbortDelegate abortDelegate = null; int abortState = 0; return FindServicePoint(address, proxy, out chain, ref abortDelegate, ref abortState); } // If abortState becomes non-zero, the attempt to find a service point has been aborted. internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState) { if (address==null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString()); bool isProxyServicePoint = false; chain = null; // // find proxy info, and then switch on proxy // Uri proxyAddress = null; if (proxy!=null && !address.IsLoopback) { IAutoWebProxy autoProxy = proxy as IAutoWebProxy; if (autoProxy != null) { chain = autoProxy.GetProxies(address); // Set up our ability to abort this MoveNext call. Note that the current implementations of ProxyChain will only // take time on the first call, so this is the only place we do this. If a new ProxyChain takes time in later // calls, this logic should be copied to other places MoveNext is called. GlobalLog.Assert(abortDelegate == null, "ServicePointManager::FindServicePoint()|AbortDelegate already set."); abortDelegate = chain.HttpAbortDelegate; try { Thread.MemoryBarrier(); if (abortState != 0) { Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Request aborted before proxy lookup.", exception); throw exception; } if (!chain.Enumerator.MoveNext()) { GlobalLog.Assert("ServicePointManager::FindServicePoint()|GetProxies() returned zero proxies."); /* Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestProhibitedByProxy), WebExceptionStatus.RequestProhibitedByProxy); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Proxy prevented request.", exception); throw exception; */ } proxyAddress = chain.Enumerator.Current; } finally { abortDelegate = null; } } else if (!proxy.IsBypassed(address)) { // use proxy support // rework address proxyAddress = proxy.GetProxy(address); } // null means DIRECT if (proxyAddress!=null) { address = proxyAddress; isProxyServicePoint = true; } } ServicePoint servicePoint = FindServicePointHelper(address, isProxyServicePoint); GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; } // Returns null if we get to the end of the chain. internal static ServicePoint FindServicePoint(ProxyChain chain) { GlobalLog.Print("ServicePointManager::FindServicePoint() Calling chained version."); if (!chain.Enumerator.MoveNext()) { return null; } Uri proxyAddress = chain.Enumerator.Current; return FindServicePointHelper(proxyAddress == null ? chain.Destination : proxyAddress, proxyAddress != null); } private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint) { GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString()); if (isProxyServicePoint) { if (address.Scheme != Uri.UriSchemeHttp) { // < Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception); throw exception; } } // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // string tempEntry = MakeQueryString(address, isProxyServicePoint); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if ( servicePointReference != null ) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint==null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); bool userDefined = s_UserChangedLimit; if (ConfigTable.ContainsKey(schemeHostPort) ) { connectionLimit = (int) ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; } // // FindServicePoint - Query using an Uri for a given server point // /// <devdoc> /// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/> /// instance.</para> /// </devdoc> internal static ServicePoint FindServicePoint(string host, int port) { if (host==null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() host:" + host.ToString()); string tempEntry = null; bool isProxyServicePoint = false; // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // tempEntry = "ByHost:"+host+":"+port.ToString(CultureInfo.InvariantCulture); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePoint() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePoint() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if ( servicePointReference != null ) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePoint() successfull lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint==null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; bool userDefined = s_UserChangedLimit; string schemeHostPort =host+":"+port.ToString(CultureInfo.InvariantCulture); if (ConfigTable.ContainsKey(schemeHostPort) ) { connectionLimit = (int) ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(host, port, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePoint() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePoint() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; } [FriendAccessAllowed] internal static void CloseConnectionGroups(string connectionGroupName) { // This method iterates through all service points and closes connection groups with the provided name. ServicePoint servicePoint = null; lock (s_ServicePointTable) { foreach (DictionaryEntry item in s_ServicePointTable) { WeakReference servicePointReference = item.Value as WeakReference; if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; if (servicePoint != null) { // We found a service point. Ask the service point to close all internal connection groups // with name 'connectionGroupName'. servicePoint.CloseConnectionGroupInternal(connectionGroupName); } } } } } // // SetTcpKeepAlive // // Enable/Disable the use of TCP keepalive option on ServicePoint // connections. This method does not affect existing ServicePoints. // When a ServicePoint is constructed it will inherit the current // settings. // // Parameters: // // enabled - if true enables the use of the TCP keepalive option // for ServicePoint connections. // // keepAliveTime - specifies the timeout, in milliseconds, with no // activity until the first keep-alive packet is sent. Ignored if // enabled parameter is false. // // keepAliveInterval - specifies the interval, in milliseconds, between // when successive keep-alive packets are sent if no acknowledgement is // received. Ignored if enabled parameter is false. // public static void SetTcpKeepAlive( bool enabled, int keepAliveTime, int keepAliveInterval) { GlobalLog.Enter( "ServicePointManager::SetTcpKeepAlive()" + " enabled: " + enabled.ToString() + " keepAliveTime: " + keepAliveTime.ToString() + " keepAliveInterval: " + keepAliveInterval.ToString() ); if (enabled) { s_UseTcpKeepAlive = true; if (keepAliveTime <= 0) { throw new ArgumentOutOfRangeException("keepAliveTime"); } if (keepAliveInterval <= 0) { throw new ArgumentOutOfRangeException("keepAliveInterval"); } s_TcpKeepAliveTime = keepAliveTime; s_TcpKeepAliveInterval = keepAliveInterval; } else { s_UseTcpKeepAlive = false; s_TcpKeepAliveTime = 0; s_TcpKeepAliveInterval =0; } GlobalLog.Leave("ServicePointManager::SetTcpKeepAlive()"); } } }
// Copyright 2008 Adrian Akison // Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx using System; using System.Collections; using System.Collections.Generic; namespace MCEBuddy.Util.Combinatorics { /// <summary> /// Permutations defines a meta-collection, typically a list of lists, of all /// possible orderings of a set of values. This list is enumerable and allows /// the scanning of all possible permutations using a simple foreach() loop. /// The MetaCollectionType parameter of the constructor allows for the creation of /// two types of sets, those with and without repetition in the output set when /// presented with repetition in the input set. /// </summary> /// <remarks> /// When given a input collect {A A B}, the following sets are generated: /// MetaCollectionType.WithRepetition => /// {A A B}, {A B A}, {A A B}, {A B A}, {B A A}, {B A A} /// MetaCollectionType.WithoutRepetition => /// {A A B}, {A B A}, {B A A} /// /// When generating non-repetition sets, ordering is based on the lexicographic /// ordering of the lists based on the provided Comparer. /// If no comparer is provided, then T must be IComparable on T. /// /// When generating repetition sets, no comparisions are performed and therefore /// no comparer is required and T does not need to be IComparable. /// </remarks> /// <typeparam name="T">The type of the values within the list.</typeparam> public class Permutations<T> : IMetaCollection<T> { #region Constructors /// <summary> /// No default constructor, must at least provided a list of values. /// </summary> protected Permutations() { ; } /// <summary> /// Create a permutation set from the provided list of values. /// The values (T) must implement IComparable. /// If T does not implement IComparable use a constructor with an explict IComparer. /// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets /// </summary> /// <param name="values">List of values to permute.</param> public Permutations(IList<T> values) { Initialize(values, GenerateOption.WithoutRepetition, null); } /// <summary> /// Create a permutation set from the provided list of values. /// If type is MetaCollectionType.WithholdRepetitionSets, then values (T) must implement IComparable. /// If T does not implement IComparable use a constructor with an explict IComparer. /// </summary> /// <param name="values">List of values to permute.</param> /// <param name="type">The type of permutation set to calculate.</param> public Permutations(IList<T> values, GenerateOption type) { Initialize(values, type, null); } /// <summary> /// Create a permutation set from the provided list of values. /// The values will be compared using the supplied IComparer. /// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets /// </summary> /// <param name="values">List of values to permute.</param> /// <param name="comparer">Comparer used for defining the lexigraphic order.</param> public Permutations(IList<T> values, IComparer<T> comparer) { Initialize(values, GenerateOption.WithoutRepetition, comparer); } #endregion #region IEnumerable Interface /// <summary> /// Gets an enumerator for collecting the list of permutations. /// </summary> /// <returns>The enumerator.</returns> public virtual IEnumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Gets an enumerator for collecting the list of permutations. /// </summary> /// <returns>The enumerator.</returns> IEnumerator<IList<T>> IEnumerable<IList<T>>.GetEnumerator() { return new Enumerator(this); } #endregion #region Enumerator Inner-Class /// <summary> /// The enumerator that enumerates each meta-collection of the enclosing Permutations class. /// </summary> public class Enumerator : IEnumerator<IList<T>> { #region Constructors /// <summary> /// Construct a enumerator with the parent object. /// </summary> /// <param name="source">The source Permutations object.</param> public Enumerator(Permutations<T> source) { myParent = source; myLexicographicalOrders = new int[source.myLexicographicOrders.Length]; source.myLexicographicOrders.CopyTo(myLexicographicalOrders, 0); Reset(); } #endregion #region IEnumerator Interface /// <summary> /// Resets the permutations enumerator to the first permutation. /// This will be the first lexicographically order permutation. /// </summary> public void Reset() { myPosition = Position.BeforeFirst; } /// <summary> /// Advances to the next permutation. /// </summary> /// <returns>True if successfully moved to next permutation, False if no more permutations exist.</returns> /// <remarks> /// Continuation was tried (i.e. yield return) by was not nearly as efficient. /// Performance is further increased by using value types and removing generics, that is, the LexicographicOrder parellel array. /// This is a issue with the .NET CLR not optimizing as well as it could in this infrequently used scenario. /// </remarks> public bool MoveNext() { if(myPosition == Position.BeforeFirst) { myValues = new List<T>(myParent.myValues.Count); myValues.AddRange(myParent.myValues); Array.Sort(myLexicographicalOrders); myPosition = Position.InSet; } else if(myPosition == Position.InSet) { if(myValues.Count < 2) { myPosition = Position.AfterLast; } else if(NextPermutation() == false) { myPosition = Position.AfterLast; } } return myPosition != Position.AfterLast; } /// <summary> /// The current permutation. /// </summary> public object Current { get { if(myPosition == Position.InSet) { return new List<T>(myValues); } else { throw new InvalidOperationException(); } } } /// <summary> /// The current permutation. /// </summary> IList<T> IEnumerator<IList<T>>.Current { get { if(myPosition == Position.InSet) { return new List<T>(myValues); } else { throw new InvalidOperationException(); } } } /// <summary> /// Cleans up non-managed resources, of which there are none used here. /// </summary> public virtual void Dispose() { ; } #endregion #region Heavy Lifting Methods /// <summary> /// Calculates the next lexicographical permutation of the set. /// This is a permutation with repetition where values that compare as equal will not /// swap positions to create a new permutation. /// http://www.cut-the-knot.org/do_you_know/AllPerm.shtml /// E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997 /// </summary> /// <returns>True if a new permutation has been returned, false if not.</returns> /// <remarks> /// This uses the integers of the lexicographical order of the values so that any /// comparison of values are only performed during initialization. /// </remarks> private bool NextPermutation() { int i = myLexicographicalOrders.Length - 1; while(myLexicographicalOrders[i - 1] >= myLexicographicalOrders[i]) { --i; if(i == 0) { return false; } } int j = myLexicographicalOrders.Length; while(myLexicographicalOrders[j - 1] <= myLexicographicalOrders[i - 1]) { --j; } Swap(i - 1, j - 1); ++i; j = myLexicographicalOrders.Length; while(i < j) { Swap(i - 1, j - 1); ++i; --j; } return true; } /// <summary> /// Helper function for swapping two elements within the internal collection. /// This swaps both the lexicographical order and the values, maintaining the parallel array. /// </summary> private void Swap(int i, int j) { myTemp = myValues[i]; myValues[i] = myValues[j]; myValues[j] = myTemp; myKviTemp = myLexicographicalOrders[i]; myLexicographicalOrders[i] = myLexicographicalOrders[j]; myLexicographicalOrders[j] = myKviTemp; } #endregion #region Data and Internal Members /// <summary> /// Single instance of swap variable for T, small performance improvement over declaring in Swap function scope. /// </summary> private T myTemp; /// <summary> /// Single instance of swap variable for int, small performance improvement over declaring in Swap function scope. /// </summary> private int myKviTemp; /// <summary> /// Flag indicating the position of the enumerator. /// </summary> private Position myPosition = Position.BeforeFirst; /// <summary> /// Parrellel array of integers that represent the location of items in the myValues array. /// This is generated at Initialization and is used as a performance speed up rather that /// comparing T each time, much faster to let the CLR optimize around integers. /// </summary> private int[] myLexicographicalOrders; /// <summary> /// The list of values that are current to the enumerator. /// </summary> private List<T> myValues; /// <summary> /// The set of permuations that this enumerator enumerates. /// </summary> private Permutations<T> myParent; /// <summary> /// Internal position type for tracking enumertor position. /// </summary> private enum Position { BeforeFirst, InSet, AfterLast } #endregion } #endregion #region IMetaList Interface /// <summary> /// The count of all permutations that will be returned. /// If type is MetaCollectionType.WithholdGeneratedSets, then this does not double count permutations with multiple identical values. /// I.e. count of permutations of "AAB" will be 3 instead of 6. /// If type is MetaCollectionType.WithRepetition, then this is all combinations and is therefore N!, where N is the number of values. /// </summary> public long Count { get { return myCount; } } /// <summary> /// The type of Permutations set that is generated. /// </summary> public GenerateOption Type { get { return myMetaCollectionType; } } /// <summary> /// The upper index of the meta-collection, equal to the number of items in the initial set. /// </summary> public int UpperIndex { get { return myValues.Count; } } /// <summary> /// The lower index of the meta-collection, equal to the number of items returned each iteration. /// For Permutation, this is always equal to the UpperIndex. /// </summary> public int LowerIndex { get { return myValues.Count; } } #endregion #region Heavy Lifting Members /// <summary> /// Common intializer used by the multiple flavors of constructors. /// </summary> /// <remarks> /// Copies information provided and then creates a parellel int array of lexicographic /// orders that will be used for the actual permutation algorithm. /// The input array is first sorted as required for WithoutRepetition and always just for consistency. /// This array is constructed one of two way depending on the type of the collection. /// /// When type is MetaCollectionType.WithRepetition, then all N! permutations are returned /// and the lexicographic orders are simply generated as 1, 2, ... N. /// E.g. /// Input array: {A A B C D E E} /// Lexicograhpic Orders: {1 2 3 4 5 6 7} /// /// When type is MetaCollectionType.WithoutRepetition, then fewer are generated, with each /// identical element in the input array not repeated. The lexicographic sort algorithm /// handles this natively as long as the repetition is repeated. /// E.g. /// Input array: {A A B C D E E} /// Lexicograhpic Orders: {1 1 2 3 4 5 5} /// </remarks> private void Initialize(IList<T> values, GenerateOption type, IComparer<T> comparer) { myMetaCollectionType = type; myValues = new List<T>(values.Count); myValues.AddRange(values); myLexicographicOrders = new int[values.Count]; if(type == GenerateOption.WithRepetition) { for(int i = 0; i < myLexicographicOrders.Length; ++i) { myLexicographicOrders[i] = i; } } else { if(comparer == null) { comparer = new SelfComparer<T>(); } myValues.Sort(comparer); int j = 1; if(myLexicographicOrders.Length > 0) { myLexicographicOrders[0] = j; } for(int i = 1; i < myLexicographicOrders.Length; ++i) { if(comparer.Compare(myValues[i - 1], myValues[i]) != 0) { ++j; } myLexicographicOrders[i] = j; } } myCount = GetCount(); } /// <summary> /// Calculates the total number of permutations that will be returned. /// As this can grow very large, extra effort is taken to avoid overflowing the accumulator. /// While the algorithm looks complex, it really is just collecting numerator and denominator terms /// and cancelling out all of the denominator terms before taking the product of the numerator terms. /// </summary> /// <returns>The number of permutations.</returns> private long GetCount() { int runCount = 1; List<int> divisors = new List<int>(); List<int> numerators = new List<int>(); for(int i = 1; i < myLexicographicOrders.Length; ++i) { numerators.AddRange(SmallPrimeUtility.Factor(i + 1)); if(myLexicographicOrders[i] == myLexicographicOrders[i - 1]) { ++runCount; } else { for(int f = 2; f <= runCount; ++f) { divisors.AddRange(SmallPrimeUtility.Factor(f)); } runCount = 1; } } for(int f = 2; f <= runCount; ++f) { divisors.AddRange(SmallPrimeUtility.Factor(f)); } return SmallPrimeUtility.EvaluatePrimeFactors(SmallPrimeUtility.DividePrimeFactors(numerators, divisors)); } #endregion #region Data and Internal Members /// <summary> /// A list of T that represents the order of elements as originally provided, used for Reset. /// </summary> private List<T> myValues; /// <summary> /// Parrellel array of integers that represent the location of items in the myValues array. /// This is generated at Initialization and is used as a performance speed up rather that /// comparing T each time, much faster to let the CLR optimize around integers. /// </summary> private int[] myLexicographicOrders; /// <summary> /// Inner class that wraps an IComparer around a type T when it is IComparable /// </summary> private class SelfComparer<U> : IComparer<U> { public int Compare(U x, U y) { return ((IComparable<U>)x).CompareTo(y); } } /// <summary> /// The count of all permutations. Calculated at Initialization and returned by Count property. /// </summary> private long myCount; /// <summary> /// The type of Permutations that this was intialized from. /// </summary> private GenerateOption myMetaCollectionType; #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. // /*============================================================================= ** ** ** ** Purpose: synchronization primitive that can also be used for interprocess synchronization ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Diagnostics; using System.Diagnostics.Contracts; public sealed class Mutex : WaitHandle { private const uint AccessRights = (uint)Win32Native.MAXIMUM_ALLOWED | Win32Native.SYNCHRONIZE | Win32Native.MUTEX_MODIFY_STATE; private static bool dummyBool; internal class MutexSecurity { } public Mutex(bool initiallyOwned, String name, out bool createdNew) : this(initiallyOwned, name, out createdNew, (MutexSecurity)null) { } internal unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity) { if (name == string.Empty) { // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on. name = null; } #if PLATFORM_WINDOWS if (name != null && System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif // PLATFORM_WINDOWS Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) { RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode); MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false); MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this); RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( tryCode, cleanupCode, cleanupInfo); createdNew = tryCodeHelper.m_newMutex; } internal class MutexTryCodeHelper { private bool m_initiallyOwned; private MutexCleanupInfo m_cleanupInfo; internal bool m_newMutex; private String m_name; private Win32Native.SECURITY_ATTRIBUTES m_secAttrs; private Mutex m_mutex; internal MutexTryCodeHelper(bool initiallyOwned, MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) { Debug.Assert(name == null || name.Length != 0); m_initiallyOwned = initiallyOwned; m_cleanupInfo = cleanupInfo; m_name = name; m_secAttrs = secAttrs; m_mutex = mutex; } internal void MutexTryCode(object userData) { // try block if (m_initiallyOwned) { m_cleanupInfo.inCriticalRegion = true; } uint mutexFlags = m_initiallyOwned ? Win32Native.CREATE_MUTEX_INITIAL_OWNER : 0; SafeWaitHandle mutexHandle = Win32Native.CreateMutexEx(m_secAttrs, m_name, mutexFlags, AccessRights); int errorCode = Marshal.GetLastWin32Error(); if (mutexHandle.IsInvalid) { mutexHandle.SetHandleAsInvalid(); if (m_name != null) { switch (errorCode) { #if PLATFORM_UNIX case Win32Native.ERROR_FILENAME_EXCED_RANGE: // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), "name"); #endif case Win32Native.ERROR_INVALID_HANDLE: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, m_name)); } } __Error.WinIOError(errorCode, m_name); } m_newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS; m_mutex.SetHandleInternal(mutexHandle); m_mutex.hasThreadAffinity = true; } } private void MutexCleanupCode(Object userData, bool exceptionThrown) { MutexCleanupInfo cleanupInfo = (MutexCleanupInfo)userData; // If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex // on this OS thread before ending our thread affninity. if (!hasThreadAffinity) { if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) { if (cleanupInfo.inCriticalRegion) { Win32Native.ReleaseMutex(cleanupInfo.mutexHandle); } cleanupInfo.mutexHandle.Dispose(); } } } internal class MutexCleanupInfo { internal SafeWaitHandle mutexHandle; internal bool inCriticalRegion; internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion) { this.mutexHandle = mutexHandle; this.inCriticalRegion = inCriticalRegion; } } public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) { } public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool) { } public Mutex() : this(false, null, out dummyBool) { } private Mutex(SafeWaitHandle handle) { SetHandleInternal(handle); hasThreadAffinity = true; } public static Mutex OpenExisting(string name) { return OpenExisting(name, (MutexRights)0); } internal enum MutexRights { } internal static Mutex OpenExisting(string name, MutexRights rights) { Mutex result; switch (OpenExistingWorker(name, rights, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); case OpenExistingResult.PathNotFound: __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name); return result; //never executes default: return result; } } public static bool TryOpenExisting(string name, out Mutex result) { return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success; } private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result) { if (name == null) { throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); } #if !PLATFORM_UNIX if (System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif Contract.EndContractBlock(); result = null; // To allow users to view & edit the ACL's, call OpenMutex // with parameters to allow us to view & edit the ACL. This will // fail if we don't have permission to view or edit the ACL's. // If that happens, ask for less permissions. SafeWaitHandle myHandle = Win32Native.OpenMutex(AccessRights, false, name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); #if PLATFORM_UNIX if (name != null && errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) { // On Unix, length validation is done by CoreCLR's PAL after converting to utf-8 throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), nameof(name)); } #endif if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && Win32Native.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; // this is for passed through Win32Native Errors __Error.WinIOError(errorCode, name); } result = new Mutex(myHandle); return OpenExistingResult.Success; } // Note: To call ReleaseMutex, you must have an ACL granting you // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). public void ReleaseMutex() { if (Win32Native.ReleaseMutex(safeWaitHandle)) { } else { throw new ApplicationException(SR.Arg_SynchronizationLockException); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using TDTK; namespace TDTK { public enum _GameState { Play, Pause, Over } [RequireComponent(typeof(ResourceManager))] public class GameControl : MonoBehaviour { public delegate void GameMessageHandler(string msg, float duration); public static event GameMessageHandler onGameMessageE; public static void DisplayMessage(string msg, float duration = 1.25f) { if (onGameMessageE != null) onGameMessageE(msg, duration); } public delegate void GameOverHandler(bool win); //true if win public static event GameOverHandler onGameOverE; public delegate void LifeHandler(int value); public static event LifeHandler onLifeE; private bool gameStarted = false; public static bool IsGameStarted() { return instance.gameStarted; } public static bool IsGameOver() { return instance.gameState == _GameState.Over ? true : false; } public _GameState gameState = _GameState.Play; public static _GameState GetGameState() { return instance.gameState; } public bool playerWon = false; public static bool HasPlayerWon() { return instance.playerWon; } public int levelID = 1; //the level progression (as in lvl1, lvl2, lvl3 and so on), user defined, use to verify perk availability public static int GetLevelID() { return instance.levelID; } public bool capLife = false; public int playerLifeCap = 0; public int playerLife = 10; public static int GetPlayerLife() { return instance.playerLife; } public static int GetPlayerLifeCap() { return instance.capLife ? instance.playerLifeCap : -1; } public bool enableLifeGen = false; public int lifeRegenRate = 0; //~ public bool enableScoring; public float sellTowerRefundRatio = 0.5f; public Transform rangeIndicator; private GameObject rangeIndicatorObj; public string nextScene = ""; public string mainMenu = ""; public static void LoadNextScene() { if (instance.nextScene != "") Load(instance.nextScene); } public static void LoadMainMenu() { if (instance.mainMenu != "") Load(instance.mainMenu); } public static void Load(string levelName) { //if(gameState==_GameState.Ended && instance.playerLife>0){ // ResourceManager.NewSceneNotification(); //} Application.LoadLevel(levelName); //UnityEngine.SceneManagement.SceneManager.LoadScene(levelName); } public bool loadAudioManager = false; private float timeStep = 0.015f; public static GameControl instance; public Transform thisT; void Awake() { Time.fixedDeltaTime = timeStep; instance = this; thisT = transform; ObjectPoolManager.Init(); BuildManager buildManager = (BuildManager)FindObjectOfType(typeof(BuildManager)); buildManager.Init(); SpawnManager.instance.Init(); PathTD[] paths = FindObjectsOfType(typeof(PathTD)) as PathTD[]; for (int i = 0; i < paths.Length; i++) paths[i].Init(); for (int i = 0; i < buildManager.buildPlatforms.Count; i++) buildManager.buildPlatforms[i].Init(); gameObject.GetComponent<ResourceManager>().Init(); if (loadAudioManager) { //GameObject amObj=Resources.Load("AudioManager", typeof(GameObject)) as GameObject; Instantiate(Resources.Load("AudioManager", typeof(GameObject))); } if (rangeIndicator) { rangeIndicator = (Transform)Instantiate(rangeIndicator); rangeIndicator.parent = thisT; rangeIndicatorObj = rangeIndicator.gameObject; } ClearSelectedTower(); Time.timeScale = 1; } // Use this for initialization void Start() { UnitTower[] towers = FindObjectsOfType(typeof(UnitTower)) as UnitTower[]; for (int i = 0; i < towers.Length; i++) BuildManager.PreBuildTower(towers[i]); //ignore collision between shootObject so they dont hit each other int soLayer = LayerManager.LayerShootObject(); Physics.IgnoreLayerCollision(soLayer, soLayer, true); //playerLife=playerLifeCap; if (capLife) playerLife = Mathf.Min(playerLife, GetPlayerLifeCap()); if (enableLifeGen) StartCoroutine(LifeRegenRoutine()); } void OnEnable() { UnitCreep.onDestinationE += OnUnitReachDestination; Unit.onDestroyedE += OnUnitDestroyed; } void OnDisable() { UnitCreep.onDestinationE -= OnUnitReachDestination; Unit.onDestroyedE -= OnUnitDestroyed; } void OnUnitDestroyed(Unit unit) { if (unit.IsCreep()) { if (unit.GetUnitCreep().lifeValue > 0) GainLife(unit.GetUnitCreep().lifeValue); } else if (unit.IsTower()) { if (unit.GetUnitTower() == selectedTower) _ClearSelectedTower(); } } void OnUnitReachDestination(UnitCreep unit) { playerLife = Mathf.Max(0, playerLife - unit.lifeCost); if (onLifeE != null) onLifeE(-unit.lifeCost); if (playerLife <= 0) { gameState = _GameState.Over; if (onGameOverE != null) onGameOverE(playerWon); } } IEnumerator LifeRegenRoutine() { float temp = 0; while (true) { yield return new WaitForSeconds(1); temp += lifeRegenRate; int value = 0; while (temp >= 1) { value += 1; temp -= 1; } if (value > 0) _GainLife(value); } } public static void GainLife(int value) { instance._GainLife(value); } public void _GainLife(int value) { playerLife += value; if (capLife) playerLife = Mathf.Min(playerLife, GetPlayerLifeCap()); if (onLifeE != null) onLifeE(value); } public static void StartGame() { //if game is not yet started, start it now instance.gameStarted = true; //instance.gameState=_GameState.Play; } public static void GameWon() { instance.StartCoroutine(instance._GameWon()); } public IEnumerator _GameWon() { ResumeGame(); //call to reset ff speed yield return new WaitForSeconds(0.0f); gameState = _GameState.Over; playerWon = true; if (onGameOverE != null) onGameOverE(playerWon); } public UnitTower selectedTower; public static UnitTower GetSelectedTower() { return instance.selectedTower; } public static UnitTower Select(Vector3 pointer) { int layer = LayerManager.LayerTower(); LayerMask mask = 1 << layer; Ray ray = Camera.main.ScreenPointToRay(pointer); RaycastHit hit; if (!Physics.Raycast(ray, out hit, Mathf.Infinity, mask)) return null; SelectTower(hit.transform.GetComponent<UnitTower>()); //instance._ShowIndicator(selectedTower); return instance.selectedTower; } public static void SelectTower(UnitTower tower) { instance._SelectTower(tower); } public void _SelectTower(UnitTower tower) { _ClearSelectedTower(); selectedTower = tower; float range = tower.GetRange(); Transform indicatorT = rangeIndicator; if (indicatorT != null) { indicatorT.parent = tower.thisT; indicatorT.position = tower.thisT.position; indicatorT.localScale = new Vector3(2 * range, 1, 2 * range); indicatorT.gameObject.SetActive(true); } } public static void ClearSelectedTower() { instance._ClearSelectedTower(); } public void _ClearSelectedTower() { selectedTower = null; rangeIndicatorObj.SetActive(false); rangeIndicator.parent = thisT; } public static void PauseGame() { instance.gameState = _GameState.Pause; Time.timeScale = 0; } public static void ResumeGame() { instance.gameState = _GameState.Play; Time.timeScale = 1; } public static float GetSellTowerRefundRatio() { return instance.sellTowerRefundRatio; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace Kintai { public partial class WorkTimeDao { public const string TABLE_NAME = "WorkTime"; public static class COLUMN_LIST { #region Columns public const string UserId = "UserId"; public const string WorkDate = "WorkDate"; public const string WorkType = "WorkType"; public const string BeginTime = "BeginTime"; public const string EndTime = "EndTime"; public const string RestTime = "RestTime"; public const string OfficeTime = "OfficeTime"; public const string WorkTime = "WorkTime"; public const string WorkDetail = "WorkDetail"; public const string CreateTimestamp = "CreateTimestamp"; public const string CreateUserId = "CreateUserId"; public const string UpdateTimestamp = "UpdateTimestamp"; public const string UpdateUserId = "UpdateUserId"; #endregion } public const string SQL_SELECT_PRIMARY_KEY = "select UserId,WorkDate,WorkType,BeginTime,EndTime,RestTime,OfficeTime,WorkTime,WorkDetail,CreateTimestamp,CreateUserId,UpdateTimestamp,UpdateUserId from WorkTime where UserId = @UserId AND WorkDate = @WorkDate"; public const string SQL_INSERT = "insert into WorkTime(UserId,WorkDate,WorkType,BeginTime,EndTime,RestTime,OfficeTime,WorkTime,WorkDetail,CreateTimestamp,CreateUserId,UpdateTimestamp,UpdateUserId)values(@UserId,@WorkDate,@WorkType,@BeginTime,@EndTime,@RestTime,@OfficeTime,@WorkTime,@WorkDetail,@CreateTimestamp,@CreateUserId,@UpdateTimestamp,@UpdateUserId)"; public const string SQL_UPDATE_PRIMARY_KEY = "update WorkTime set WorkType=@WorkType,BeginTime=@BeginTime,EndTime=@EndTime,RestTime=@RestTime,OfficeTime=@OfficeTime,WorkTime=@WorkTime,WorkDetail=@WorkDetail,CreateTimestamp=@CreateTimestamp,CreateUserId=@CreateUserId,UpdateTimestamp=@UpdateTimestamp,UpdateUserId=@UpdateUserId where UserId = @UserId AND WorkDate = @WorkDate"; public const string SQL_DELETE_PRIMARY_KEY = "delete from WorkTime where UserId = @UserId AND WorkDate = @WorkDate"; public virtual DatabaseAccess Access { get; set; } public virtual SqlConnection Connection { get; set; } public WorkTimeDao() { Access = new DatabaseAccess(); } public WorkTimeDao(SqlConnection conn) : this() { Connection = conn; } protected virtual SqlConnection GetConnection() { return Connection; } public WorkTimeEntity SelectPrimaryKey(WorkTimeEntity filter) { Dictionary<string, object> param = FillPrimaryKey(filter); SqlConnection conn = GetConnection(); SqlCommand command = conn.CreateCommand(); command.CommandText = SQL_SELECT_PRIMARY_KEY; if (param != null) { foreach (var key in param.Keys) { command.Parameters.AddWithValue("@" + key, param[key]); } } List<Dictionary<string, object>> list = Access.Select(conn, SQL_SELECT_PRIMARY_KEY, param); if (list.Count == 0) { return null; } WorkTimeEntity record2 = FillEntyty(list[0]); return record2; } public List<WorkTimeEntity> SelectWhere(string sql, Dictionary<string, object> param) { SqlConnection conn = GetConnection(); List<Dictionary<string, object>> list = Access.Select(conn, sql, param); List<WorkTimeEntity> list2 = new List<WorkTimeEntity>(); foreach (var item in list) { WorkTimeEntity record2 = FillEntyty(item); list2.Add(record2); } return list2; } public void Insert(WorkTimeEntity filter) { Dictionary<string, object> param = FillParam(filter); SqlConnection conn = GetConnection(); Access.Update(conn, SQL_INSERT, param); } public int UpdatePrimaryKey(WorkTimeEntity filter) { Dictionary<string, object> param = FillParam(filter); SqlConnection conn = GetConnection(); return Access.Update(conn, SQL_UPDATE_PRIMARY_KEY, param); } public int DeletePrimaryKey(WorkTimeEntity filter) { Dictionary<string, object> param = FillPrimaryKey(filter); SqlConnection conn = GetConnection(); return Access.Update(conn, SQL_DELETE_PRIMARY_KEY, param); } protected virtual Dictionary<string, object> FillPrimaryKey(WorkTimeEntity filter) { Dictionary<string, object> param = new Dictionary<string, object>(); #region PrimaryKeySet param[COLUMN_LIST.UserId] = filter.UserId; param[COLUMN_LIST.WorkDate] = filter.WorkDate; #endregion return param; } protected virtual Dictionary<string, object> FillParam(WorkTimeEntity filter) { Dictionary<string, object> param = new Dictionary<string, object>(); #region ParamSet param[COLUMN_LIST.UserId] = filter.UserId; param[COLUMN_LIST.WorkDate] = filter.WorkDate; param[COLUMN_LIST.WorkType] = filter.WorkType; param[COLUMN_LIST.BeginTime] = filter.BeginTime; param[COLUMN_LIST.EndTime] = filter.EndTime; param[COLUMN_LIST.RestTime] = filter.RestTime; param[COLUMN_LIST.OfficeTime] = filter.OfficeTime; param[COLUMN_LIST.WorkTime] = filter.WorkTime; param[COLUMN_LIST.WorkDetail] = filter.WorkDetail; param[COLUMN_LIST.CreateTimestamp] = filter.CreateTimestamp; param[COLUMN_LIST.CreateUserId] = filter.CreateUserId; param[COLUMN_LIST.UpdateTimestamp] = filter.UpdateTimestamp; param[COLUMN_LIST.UpdateUserId] = filter.UpdateUserId; #endregion return param; } protected virtual WorkTimeEntity FillEntyty(Dictionary<string, object> record) { WorkTimeEntity record2 = new WorkTimeEntity(); #region EntytySet record2.UserId = (string)record[COLUMN_LIST.UserId]; record2.WorkDate = (DateTime?)record[COLUMN_LIST.WorkDate]; record2.WorkType = (int?)record[COLUMN_LIST.WorkType]; record2.BeginTime = (int?)record[COLUMN_LIST.BeginTime]; record2.EndTime = (int?)record[COLUMN_LIST.EndTime]; record2.RestTime = (int?)record[COLUMN_LIST.RestTime]; record2.OfficeTime = (int?)record[COLUMN_LIST.OfficeTime]; record2.WorkTime = (int?)record[COLUMN_LIST.WorkTime]; record2.WorkDetail = (string)record[COLUMN_LIST.WorkDetail]; record2.CreateTimestamp = (DateTime?)record[COLUMN_LIST.CreateTimestamp]; record2.CreateUserId = (string)record[COLUMN_LIST.CreateUserId]; record2.UpdateTimestamp = (DateTime?)record[COLUMN_LIST.UpdateTimestamp]; record2.UpdateUserId = (string)record[COLUMN_LIST.UpdateUserId]; #endregion return record2; } #region DatabaseAccess public class DatabaseAccess { public virtual List<Dictionary<string, object>> Select(SqlConnection conn, string sql, Dictionary<string, object> param) { if (sql == null) { throw new ArgumentNullException("sql"); } SqlCommand command = conn.CreateCommand(); command.CommandText = sql; if (param != null) { foreach (var key in param.Keys) { command.Parameters.AddWithValue("@" + key, param[key]); } } using (SqlDataReader reader = command.ExecuteReader()) { int fields = reader.FieldCount; List<string> columnNames = new List<string>(); for (int i = 0; i < fields; i++) { columnNames.Add(reader.GetName(i)); } List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); while (reader.Read()) { Dictionary<string, object> record = new Dictionary<string, object>(); for (int i = 0; i < fields; i++) { if (reader.IsDBNull(i)) { record.Add(columnNames[i], null); } else if (reader.GetFieldType(i) == typeof(String)) { record.Add(columnNames[i], reader.GetString(i)); } else if (reader.GetFieldType(i) == typeof(Int32)) { record.Add(columnNames[i], reader.GetInt32(i)); } else if (reader.GetFieldType(i) == typeof(DateTime)) { record.Add(columnNames[i], reader.GetDateTime(i)); } else { record.Add(columnNames[i], reader.GetValue(i)); } } list.Add(record); } return list; } } public virtual int Update(SqlConnection conn, string sql, Dictionary<string, object> param) { if (sql == null) { throw new ArgumentNullException("sql"); } SqlCommand command = conn.CreateCommand(); command.CommandText = sql; if (param != null) { foreach (var key in param.Keys) { object val = param[key]; if (val == null) { val = DBNull.Value; } command.Parameters.AddWithValue("@" + key, val); } } int cnt = command.ExecuteNonQuery(); return cnt; } } #endregion } }
using System; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using Ai2dShooter.Common; using Ai2dShooter.Controller; using Ai2dShooter.Map; using Ai2dShooter.View; namespace Ai2dShooter.Model { /// <summary> /// An AI player controlled by a finite state machine (FSM). /// </summary> public sealed class FsmPlayer : Player { #region Private Fields private enum State { FindEnemy, AttackEnemy, Combat, FindFriend, Reload, Dead } private static readonly Color[] StateColors = { Color.Green, Color.Goldenrod, Color.Red, Color.Pink, Color.Purple, Color.FromArgb(Constants.DeadAlpha, Color.DeepSkyBlue) }; private readonly Pen _targetPen = new Pen(Color.FromArgb(127, Color.LawnGreen), 4); /// <summary> /// Cell that the player is targetting. /// </summary> private Cell _targetCell; /// <summary> /// Current state. /// </summary> private State _state; /// <summary> /// Number of reloading steps remaining. /// </summary> private int _reloadSteps = -1; #endregion #region Constructor public FsmPlayer(Cell initialLocation, Teams team) : base(initialLocation, PlayerController.AiFsm, team) { // register to events LocationChanged += MakeDecision; HealthChanged += MakeDecision; Death += () => _state = State.Dead; } #endregion #region Main Methods protected override void DrawPlayerImplementation(Graphics graphics, int scaleFactor, Rectangle box) { // make the box a bit smaller (so the circle doesn't exceed the box) var smallerBox = box; const int penWidth = 4; smallerBox.Inflate(-penWidth, -penWidth); // draw circle in the color belonging to the current state graphics.DrawEllipse(new Pen(StateColors[(int)_state], penWidth), smallerBox); // if required, draw a line to the cell that is currently being targeted by the player if (_targetCell != null && IsAlive) graphics.DrawLine(_targetPen, box.X + box.Width/2, box.Y + box.Height/2, _targetCell.X * scaleFactor + box.Width / 2, _targetCell.Y*scaleFactor + box.Height / 2); } public override void StartGame() { // initial state: seek enemy _state = State.FindEnemy; // start own worker thread new Thread(MakeDecision).Start(); } public override void EnemySpotted() { // stop moving and start fighting _state = State.Combat; AbortMovement(); } public override void SpottedByEnemy() { // stop moving and start fighting _state = State.Combat; AbortMovement(); } public override void KilledEnemy() { base.KilledEnemy(); // depending on health, look for friends or enemies or reload if (UsesKnife) { _state = State.Reload; _reloadSteps = Constants.ReloadSounds.Length - 1; } else _state = Health >= HealthyThreshold ? State.FindEnemy : State.FindFriend; //Console.WriteLine(this + " has killed an enemy and is now " + _state); // start movement MakeDecision(); } private void MakeDecision() { if (IsMoving || !IsAlive || !PlayerExists) return; Cell[] neighbors; switch (_state) { case State.FindEnemy: case State.AttackEnemy: // stuck? neighbors = Location.Neighbors.Where(n => n != null && !n.IsWall).ToArray(); if (neighbors.Length == 1) { _state = State.FindEnemy; // backtrack Move(Location.GetDirection(neighbors[0])); } else { // find closest enemy if (GameController.Instance == null) return; _targetCell = GameController.Instance.GetClosestVisibleOpponentCell(this); _state = _targetCell == null ? State.FindEnemy : State.AttackEnemy; if (_targetCell == null) { // no target found, move to neighboring cell where influence is lowest. Dont go backwards. Move( Location.GetDirection( GameController.Instance.GetCellWithLowestInfluence( neighbors.Except(new[] {Location.GetNeighbor((Direction) (((int) Orientation + 2)%4))}).ToArray(), this))); } else { // target found // calculate scores for each direction var directionScore = new int[4]; // iterate over directions for (var i = 0; i < (int)Direction.Count; i++) { // get neighbor in that direction var neighbor = Location.GetNeighbor((Direction)i); // ignore neighbors that can't be moved to if (neighbor == null || neighbor.IsWall) { directionScore[i] = int.MaxValue; continue; } // calculate score: distance * distance + rnd directionScore[i] = neighbor.GetManhattenDistance(_targetCell)* neighbor.GetManhattenDistance(_targetCell); //// if we'd have to go backwards, double the score //if (((int)Orientation + 2 % (int)Direction.Count) == i) // directionScore[i] *= 2; } // pick all directions with lowest costs var bestDirections = (from d in directionScore where d == directionScore.Min() select Array.IndexOf(directionScore, d)).ToArray(); // randomly chose one of the best directions Move((Direction)bestDirections[Constants.Rnd.Next(bestDirections.Length)]); } } break; case State.FindFriend: // stuck? neighbors = Location.Neighbors.Where(n => n != null && !n.IsWall).ToArray(); if (neighbors.Length == 1) { // backtrack Move(Location.GetDirection(neighbors[0])); } else { if (GameController.Instance == null) return; // find closest friend var friend = GameController.Instance.GetClosestFriend(this); _targetCell = friend == null ? null : friend.Location; if (_targetCell == null) { // all friends are dead or already follow me // move in random direction Move( Location.GetDirection( neighbors.Except(new[] { Location.GetNeighbor((Direction)(((int)Orientation + 2) % 4)) }).ToArray()[ Constants.Rnd.Next(neighbors.Length - 1)])); } else { // found friend to follow FollowedPlayer = friend; // calculate scores for each direction var directionScore = new int[4]; // iterate over directions for (var i = 0; i < (int)Direction.Count; i++) { // get neighbor in that direction var neighbor = Location.GetNeighbor((Direction)i); // ignore neighbors that can't be moved to if (neighbor == null || neighbor.IsWall) { directionScore[i] = int.MaxValue; continue; } // calculate score: distance * distance directionScore[i] = neighbor.GetManhattenDistance(_targetCell)* neighbor.GetManhattenDistance(_targetCell); // if we'd have to go backwards, double the score if (((int)Orientation + 2 % (int)Direction.Count) == i) directionScore[i] *= 2; } // pick all directions with lowest costs var bestDirections = (from d in directionScore where d == directionScore.Min() select Array.IndexOf(directionScore, d)).ToArray(); // randomly chose one of the best directions Move((Direction)bestDirections[Constants.Rnd.Next(bestDirections.Length)]); } } break; case State.Combat: // keep fighting break; case State.Reload: if (_reloadSteps < 0) { Ammo = MaxAmmo; MakeDecision(); return; } lock (Constants.MovementLock) { if (_reloadSteps < 0) return; if (MainForm.Instance.PlaySoundEffects) MainForm.Instance.Invoke((MethodInvoker) (() => Constants.ReloadSounds[_reloadSteps--].Play())); if (_reloadSteps < 0) { _state = Health >= HealthyThreshold ? State.FindEnemy : State.FindFriend; Ammo = MaxAmmo; } new Thread(() => { Thread.Sleep(Constants.ReloadTimeout); MakeDecision(); }).Start(); } return; default: throw new ArgumentOutOfRangeException(); } Thread.Sleep(Constants.AiMoveTimeout); } #endregion } }
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Drawing; using SDL2Idiomatic; using SDL2Idiomatic.Input; using GoblinPlugin; namespace Goblin { class Goblin { private static List<IGamePlugin> plugins = new List<IGamePlugin>(); private static List<IGameUpdateable> updateables = new List<IGameUpdateable>(); private static SortedDictionary<sbyte, List<IGameDrawable>> drawables = new SortedDictionary<sbyte, List<IGameDrawable>>(); private static List <IGameInputReceiver> inputReceivers = new List<IGameInputReceiver>(); private static MessageHub hub = new MessageHub(); private static void Init() { SDL.Init(); SDLImage.Init(); SDLMixer.Init(); SDLTruetype.Init(); SDL2.SDL.SDL_EventState(SDL2.SDL.SDL_EventType.SDL_DROPFILE, SDL2.SDL.SDL_ENABLE); } private static void Quit() { SDLTruetype.Quit(); SDLMixer.Quit(); SDLImage.Quit(); SDL.Quit(); } private static void LoadPlugins(Renderer render) { foreach (string file in ResourceLoader.ListAllWithExtension(".dll")) { //Console.WriteLine("Plugin loader found DLL {0}", file); Assembly assembly = ResourceLoader.LoadAssembly(file); foreach (Type type in assembly.GetTypes()) { if (type.GetInterface("IGamePlugin") != null) { //Console.WriteLine("\tLoaded {0}", type.Name); var plugin = (IGamePlugin)Activator.CreateInstance(type); plugins.Add(plugin); } } } if (plugins.Count == 0) plugins.Add((IGamePlugin)Activator.CreateInstance(typeof(Internal.InternalSample))); foreach (IGameUpdateable updatePlugin in plugins.ProvidingInterface<IGameUpdateable>()) { updateables.Add(updatePlugin); } //updateables.AddRange(plugins.ProvidingInterface<IGameUpdateable>()); foreach (IGameDrawable drawPlugin in plugins.ProvidingInterface<IGameDrawable>()) { sbyte zOrder = drawPlugin.RegisterZOrder(); if (!drawables.ContainsKey(zOrder)) { drawables.Add(zOrder, new List<IGameDrawable>()); } drawables[zOrder].Add(drawPlugin); } inputReceivers.AddRange(plugins.ProvidingInterface<IGameInputReceiver>()); foreach (var plugin in plugins) plugin.Init(render, plugins, hub); } private static void ReloadPlugins(Renderer render) { foreach (var plugin in plugins) plugin.Quit(); plugins.Clear(); updateables.Clear(); drawables.Clear(); inputReceivers.Clear(); LoadPlugins(render); } [STAThread] public static void Main(string[] args) { Init(); Window window = new Window(); window.Title = ""; Renderer render = new Renderer(window); bool running = true; hub.AddBuiltin("/quit", () => running = false); /* Game loading strategy: * 1. Bundle on command line, if specified * 2. Bundle in current directory, if present * 3. Separate files in current directory, if possible * 4. Internal fallback. */ Bundle bundle = null; if (args.Length > 0) { // 1. Bundle on command line, if specified if (File.Exists(args[0])) bundle = new Bundle(args[0]); else Console.WriteLine("{0} not found.", args[0]); } else { // 2. Bundle in current directory, if present string maybe = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location) + Bundle.FileExtension; if (File.Exists(maybe)) { bundle = new Bundle(maybe); } } ResourceLoader.SetBundle(bundle); // Now we can load everything via ResourceLoader, and it just works! if (ResourceLoader.Exists("icon")) window.SetIcon(ResourceLoader.LoadSurface("icon")); LoadPlugins(render); //foreach (IGameUpdateable u in updateables) u.Broadcast += OnBroadcast; SDL.OnEvent += ev => { switch (ev.type) { case SDL2.SDL.SDL_EventType.SDL_QUIT: running = false; break; case SDL2.SDL.SDL_EventType.SDL_KEYDOWN: foreach (var plugin in inputReceivers) plugin.KeyDown((Key)ev.key.keysym.sym); break; case SDL2.SDL.SDL_EventType.SDL_KEYUP: foreach (var plugin in inputReceivers) plugin.KeyUp((Key)ev.key.keysym.sym); break; case SDL2.SDL.SDL_EventType.SDL_MOUSEMOTION: foreach (var plugin in inputReceivers) plugin.MouseMoved(new Point(ev.motion.x, ev.motion.y), new Point(ev.motion.xrel, ev.motion.yrel)); break; case SDL2.SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN: foreach (var plugin in inputReceivers) plugin.MouseDown((MouseButton)ev.button.button, new Point(ev.button.x, ev.button.y)); break; case SDL2.SDL.SDL_EventType.SDL_MOUSEBUTTONUP: foreach (var plugin in inputReceivers) plugin.MouseUp((MouseButton)ev.button.button, new Point(ev.button.x, ev.button.y)); break; case SDL2.SDL.SDL_EventType.SDL_MOUSEWHEEL: foreach (var plugin in inputReceivers) plugin.MouseWheel(new Point(ev.wheel.x, ev.wheel.y)); break; case SDL2.SDL.SDL_EventType.SDL_DROPFILE: string filename = SDL2.Supplementary.FilenameFromDropEvent(ev.drop); Console.WriteLine("Dropped {0}", filename); if (Path.GetExtension(filename) == Bundle.FileExtension) { bundle = new Bundle(filename); ResourceLoader.SetBundle(bundle); if (ResourceLoader.Exists("icon")) window.SetIcon(ResourceLoader.LoadSurface("icon")); ReloadPlugins(render); //foreach (IGameUpdateable u in updateables) u.Broadcast += OnBroadcast; } break; default: break; } }; uint lastTime = SDL.Elapsed(); uint thisTime; while (running) { SDL.PollEvents(); thisTime = SDL.Elapsed(); uint dt = thisTime - lastTime; foreach (var plugin in updateables) plugin.Update(dt); lastTime = SDL.Elapsed(); foreach (var kvp in drawables) foreach (var plugin in kvp.Value) plugin.Draw(); render.Present(); } foreach (var plugin in plugins) plugin.Quit(); Quit(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/table/v1/bigtable_table_data.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Bigtable.Admin.Table.V1 { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class BigtableTableData { #region Descriptor public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static BigtableTableData() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjhnb29nbGUvYmlndGFibGUvYWRtaW4vdGFibGUvdjEvYmlndGFibGVfdGFi", "bGVfZGF0YS5wcm90bxIeZ29vZ2xlLmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYx", "GiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90bxoeZ29vZ2xl", "L3Byb3RvYnVmL2R1cmF0aW9uLnByb3RvIv0CCgVUYWJsZRIMCgRuYW1lGAEg", "ASgJEjgKEWN1cnJlbnRfb3BlcmF0aW9uGAIgASgLMh0uZ29vZ2xlLmxvbmdy", "dW5uaW5nLk9wZXJhdGlvbhJSCg9jb2x1bW5fZmFtaWxpZXMYAyADKAsyOS5n", "b29nbGUuYmlndGFibGUuYWRtaW4udGFibGUudjEuVGFibGUuQ29sdW1uRmFt", "aWxpZXNFbnRyeRJPCgtncmFudWxhcml0eRgEIAEoDjI6Lmdvb2dsZS5iaWd0", "YWJsZS5hZG1pbi50YWJsZS52MS5UYWJsZS5UaW1lc3RhbXBHcmFudWxhcml0", "eRpjChNDb2x1bW5GYW1pbGllc0VudHJ5EgsKA2tleRgBIAEoCRI7CgV2YWx1", "ZRgCIAEoCzIsLmdvb2dsZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MS5Db2x1", "bW5GYW1pbHk6AjgBIiIKFFRpbWVzdGFtcEdyYW51bGFyaXR5EgoKBk1JTExJ", "UxAAImwKDENvbHVtbkZhbWlseRIMCgRuYW1lGAEgASgJEhUKDWdjX2V4cHJl", "c3Npb24YAiABKAkSNwoHZ2NfcnVsZRgDIAEoCzImLmdvb2dsZS5iaWd0YWJs", "ZS5hZG1pbi50YWJsZS52MS5HY1J1bGUi7QIKBkdjUnVsZRIaChBtYXhfbnVt", "X3ZlcnNpb25zGAEgASgFSAASLAoHbWF4X2FnZRgCIAEoCzIZLmdvb2dsZS5w", "cm90b2J1Zi5EdXJhdGlvbkgAEksKDGludGVyc2VjdGlvbhgDIAEoCzIzLmdv", "b2dsZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MS5HY1J1bGUuSW50ZXJzZWN0", "aW9uSAASPQoFdW5pb24YBCABKAsyLC5nb29nbGUuYmlndGFibGUuYWRtaW4u", "dGFibGUudjEuR2NSdWxlLlVuaW9uSAAaRQoMSW50ZXJzZWN0aW9uEjUKBXJ1", "bGVzGAEgAygLMiYuZ29vZ2xlLmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYxLkdj", "UnVsZRo+CgVVbmlvbhI1CgVydWxlcxgBIAMoCzImLmdvb2dsZS5iaWd0YWJs", "ZS5hZG1pbi50YWJsZS52MS5HY1J1bGVCBgoEcnVsZUI+CiJjb20uZ29vZ2xl", "LmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYxQhZCaWd0YWJsZVRhYmxlRGF0YVBy", "b3RvUAFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbr::FileDescriptor[] { global::Google.Longrunning.Proto.Operations.Descriptor, global::Google.Protobuf.Proto.Duration.Descriptor, }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.Table), new[]{ "Name", "CurrentOperation", "ColumnFamilies", "Granularity" }, null, new[]{ typeof(global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity) }, new pbr::GeneratedCodeInfo[] { null, }), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.ColumnFamily), new[]{ "Name", "GcExpression", "GcRule" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule), new[]{ "MaxNumVersions", "MaxAge", "Intersection", "Union" }, new[]{ "Rule" }, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection), new[]{ "Rules" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union), new[]{ "Rules" }, null, null, null)}) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Table : pb::IMessage<Table> { private static readonly pb::MessageParser<Table> _parser = new pb::MessageParser<Table>(() => new Table()); public static pb::MessageParser<Table> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableData.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Table() { OnConstruction(); } partial void OnConstruction(); public Table(Table other) : this() { name_ = other.name_; CurrentOperation = other.currentOperation_ != null ? other.CurrentOperation.Clone() : null; columnFamilies_ = other.columnFamilies_.Clone(); granularity_ = other.granularity_; } public Table Clone() { return new Table(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int CurrentOperationFieldNumber = 2; private global::Google.Longrunning.Operation currentOperation_; public global::Google.Longrunning.Operation CurrentOperation { get { return currentOperation_; } set { currentOperation_ = value; } } public const int ColumnFamiliesFieldNumber = 3; private static readonly pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>.Codec _map_columnFamilies_codec = new pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Bigtable.Admin.Table.V1.ColumnFamily.Parser), 26); private readonly pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> columnFamilies_ = new pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>(); public pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> ColumnFamilies { get { return columnFamilies_; } } public const int GranularityFieldNumber = 4; private global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity granularity_ = global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity.MILLIS; public global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity Granularity { get { return granularity_; } set { granularity_ = value; } } public override bool Equals(object other) { return Equals(other as Table); } public bool Equals(Table other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(CurrentOperation, other.CurrentOperation)) return false; if (!ColumnFamilies.Equals(other.ColumnFamilies)) return false; if (Granularity != other.Granularity) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (currentOperation_ != null) hash ^= CurrentOperation.GetHashCode(); hash ^= ColumnFamilies.GetHashCode(); if (Granularity != global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity.MILLIS) hash ^= Granularity.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (currentOperation_ != null) { output.WriteRawTag(18); output.WriteMessage(CurrentOperation); } columnFamilies_.WriteTo(output, _map_columnFamilies_codec); if (Granularity != global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity.MILLIS) { output.WriteRawTag(32); output.WriteEnum((int) Granularity); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (currentOperation_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CurrentOperation); } size += columnFamilies_.CalculateSize(_map_columnFamilies_codec); if (Granularity != global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity.MILLIS) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Granularity); } return size; } public void MergeFrom(Table other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.currentOperation_ != null) { if (currentOperation_ == null) { currentOperation_ = new global::Google.Longrunning.Operation(); } CurrentOperation.MergeFrom(other.CurrentOperation); } columnFamilies_.Add(other.columnFamilies_); if (other.Granularity != global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity.MILLIS) { Granularity = other.Granularity; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (currentOperation_ == null) { currentOperation_ = new global::Google.Longrunning.Operation(); } input.ReadMessage(currentOperation_); break; } case 26: { columnFamilies_.AddEntriesFrom(input, _map_columnFamilies_codec); break; } case 32: { granularity_ = (global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity) input.ReadEnum(); break; } } } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum TimestampGranularity { MILLIS = 0, } } #endregion } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ColumnFamily : pb::IMessage<ColumnFamily> { private static readonly pb::MessageParser<ColumnFamily> _parser = new pb::MessageParser<ColumnFamily>(() => new ColumnFamily()); public static pb::MessageParser<ColumnFamily> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableData.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ColumnFamily() { OnConstruction(); } partial void OnConstruction(); public ColumnFamily(ColumnFamily other) : this() { name_ = other.name_; gcExpression_ = other.gcExpression_; GcRule = other.gcRule_ != null ? other.GcRule.Clone() : null; } public ColumnFamily Clone() { return new ColumnFamily(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int GcExpressionFieldNumber = 2; private string gcExpression_ = ""; public string GcExpression { get { return gcExpression_; } set { gcExpression_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int GcRuleFieldNumber = 3; private global::Google.Bigtable.Admin.Table.V1.GcRule gcRule_; public global::Google.Bigtable.Admin.Table.V1.GcRule GcRule { get { return gcRule_; } set { gcRule_ = value; } } public override bool Equals(object other) { return Equals(other as ColumnFamily); } public bool Equals(ColumnFamily other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (GcExpression != other.GcExpression) return false; if (!object.Equals(GcRule, other.GcRule)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (GcExpression.Length != 0) hash ^= GcExpression.GetHashCode(); if (gcRule_ != null) hash ^= GcRule.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (GcExpression.Length != 0) { output.WriteRawTag(18); output.WriteString(GcExpression); } if (gcRule_ != null) { output.WriteRawTag(26); output.WriteMessage(GcRule); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (GcExpression.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GcExpression); } if (gcRule_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GcRule); } return size; } public void MergeFrom(ColumnFamily other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.GcExpression.Length != 0) { GcExpression = other.GcExpression; } if (other.gcRule_ != null) { if (gcRule_ == null) { gcRule_ = new global::Google.Bigtable.Admin.Table.V1.GcRule(); } GcRule.MergeFrom(other.GcRule); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { GcExpression = input.ReadString(); break; } case 26: { if (gcRule_ == null) { gcRule_ = new global::Google.Bigtable.Admin.Table.V1.GcRule(); } input.ReadMessage(gcRule_); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class GcRule : pb::IMessage<GcRule> { private static readonly pb::MessageParser<GcRule> _parser = new pb::MessageParser<GcRule>(() => new GcRule()); public static pb::MessageParser<GcRule> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableData.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public GcRule() { OnConstruction(); } partial void OnConstruction(); public GcRule(GcRule other) : this() { switch (other.RuleCase) { case RuleOneofCase.MaxNumVersions: MaxNumVersions = other.MaxNumVersions; break; case RuleOneofCase.MaxAge: MaxAge = other.MaxAge.Clone(); break; case RuleOneofCase.Intersection: Intersection = other.Intersection.Clone(); break; case RuleOneofCase.Union: Union = other.Union.Clone(); break; } } public GcRule Clone() { return new GcRule(this); } public const int MaxNumVersionsFieldNumber = 1; public int MaxNumVersions { get { return ruleCase_ == RuleOneofCase.MaxNumVersions ? (int) rule_ : 0; } set { rule_ = value; ruleCase_ = RuleOneofCase.MaxNumVersions; } } public const int MaxAgeFieldNumber = 2; public global::Google.Protobuf.Duration MaxAge { get { return ruleCase_ == RuleOneofCase.MaxAge ? (global::Google.Protobuf.Duration) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.MaxAge; } } public const int IntersectionFieldNumber = 3; public global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection Intersection { get { return ruleCase_ == RuleOneofCase.Intersection ? (global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.Intersection; } } public const int UnionFieldNumber = 4; public global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union Union { get { return ruleCase_ == RuleOneofCase.Union ? (global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.Union; } } private object rule_; public enum RuleOneofCase { None = 0, MaxNumVersions = 1, MaxAge = 2, Intersection = 3, Union = 4, } private RuleOneofCase ruleCase_ = RuleOneofCase.None; public RuleOneofCase RuleCase { get { return ruleCase_; } } public void ClearRule() { ruleCase_ = RuleOneofCase.None; rule_ = null; } public override bool Equals(object other) { return Equals(other as GcRule); } public bool Equals(GcRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MaxNumVersions != other.MaxNumVersions) return false; if (!object.Equals(MaxAge, other.MaxAge)) return false; if (!object.Equals(Intersection, other.Intersection)) return false; if (!object.Equals(Union, other.Union)) return false; return true; } public override int GetHashCode() { int hash = 1; if (ruleCase_ == RuleOneofCase.MaxNumVersions) hash ^= MaxNumVersions.GetHashCode(); if (ruleCase_ == RuleOneofCase.MaxAge) hash ^= MaxAge.GetHashCode(); if (ruleCase_ == RuleOneofCase.Intersection) hash ^= Intersection.GetHashCode(); if (ruleCase_ == RuleOneofCase.Union) hash ^= Union.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (ruleCase_ == RuleOneofCase.MaxNumVersions) { output.WriteRawTag(8); output.WriteInt32(MaxNumVersions); } if (ruleCase_ == RuleOneofCase.MaxAge) { output.WriteRawTag(18); output.WriteMessage(MaxAge); } if (ruleCase_ == RuleOneofCase.Intersection) { output.WriteRawTag(26); output.WriteMessage(Intersection); } if (ruleCase_ == RuleOneofCase.Union) { output.WriteRawTag(34); output.WriteMessage(Union); } } public int CalculateSize() { int size = 0; if (ruleCase_ == RuleOneofCase.MaxNumVersions) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaxNumVersions); } if (ruleCase_ == RuleOneofCase.MaxAge) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MaxAge); } if (ruleCase_ == RuleOneofCase.Intersection) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Intersection); } if (ruleCase_ == RuleOneofCase.Union) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Union); } return size; } public void MergeFrom(GcRule other) { if (other == null) { return; } switch (other.RuleCase) { case RuleOneofCase.MaxNumVersions: MaxNumVersions = other.MaxNumVersions; break; case RuleOneofCase.MaxAge: MaxAge = other.MaxAge; break; case RuleOneofCase.Intersection: Intersection = other.Intersection; break; case RuleOneofCase.Union: Union = other.Union; break; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { MaxNumVersions = input.ReadInt32(); break; } case 18: { global::Google.Protobuf.Duration subBuilder = new global::Google.Protobuf.Duration(); if (ruleCase_ == RuleOneofCase.MaxAge) { subBuilder.MergeFrom(MaxAge); } input.ReadMessage(subBuilder); MaxAge = subBuilder; break; } case 26: { global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection subBuilder = new global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection(); if (ruleCase_ == RuleOneofCase.Intersection) { subBuilder.MergeFrom(Intersection); } input.ReadMessage(subBuilder); Intersection = subBuilder; break; } case 34: { global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union subBuilder = new global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union(); if (ruleCase_ == RuleOneofCase.Union) { subBuilder.MergeFrom(Union); } input.ReadMessage(subBuilder); Union = subBuilder; break; } } } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Intersection : pb::IMessage<Intersection> { private static readonly pb::MessageParser<Intersection> _parser = new pb::MessageParser<Intersection>(() => new Intersection()); public static pb::MessageParser<Intersection> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.GcRule.Descriptor.NestedTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Intersection() { OnConstruction(); } partial void OnConstruction(); public Intersection(Intersection other) : this() { rules_ = other.rules_.Clone(); } public Intersection Clone() { return new Intersection(this); } public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Bigtable.Admin.Table.V1.GcRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Bigtable.Admin.Table.V1.GcRule.Parser); private readonly pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> rules_ = new pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule>(); public pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> Rules { get { return rules_; } } public override bool Equals(object other) { return Equals(other as Intersection); } public bool Equals(Intersection other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } public void MergeFrom(Intersection other) { if (other == null) { return; } rules_.Add(other.rules_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Union : pb::IMessage<Union> { private static readonly pb::MessageParser<Union> _parser = new pb::MessageParser<Union>(() => new Union()); public static pb::MessageParser<Union> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.GcRule.Descriptor.NestedTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Union() { OnConstruction(); } partial void OnConstruction(); public Union(Union other) : this() { rules_ = other.rules_.Clone(); } public Union Clone() { return new Union(this); } public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Bigtable.Admin.Table.V1.GcRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Bigtable.Admin.Table.V1.GcRule.Parser); private readonly pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> rules_ = new pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule>(); public pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> Rules { get { return rules_; } } public override bool Equals(object other) { return Equals(other as Union); } public bool Equals(Union other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } public void MergeFrom(Union other) { if (other == null) { return; } rules_.Add(other.rules_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Diagnostics; using Gallio.Common.Splash.Internal; namespace Gallio.Common.Splash { /// <summary> /// A splash document contains styled text and embedded objects and retains layout information /// for presentation. /// </summary> public unsafe class SplashDocument { private readonly LookupTable<Style> styleTable; private readonly LookupTable<EmbeddedObject> objectTable; private readonly Dictionary<string, object> annotationTables; private readonly Stack<int> styleIndexStack; private readonly UnmanagedBuffer charBuffer; private readonly UnmanagedBuffer paragraphBuffer; private readonly UnmanagedBuffer runBuffer; private Paragraph* currentParagraph; private Run* currentRun; /// <summary> /// The character used as a placeholder for text itemizing when a paragraph contains an object run. /// </summary> private const char ObjectRunPlaceholderChar = ' '; /// <summary> /// The maximum number of characters that a text run can contain. /// </summary> internal const int MaxCharsPerRun = 65535; /// <summary> /// The maximum number of distinct objects supported by the implementation. /// </summary> public const int MaxObjects = 65535; /// <summary> /// The maximum number of distinct styles supported by the implementation. /// </summary> /// <value>256</value> public const int MaxStyles = 256; private const int InitialCapacityForCharsPerDocument = 4096; private const int InitialCapacityForParagraphsPerDocument = 64; private const int InitialCapacityForRunsPerDocument = 128; /// <summary> /// Creates an empty splash document. /// </summary> public SplashDocument() { styleTable = new LookupTable<Style>(MaxStyles, "This implementation only supports at most {0} distinct styles."); objectTable = new LookupTable<EmbeddedObject>(MaxObjects, "This implementation only supports at most {0} distinct objects."); annotationTables = new Dictionary<string, object>(); styleIndexStack = new Stack<int>(); charBuffer = new UnmanagedBuffer(InitialCapacityForCharsPerDocument, sizeof(char)); paragraphBuffer = new UnmanagedBuffer(InitialCapacityForParagraphsPerDocument, sizeof(Paragraph)); runBuffer = new UnmanagedBuffer(InitialCapacityForRunsPerDocument, sizeof(Run)); InternalClear(); } /// <summary> /// Event raised when the document is cleared. /// </summary> public event EventHandler DocumentCleared; /// <summary> /// Event raised when a paragraph is changed. /// </summary> public event EventHandler<ParagraphChangedEventArgs> ParagraphChanged; /// <summary> /// Gets the number of paragraphs in the document. /// </summary> /// <remarks> /// This number is guaranteed to always be at least 1 even in an empty document. /// </remarks> public int ParagraphCount { get { return paragraphBuffer.Count; } } /// <summary> /// Gets the number of characters in the document. /// </summary> public int CharCount { get { return charBuffer.Count; } } /// <summary> /// Gets the current style. /// </summary> public Style CurrentStyle { get { return LookupStyle(CurrentStyleIndex); } } /// <summary> /// Clears the text in the document. /// </summary> public void Clear() { InternalClear(); RaiseDocumentCleared(); } private void InternalClear() { currentParagraph = null; currentRun = null; styleTable.Clear(); objectTable.Clear(); annotationTables.Clear(); styleIndexStack.Clear(); charBuffer.Clear(); paragraphBuffer.Clear(); runBuffer.Clear(); InternalBeginStyle(Style.Default); InternalStartParagraph(); } /// <summary> /// Gets a range of the document text. /// </summary> /// <param name="start">The start character index.</param> /// <param name="length">The length of the range.</param> /// <returns>The text in the specified range.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="start"/> /// or <paramref name="length"/> are negative or refer to a range that exceeds the document length.</exception> public string GetTextRange(int start, int length) { ValidateCharacterRange(start, length); return new string(GetCharZero(), start, length); } /// <summary> /// Gets the style of the text at the specified character index. /// </summary> /// <param name="index">The character index.</param> /// <returns>The style.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="index"/> is /// outside of the bounds of the document.</exception> public Style GetStyleAtIndex(int index) { Run* run = ValidateCharacterIndexAndGetRun(index); return LookupStyle(run->StyleIndex); } /// <summary> /// Gets the embedded object at the specified character index, or null if none. /// </summary> /// <param name="index">The character index.</param> /// <returns>The embedded object, or null if none.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="index"/> is /// outside of the bounds of the document.</exception> public EmbeddedObject GetObjectAtIndex(int index) { Run* run = ValidateCharacterIndexAndGetRun(index); return run->RunKind == RunKind.Object ? LookupObject(run->ObjectIndex) : null; } /// <summary> /// Gets the annotation with the specified key at the specified character index. /// </summary> /// <param name="key">The annotation key.</param> /// <param name="index">The character index.</param> /// <param name="value">Set to the annotation value, or default if none.</param> /// <returns>True if an annotation was found.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="index"/> is /// outside of the bounds of the document.</exception> public bool TryGetAnnotationAtIndex<T>(Key<T> key, int index, out T value) { ValidateCharacterIndex(index); AnnotationTable<T> annotationTable = GetAnnotationTable(key, false); if (annotationTable == null) { value = default(T); return false; } return annotationTable.TryGetValueAtIndex(index, out value); } /// <summary> /// Gets the current annotation with the specified key. /// </summary> /// <param name="key">The annotation key.</param> /// <param name="value">Set to the annotation value, or default if none.</param> /// <returns>True if there is a current annotation.</returns> public bool TryGetCurrentAnnotation<T>(Key<T> key, out T value) { AnnotationTable<T> annotationTable = GetAnnotationTable(key, false); if (annotationTable == null) { value = default(T); return false; } return annotationTable.TryGetCurrentValue(out value); } /// <summary> /// Appends text to the document. /// </summary> /// <param name="text">The text to append.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="text"/> is null.</exception> public void AppendText(string text) { if (text == null) throw new ArgumentNullException("text"); if (text.Length != 0) { int styleIndex = CurrentStyleIndex; int paragraphIndex = CurrentParagraphIndex; InternalAppendText(styleIndex, text); RaiseParagraphChanged(paragraphIndex); } } /// <summary> /// Appends a new line to the document. /// </summary> public void AppendLine() { int styleIndex = CurrentStyleIndex; int paragraphIndex = CurrentParagraphIndex; fixed (char* chars = "\n") InternalAppendChars(styleIndex, chars, 1); InternalStartParagraph(); RaiseParagraphChanged(paragraphIndex); } /// <summary> /// Appends an object to the document. /// </summary> /// <param name="obj">The object to append.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="obj"/> is null.</exception> public void AppendObject(EmbeddedObject obj) { if (obj == null) throw new ArgumentNullException("obj"); int styleIndex = CurrentStyleIndex; int paragraphIndex = CurrentParagraphIndex; InternalAppendObject(styleIndex, obj); RaiseParagraphChanged(paragraphIndex); } /// <summary> /// Pushes a new style onto the style stack. /// Subsequently appended content will use the new style. /// </summary> /// <example> /// <code> /// using (document.BeginStyle(linkStyle)) /// { /// using (document.BeginAnnotation("href", "http://www.gallio.org")) /// { /// document.AppendText("Gallio"); /// } /// } /// </code> /// </example> /// <param name="style">The style to use.</param> /// <returns>A value that when disposed automatically calls <see cref="EndStyle"/>. /// Used with the C# "using" syntax to end the style at the end of a block scope.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="style"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if more than <see cref="MaxStyles" /> distinct styles are used.</exception> /// <seealso cref="EndStyle"/> public DisposableCookie BeginStyle(Style style) { if (style == null) throw new ArgumentNullException("style"); InternalBeginStyle(style); return new DisposableCookie(EndStyle); } private void InternalBeginStyle(Style style) { int styleIndex = styleTable.AssignIndex(style); // may throw InvalidOperationException due to too many styles styleIndexStack.Push(styleIndex); } /// <summary> /// Pops the current style off the style stack. /// Subsequently appended content will use the previous style. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the style stack only contains the default style.</exception> /// <seealso cref="BeginStyle"/> public void EndStyle() { if (styleIndexStack.Count <= 1) throw new InvalidOperationException("The style stack only contains the default style which cannot be popped."); styleIndexStack.Pop(); } /// <summary> /// Pushes an annotation value onto the keyed annotation stack. /// Subsequently appended content will acquire the new annotation value. /// </summary> /// <remarks> /// <para> /// Each annotation key has its own separate stack. /// </para> /// </remarks> /// <example> /// <code> /// using (document.BeginStyle(linkStyle)) /// { /// using (document.BeginAnnotation("href", "http://www.gallio.org")) /// { /// document.AppendText("Gallio"); /// } /// } /// </code> /// </example> /// <param name="key">The annotation key.</param> /// <param name="value">The annotation value.</param> /// <returns>A value that when disposed automatically calls <see cref="EndAnnotation{T}"/>. /// Used with the C# "using" syntax to end the annotation at the end of a block scope.</returns> /// <seealso cref="EndAnnotation{T}"/> public DisposableCookie BeginAnnotation<T>(Key<T> key, T value) { InternalBeginAnnotation(key, value); return new DisposableCookie(() => EndAnnotation(key)); } private void InternalBeginAnnotation<T>(Key<T> key, T value) { AnnotationTable<T> annotationTable = GetAnnotationTable(key, true); annotationTable.BeginValue(CharCount, value); } /// <summary> /// Pushes an annotation value onto the keyed annotation stack. /// Subsequently appended content will acquire the new annotation value. /// </summary> /// <remarks> /// <para> /// Each annotation key has its own separate stack. /// </para> /// </remarks> /// <param name="key">The annotation key.</param> /// <exception cref="InvalidOperationException">Thrown if there is no current annotation with the /// specified key.</exception> /// <seealso cref="BeginAnnotation{T}"/> public void EndAnnotation<T>(Key<T> key) { AnnotationTable<T> annotationTable = GetAnnotationTable(key, false); if (annotationTable == null || !annotationTable.TryEndValue(CharCount)) throw new InvalidOperationException(string.Format("There is no current annotation with key '{0}'.", key.Name)); } /// <summary> /// Returns the plain text content of the document as a string. /// </summary> /// <returns></returns> public override string ToString() { return GetTextRange(0, CharCount); } private void InternalAppendText(int styleIndex, string text) { int length = text.Length; fixed (char* textPtr = text) { char* source = textPtr; char* sourceEnd = source + length; char* mark = source; for (; source != sourceEnd; source++) { char ch = *source; if (char.IsControl(ch)) { if (ch == '\n') { char* next = source + 1; InternalAppendChars(styleIndex, mark, (int)(next - mark)); mark = next; InternalStartParagraph(); } else if (ch == '\t') { if (mark != source) InternalAppendChars(styleIndex, mark, (int)(source - mark)); InternalAppendTabRun(styleIndex); mark = source + 1; } else { // Discard all other control characters. if (mark != source) InternalAppendChars(styleIndex, mark, (int) (source - mark)); mark = source + 1; } } } if (mark != source) InternalAppendChars(styleIndex, mark, (int)(source - mark)); } } private void InternalAppendChars(int styleIndex, char* source, int count) { InternalEnsureTextRun(styleIndex); int charIndex = charBuffer.Count; charBuffer.GrowBy(count); char* chars = GetCharZero() + charIndex; currentParagraph->CharCount += count; int newCount = currentRun->CharCount + count; while (newCount > MaxCharsPerRun) { currentRun->CharCount = MaxCharsPerRun; newCount -= MaxCharsPerRun; InternalStartTextRun(styleIndex); } currentRun->CharCount = newCount; while (count-- > 0) *(chars++) = *(source++); } private void InternalStartParagraph() { Debug.Assert(currentRun != null || currentParagraph == null, "At least one run should be added to the current paragraph before a new one is started."); int paragraphIndex = paragraphBuffer.Count; paragraphBuffer.GrowBy(1); currentParagraph = GetParagraphZero() + paragraphIndex; currentParagraph->Initialize(charBuffer.Count, 0, runBuffer.Count, 0); currentRun = null; } private void InternalEnsureTextRun(int styleIndex) { if (currentRun != null && currentRun->RunKind == RunKind.Text && currentRun->StyleIndex == styleIndex) return; InternalStartTextRun(styleIndex); } private void InternalStartTextRun(int styleIndex) { int runIndex = runBuffer.Count; runBuffer.GrowBy(1); currentRun = GetRunZero() + runIndex; currentRun->InitializeTextRun(styleIndex); currentParagraph->RunCount += 1; } private void InternalAppendObject(int styleIndex, EmbeddedObject obj) { int objectIndex = objectTable.AssignIndex(obj); int runIndex = runBuffer.Count; runBuffer.GrowBy(1); int charIndex = charBuffer.Count; charBuffer.GrowBy(1); currentRun = GetRunZero() + runIndex; currentRun->InitializeObjectRun(styleIndex, objectIndex); char* chars = GetCharZero() + charIndex; *chars = ObjectRunPlaceholderChar; currentParagraph->RunCount += 1; currentParagraph->CharCount += 1; } private void InternalAppendTabRun(int styleIndex) { int runIndex = runBuffer.Count; runBuffer.GrowBy(1); int charIndex = charBuffer.Count; charBuffer.GrowBy(1); currentRun = GetRunZero() + runIndex; currentRun->InitializeTabRun(styleIndex); char* chars = GetCharZero() + charIndex; *chars = '\t'; currentParagraph->RunCount += 1; currentParagraph->CharCount += 1; } private void RaiseDocumentCleared() { if (DocumentCleared != null) DocumentCleared(this, EventArgs.Empty); } private void RaiseParagraphChanged(int paragraphIndex) { if (ParagraphChanged != null) ParagraphChanged(this, new ParagraphChangedEventArgs(paragraphIndex)); } internal Style LookupStyle(int styleIndex) { return styleTable[styleIndex]; } internal EmbeddedObject LookupObject(int objectIndex) { return objectTable[objectIndex]; } internal char* GetCharZero() { return (char*)charBuffer.GetPointer(); } internal Run* GetRunZero() { return (Run*)runBuffer.GetPointer(); } internal Paragraph* GetParagraphZero() { return (Paragraph*)paragraphBuffer.GetPointer(); } internal int StyleCount { get { return styleTable.Count; } } internal int ObjectCount { get { return objectTable.Count; } } internal int RunCount { get { return runBuffer.Count; } } internal int CurrentParagraphIndex { get { return ParagraphCount - 1; } } private int CurrentStyleIndex { get { return styleIndexStack.Peek(); } } private Paragraph* GetParagraphAtCharacterIndex(int index, out int paragraphIndex) { Paragraph* paragraphZero = GetParagraphZero(); int paragraphCount = ParagraphCount; int low = 0; int high = paragraphCount; while (low < high) { int mid = (low + high) / 2; int candidateCharIndex = paragraphZero[mid].CharIndex; if (candidateCharIndex > index) { high = mid; } else if (candidateCharIndex + paragraphZero[mid].CharCount < index) { low = mid + 1; } else { paragraphIndex = mid; return paragraphZero + mid; } } paragraphIndex = -1; return null; } private Run* GetRunAtCharacterIndex(int index, out int runIndex) { int paragraphIndex; Paragraph* paragraph = GetParagraphAtCharacterIndex(index, out paragraphIndex); if (paragraph != null) { int remainingOffset = index - paragraph->CharIndex; Run* startRun = GetRunZero() + paragraph->RunIndex; Run* endRun = startRun + paragraph->RunCount; for (Run* run = startRun; run != endRun; run++) { remainingOffset -= run->CharCount; if (remainingOffset < 0) { runIndex = (int) (run - startRun); return run; } } } runIndex = -1; return null; } private void ValidateCharacterRange(int start, int length) { if (start < 0) throw new ArgumentOutOfRangeException("start", start, "The start index must be at least 0."); if (length < 0) throw new ArgumentOutOfRangeException("length", length, "The length must be at least 0."); if (start + length > CharCount) throw new ArgumentOutOfRangeException("start", "The range must be within the document."); } private void ValidateCharacterIndex(int index) { if (index < 0 || index >= CharCount) throw new ArgumentOutOfRangeException("index", index, "The index must be within the bounds of the document."); } private Run* ValidateCharacterIndexAndGetRun(int index) { ValidateCharacterIndex(index); int runIndex; Run* run = GetRunAtCharacterIndex(index, out runIndex); Debug.Assert(run != null, "We should have found a run at the character index since the index was within the bounds of the document."); return run; } private AnnotationTable<T> GetAnnotationTable<T>(Key<T> key, bool createIfAbsent) { object annotationTable; if (! annotationTables.TryGetValue(key.Name, out annotationTable) && createIfAbsent) { annotationTable = new AnnotationTable<T>(); annotationTables.Add(key.Name, annotationTable); } return (AnnotationTable<T>) annotationTable; } private sealed class AnnotationTable<T> { private readonly Stack<T> valueStack; private readonly List<KeyValuePair<int, T>> runs; public AnnotationTable() { valueStack = new Stack<T>(); runs = new List<KeyValuePair<int, T>>(); } public bool TryGetCurrentValue(out T value) { if (valueStack.Count != 0) { value = valueStack.Peek(); return true; } value = default(T); return false; } public bool TryGetValueAtIndex(int index, out T value) { int low = 0; int high = runs.Count; while (low < high) { int mid = (low + high) / 2; if (Math.Abs(runs[mid].Key) > index) { high = mid; } else if (mid + 1 < high && Math.Abs(runs[mid + 1].Key) < index) { low = mid + 1; } else { if (runs[mid].Key < 0) break; value = runs[mid].Value; return true; } } value = default(T); return false; } public void BeginValue(int index, T value) { valueStack.Push(value); RemoveSentinel(index); runs.Add(new KeyValuePair<int, T>(index, value)); } public bool TryEndValue(int index) { if (valueStack.Count == 0) return false; valueStack.Pop(); RemoveSentinel(index); if (valueStack.Count == 0) { if (index != 0) runs.Add(new KeyValuePair<int, T>(-index, default(T))); } else { runs.Add(new KeyValuePair<int, T>(index, valueStack.Peek())); } return true; } private void RemoveSentinel(int index) { if (runs.Count != 0 && index == Math.Abs(runs[runs.Count - 1].Key)) runs.RemoveAt(runs.Count - 1); } } } }
using System; using System.Runtime; using System.Runtime.InteropServices; using System.Security; namespace System.Management { public class ConnectionOptions : ManagementOptions { private string locale; private string username; private SecureString securePassword; private string authority; private ImpersonationLevel impersonation; private AuthenticationLevel authentication; private bool enablePrivileges; internal const string DEFAULTLOCALE = null; internal const string DEFAULTAUTHORITY = null; internal const ImpersonationLevel DEFAULTIMPERSONATION = ImpersonationLevel.Impersonate; internal const AuthenticationLevel DEFAULTAUTHENTICATION = AuthenticationLevel.Unchanged; internal const bool DEFAULTENABLEPRIVILEGES = false; public AuthenticationLevel Authentication { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.authentication; } set { if (this.authentication != value) { this.authentication = value; base.FireIdentifierChanged(); } } } public string Authority { get { if (this.authority != null) { return this.authority; } else { return string.Empty; } } set { if (this.authority != value) { this.authority = value; base.FireIdentifierChanged(); } } } public bool EnablePrivileges { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.enablePrivileges; } set { if (this.enablePrivileges != value) { this.enablePrivileges = value; base.FireIdentifierChanged(); } } } public ImpersonationLevel Impersonation { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.impersonation; } set { if (this.impersonation != value) { this.impersonation = value; base.FireIdentifierChanged(); } } } public string Locale { get { if (this.locale != null) { return this.locale; } else { return string.Empty; } } set { if (this.locale != value) { this.locale = value; base.FireIdentifierChanged(); } } } public string Password { set { if (value == null) { if (this.securePassword != null) { this.securePassword.Dispose(); this.securePassword = null; base.FireIdentifierChanged(); } return; } else { if (this.securePassword != null) { SecureString secureString = new SecureString(); for (int i = 0; i < value.Length; i++) { secureString.AppendChar(value[i]); } this.securePassword.Clear(); this.securePassword = secureString.Copy(); base.FireIdentifierChanged(); secureString.Dispose(); return; } else { this.securePassword = new SecureString(); for (int j = 0; j < value.Length; j++) { this.securePassword.AppendChar(value[j]); } return; } } } } public SecureString SecurePassword { set { if (value == null) { if (this.securePassword != null) { this.securePassword.Dispose(); this.securePassword = null; base.FireIdentifierChanged(); } return; } else { if (this.securePassword != null) { this.securePassword.Clear(); this.securePassword = value.Copy(); base.FireIdentifierChanged(); return; } else { this.securePassword = value.Copy(); return; } } } } public string Username { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.username; } set { if (this.username != value) { this.username = value; base.FireIdentifierChanged(); } } } public ConnectionOptions() : this((string)null, (string)null, (string)null, (string)null, (ImpersonationLevel)3, (AuthenticationLevel)(-1), false, (ManagementNamedValueCollection)null, ManagementOptions.InfiniteTimeout) { } public ConnectionOptions(string locale, string username, string password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) { this.locale = locale; } this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = new SecureString(); for (int i = 0; i < password.Length; i++) { this.securePassword.AppendChar(password[i]); } } if (authority != null) { this.authority = authority; } if (impersonation != ImpersonationLevel.Default) { this.impersonation = impersonation; } if (authentication != AuthenticationLevel.Default) { this.authentication = authentication; } } public ConnectionOptions(string locale, string username, SecureString password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) { this.locale = locale; } this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = password.Copy(); } if (authority != null) { this.authority = authority; } if (impersonation != ImpersonationLevel.Default) { this.impersonation = impersonation; } if (authentication != AuthenticationLevel.Default) { this.authentication = authentication; } } internal ConnectionOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) : base(context, timeout, flags) { } internal ConnectionOptions(ManagementNamedValueCollection context) : base(context, ManagementOptions.InfiniteTimeout) { } internal static ConnectionOptions _Clone(ConnectionOptions options) { return ConnectionOptions._Clone(options, null); } internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierChangedEventHandler handler) { ConnectionOptions connectionOption; if (options == null) { connectionOption = new ConnectionOptions(); } else { connectionOption = new ConnectionOptions(options.Context, options.Timeout, options.Flags); connectionOption.locale = options.locale; connectionOption.username = options.username; connectionOption.enablePrivileges = options.enablePrivileges; if (options.securePassword == null) { connectionOption.securePassword = null; } else { connectionOption.securePassword = options.securePassword.Copy(); } if (options.authority != null) { connectionOption.authority = options.authority; } if (options.impersonation != ImpersonationLevel.Default) { connectionOption.impersonation = options.impersonation; } if (options.authentication != AuthenticationLevel.Default) { connectionOption.authentication = options.authentication; } } if (handler == null) { if (options != null) { connectionOption.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); } } else { connectionOption.IdentifierChanged += handler; } return connectionOption; } public override object Clone() { ManagementNamedValueCollection managementNamedValueCollection = null; if (base.Context != null) { managementNamedValueCollection = base.Context.Clone(); } return new ConnectionOptions(this.locale, this.username, this.GetSecurePassword(), this.authority, this.impersonation, this.authentication, this.enablePrivileges, managementNamedValueCollection, base.Timeout); } internal IntPtr GetPassword() { IntPtr bSTR; if (this.securePassword == null) { return IntPtr.Zero; } else { try { bSTR = Marshal.SecureStringToBSTR(this.securePassword); } catch (OutOfMemoryException outOfMemoryException) { bSTR = IntPtr.Zero; } return bSTR; } } internal SecureString GetSecurePassword() { if (this.securePassword == null) { return null; } else { return this.securePassword.Copy(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using CustomDevice; using System.Drawing.Drawing2D; namespace Snake { class SnakePit { private const int cellSize = 8; private const int scoreBoardHeight = 48; private Graphics screen; private int cellOfsX, cellOfsY; private int numCellsX, numCellsY; private Random rnd; private Point[] food; private List<ASnake> snakes = new List<ASnake>(); private int score, level; private List<Point[]> obstacles = new List<Point[]>(); public SnakePit() { this.screen = DeviceGraphics.GetScreen(); this.screen.Clear(Color.White); this.numCellsX = (DeviceGraphics.ScreenXSize / cellSize) - 2; this.numCellsY = ((DeviceGraphics.ScreenYSize - scoreBoardHeight) / cellSize) - 2; this.cellOfsX = cellSize; this.cellOfsY = cellSize; this.rnd = new Random(); this.food = null; this.score = 0; this.level = 1; using (Brush brush = new HatchBrush(HatchStyle.DiagonalCross, Color.Black, Color.White)) { this.screen.FillRectangle(brush, 0, 0, DeviceGraphics.ScreenXSize, cellSize); this.screen.FillRectangle(brush, 0, cellSize, cellSize, this.numCellsY * cellSize); this.screen.FillRectangle(brush, (1 + this.numCellsX) * cellSize, cellSize, cellSize, this.numCellsY * cellSize); this.screen.FillRectangle(brush, 0, (1 + this.numCellsY) * cellSize, DeviceGraphics.ScreenXSize, cellSize); } this.screen.DrawRectangle(Pens.Black, cellSize - 1, cellSize - 1, this.numCellsX * cellSize + 1, this.numCellsY * cellSize + 1); using (Font f = new Font("tahoma", 15)) { using (StringFormat sf = new StringFormat()) { sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; this.screen.DrawString("<", f, Brushes.Black, new RectangleF(0, 220, 64, 20), sf); this.screen.DrawString("v", f, Brushes.Black, new RectangleF(64, 220, 64, 20), sf); this.screen.DrawString("^", f, Brushes.Black, new RectangleF(128, 220, 64, 20), sf); this.screen.DrawString(">", f, Brushes.Black, new RectangleF(192, 220, 64, 20), sf); } } this.ShowScore(); } private void FillCell(Point cell, Color col) { using (Brush brush = new SolidBrush(col)) { screen.FillRectangle(brush, this.cellOfsX + cell.X * cellSize, this.cellOfsY + cell.Y * cellSize, cellSize, cellSize); } } public void FillAndOutlineCells(IEnumerable<Point> points, Color fillCol, Color outlineCol) { using (Brush brush = new SolidBrush(fillCol)) { this.FillAndOutlineCells(points, brush, outlineCol); } } public void FillAndOutlineCells(IEnumerable<Point> points, Brush fillBrush, Color outlineCol) { int minX = int.MaxValue, maxX = int.MinValue; int minY = int.MaxValue, maxY = int.MinValue; foreach (Point p in points) { minX = Math.Min(minX, p.X); maxX = Math.Max(maxX, p.X); minY = Math.Min(minY, p.Y); maxY = Math.Max(maxY, p.Y); } int x = this.cellOfsX + minX * cellSize; int y = this.cellOfsY + minY * cellSize; int width = (maxX - minX + 1) * cellSize; int height = (maxY - minY + 1) * cellSize; this.screen.FillRectangle(fillBrush, x, y, width, height); using (Pen pen = new Pen(outlineCol)) { this.screen.DrawRectangle(pen, x, y, width - 1, height - 1); } } public void AddSnake(ASnake snake) { this.snakes.Add(snake); } public Point Centre { get { return new Point(numCellsX >> 1, numCellsY >> 1); } } public Size Size { get { return new Size(numCellsX, numCellsY); } } public void SetCell(Point cell, Color col) { this.FillCell(cell, col); } public void ClearCell(Point cell) { this.FillCell(cell, Color.White); } public bool IsCrashObstacle(Point cell) { foreach (Point[] obs in this.obstacles) { foreach (Point pt in obs) { if (pt == cell) { return true; } } } return false; } public CrashType IsCrash(Point cell) { if (cell.X < 0 || cell.X >= this.numCellsX || cell.Y < 0 || cell.Y >= this.numCellsY) { return CrashType.Wall; } if (this.IsCrashObstacle(cell)) { return CrashType.Wall; } if (this.food != null) { for (int i = 0; i < this.food.Length; i++) { if (this.food[i] == cell) { return CrashType.Food; } } } return CrashType.None; } public void CreateFood(bool canMoveFood) { if (this.food != null && !canMoveFood) { // Don't move the food return; } this.RemoveFood(); Point[] newFood; for (; ; ) { int x = this.rnd.Next(this.numCellsX - 1); int y = this.rnd.Next(this.numCellsY - 1); newFood = new Point[4]; newFood[0] = new Point(x, y); newFood[1] = new Point(x + 1, y); newFood[2] = new Point(x, y + 1); newFood[3] = new Point(x + 1, y + 1); bool ok = true; foreach (ASnake snake in this.snakes) { if (snake.DoesIntersect(newFood)) { ok = false; break; } } if (ok) { foreach (Point pt in newFood) { if (IsCrashObstacle(pt)) { ok = false; break; } } } if (ok) { break; } } this.food = newFood; this.FillAndOutlineCells(this.food, Color.Gray, Color.Black); } public void RemoveFood() { if (this.food == null) { return; } for (int i = 0; i < this.food.Length; i++) { this.ClearCell(this.food[i]); } this.food = null; } public bool EatFood() { this.RemoveFood(); this.score++; bool ret = false; if (this.score >= this.level * 4) { this.level++; ret = true; } this.ShowScore(); return ret; } public void Msg(string msg) { using (Font f = new Font("tahoma", 40)) { this.screen.DrawString(msg, f, Brushes.Black, 30, 80); } } public void ShowScore() { this.screen.FillRectangle(Brushes.White, 0, DeviceGraphics.ScreenYSize - scoreBoardHeight, DeviceGraphics.ScreenXSize, scoreBoardHeight - 20); using (Font f = new Font("tahoma", 15)) { string s = string.Format("Level: {0}", this.level); this.screen.DrawString(s, f, Brushes.Black, 0, DeviceGraphics.ScreenYSize - scoreBoardHeight); s = string.Format("Score: {0}", this.score); this.screen.DrawString(s, f, Brushes.Black, DeviceGraphics.ScreenXSize >> 1, DeviceGraphics.ScreenYSize - scoreBoardHeight); } } public int Level { get { return this.level; } } private int Dist(Point a, Point b) { int dx = a.X - b.Y; int dy = a.Y - b.Y; return Math.Max(Math.Abs(dx), Math.Abs(dy)); } public void AddObsticle() { Point[] obs; for (; ; ) { int x = this.rnd.Next(this.numCellsX - 1); int y = this.rnd.Next(this.numCellsY - 1); obs = new Point[4]; obs[0] = new Point(x, y); obs[1] = new Point(x + 1, y); obs[2] = new Point(x, y + 1); obs[3] = new Point(x + 1, y + 1); bool ok = true; foreach (ASnake snake in this.snakes) { if (snake.DoesIntersect(obs) || this.Dist(snake.Head, obs[0]) < 10) { ok = false; break; } } if (ok) { break; } } using (HatchBrush brush = new HatchBrush(HatchStyle.DiagonalCross,Color.Black, Color.White)) { this.FillAndOutlineCells(obs, brush, Color.Black); } this.obstacles.Add(obs); if (this.obstacles.Count > this.Level * 2) { // Remove an obstacle obs = this.obstacles[0]; foreach (Point pt in obs) { this.ClearCell(pt); } this.obstacles.RemoveAt(0); } } } }
// 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 Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PrimitiveOperations. /// </summary> public static partial class PrimitiveOperationsExtensions { /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IntWrapper GetInt(this IPrimitiveOperations operations) { return operations.GetIntAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IntWrapper> GetIntAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> public static void PutInt(this IPrimitiveOperations operations, IntWrapper complexBody) { operations.PutIntAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutIntAsync(this IPrimitiveOperations operations, IntWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LongWrapper GetLong(this IPrimitiveOperations operations) { return operations.GetLongAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LongWrapper> GetLongAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> public static void PutLong(this IPrimitiveOperations operations, LongWrapper complexBody) { operations.PutLongAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLongAsync(this IPrimitiveOperations operations, LongWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static FloatWrapper GetFloat(this IPrimitiveOperations operations) { return operations.GetFloatAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FloatWrapper> GetFloatAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> public static void PutFloat(this IPrimitiveOperations operations, FloatWrapper complexBody) { operations.PutFloatAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutFloatAsync(this IPrimitiveOperations operations, FloatWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DoubleWrapper GetDouble(this IPrimitiveOperations operations) { return operations.GetDoubleAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DoubleWrapper> GetDoubleAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> public static void PutDouble(this IPrimitiveOperations operations, DoubleWrapper complexBody) { operations.PutDoubleAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDoubleAsync(this IPrimitiveOperations operations, DoubleWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static BooleanWrapper GetBool(this IPrimitiveOperations operations) { return operations.GetBoolAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BooleanWrapper> GetBoolAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> public static void PutBool(this IPrimitiveOperations operations, BooleanWrapper complexBody) { operations.PutBoolAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBoolAsync(this IPrimitiveOperations operations, BooleanWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static StringWrapper GetString(this IPrimitiveOperations operations) { return operations.GetStringAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StringWrapper> GetStringAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> public static void PutString(this IPrimitiveOperations operations, StringWrapper complexBody) { operations.PutStringAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutStringAsync(this IPrimitiveOperations operations, StringWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateWrapper GetDate(this IPrimitiveOperations operations) { return operations.GetDateAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateWrapper> GetDateAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> public static void PutDate(this IPrimitiveOperations operations, DateWrapper complexBody) { operations.PutDateAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateAsync(this IPrimitiveOperations operations, DateWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DatetimeWrapper GetDateTime(this IPrimitiveOperations operations) { return operations.GetDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DatetimeWrapper> GetDateTimeAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> public static void PutDateTime(this IPrimitiveOperations operations, DatetimeWrapper complexBody) { operations.PutDateTimeAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateTimeAsync(this IPrimitiveOperations operations, DatetimeWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Datetimerfc1123Wrapper GetDateTimeRfc1123(this IPrimitiveOperations operations) { return operations.GetDateTimeRfc1123Async().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Datetimerfc1123Wrapper> GetDateTimeRfc1123Async(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateTimeRfc1123WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 /// GMT' /// </param> public static void PutDateTimeRfc1123(this IPrimitiveOperations operations, Datetimerfc1123Wrapper complexBody) { operations.PutDateTimeRfc1123Async(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 /// GMT' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateTimeRfc1123Async(this IPrimitiveOperations operations, Datetimerfc1123Wrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutDateTimeRfc1123WithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DurationWrapper GetDuration(this IPrimitiveOperations operations) { return operations.GetDurationAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DurationWrapper> GetDurationAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> public static void PutDuration(this IPrimitiveOperations operations, System.TimeSpan? field = default(System.TimeSpan?)) { operations.PutDurationAsync(field).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDurationAsync(this IPrimitiveOperations operations, System.TimeSpan? field = default(System.TimeSpan?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutDurationWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ByteWrapper GetByte(this IPrimitiveOperations operations) { return operations.GetByteAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ByteWrapper> GetByteAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> public static void PutByte(this IPrimitiveOperations operations, byte[] field = default(byte[])) { operations.PutByteAsync(field).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutByteAsync(this IPrimitiveOperations operations, byte[] field = default(byte[]), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PutByteWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
// 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: Convenient wrapper for an array, an offset, and ** a count. Ideally used in streams & collections. ** Net Classes will consume an array of these. ** ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System { // Note: users should make sure they copy the fields out of an ArraySegment onto their stack // then validate that the fields describe valid bounds within the array. This must be done // because assignments to value types are not atomic, and also because one thread reading // three fields from an ArraySegment may not see the same ArraySegment from one call to another // (ie, users could assign a new value to the old location). [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of // instantiating another generic type in addition to ArraySegment<T> for new type parameters. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]); private readonly T[] _array; // Do not rename (binary serialization) private readonly int _offset; // Do not rename (binary serialization) private readonly int _count; // Do not rename (binary serialization) public ArraySegment(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path // Negative values discovered though conversion to high values when converted to unsigned // Failure should be rare and location determination and message is delegated to failure functions if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); _array = array; _offset = offset; _count = count; } public T[] Array => _array; public int Offset => _offset; public int Count => _count; public T this[int index] { get { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _array[_offset + index]; } set { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _array[_offset + index] = value; } } public Enumerator GetEnumerator() { ThrowInvalidOperationIfDefault(); return new Enumerator(this); } public override int GetHashCode() { if (_array == null) { return 0; } int hash = 5381; hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset); hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count); // The array hash is expected to be an evenly-distributed mixture of bits, // so rather than adding the cost of another rotation we just xor it. hash ^= _array.GetHashCode(); return hash; } public void CopyTo(T[] destination) => CopyTo(destination, 0); public void CopyTo(T[] destination, int destinationIndex) { ThrowInvalidOperationIfDefault(); System.Array.Copy(_array, _offset, destination, destinationIndex, _count); } public void CopyTo(ArraySegment<T> destination) { ThrowInvalidOperationIfDefault(); destination.ThrowInvalidOperationIfDefault(); if (_count > destination._count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } public override bool Equals(Object obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); else return false; } public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } public ArraySegment<T> Slice(int index) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment<T>(_array, _offset + index, _count - index); } public ArraySegment<T> Slice(int index, int count) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment<T>(_array, _offset + index, count); } public T[] ToArray() { ThrowInvalidOperationIfDefault(); if (_count == 0) { return Empty._array; } var array = new T[_count]; System.Array.Copy(_array, _offset, array, 0, _count); return array; } public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } public static implicit operator ArraySegment<T>(T[] array) => array != null ? new ArraySegment<T>(array) : default; #region IList<T> T IList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); return _array[_offset + index]; } set { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); _array[_offset + index] = value; } } int IList<T>.IndexOf(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; } void IList<T>.Insert(int index, T item) { ThrowHelper.ThrowNotSupportedException(); } void IList<T>.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(); } #endregion #region IReadOnlyList<T> T IReadOnlyList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); return _array[_offset + index]; } } #endregion IReadOnlyList<T> #region ICollection<T> bool ICollection<T>.IsReadOnly { get { // the indexer setter does not throw an exception although IsReadOnly is true. // This is to match the behavior of arrays. return true; } } void ICollection<T>.Add(T item) { ThrowHelper.ThrowNotSupportedException(); } void ICollection<T>.Clear() { ThrowHelper.ThrowNotSupportedException(); } bool ICollection<T>.Contains(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; } bool ICollection<T>.Remove(T item) { ThrowHelper.ThrowNotSupportedException(); return default(bool); } #endregion #region IEnumerable<T> IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion private void ThrowInvalidOperationIfDefault() { if (_array == null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); } } public struct Enumerator : IEnumerator<T> { private readonly T[] _array; private readonly int _start; private readonly int _end; // cache Offset + Count, since it's a little slow private int _current; internal Enumerator(ArraySegment<T> arraySegment) { Debug.Assert(arraySegment.Array != null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment.Array; _start = arraySegment.Offset; _end = arraySegment.Offset + arraySegment.Count; _current = arraySegment.Offset - 1; } public bool MoveNext() { if (_current < _end) { _current++; return (_current < _end); } return false; } public T Current { get { if (_current < _start) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_current >= _end) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array[_current]; } } object IEnumerator.Current => Current; void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Test.Azure.Management.Logic { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Microsoft.Azure.Management.Logic; using Microsoft.Azure.Management.Logic.Models; using Microsoft.Rest; using Microsoft.Rest.Azure; using Xunit; public class WorkflowsInMemoryTests : InMemoryTestsBase { #region Constructor private StringContent Workflow { get; set; } private StringContent WorkflowRun { get; set; } private StringContent WorkflowList { get; set; } public WorkflowsInMemoryTests() { var workflow = @"{ 'id': '/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName', 'name': 'wfName', 'type':'Microsoft.Logic/workflows', 'location':'westus', 'properties': { 'createdTime': '2015-06-23T21:47:00.0000001Z', 'changedTime':'2015-06-23T21:47:30.0000002Z', 'state':'Enabled', 'version':'08587717906782501130', 'accessEndpoint':'https://westus.logic.azure.com/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName', 'sku':{ 'name':'Premium', 'plan':{ 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Web/serverFarms/planName', 'type':'Microsoft.Web/serverFarms', 'name':'planName' } }, 'definition':{ '$schema':'http://schema.management.azure.com/providers/Microsoft.Logic/schemas/2014-12-01-preview/workflowdefinition.json#', 'contentVersion':'1.0.0.0', 'parameters':{ 'runworkflowmanually':{ 'defaultValue':true, 'type':'Bool' }, 'subscription':{ 'defaultValue':'66666666-6666-6666-6666-666666666666', 'type':'String' }, 'resourceGroup':{ 'defaultValue':'logicapps-e2e', 'type':'String' }, 'authentication':{ 'defaultValue':{ 'type':'ActiveDirectoryOAuth', 'audience':'https://management.azure.com/', 'tenant':'66666666-6666-6666-6666-666666666666', 'clientId':'66666666-6666-6666-6666-666666666666', 'secret':'<placeholder>' }, 'type':'Object' } }, 'triggers':{ }, 'actions':{ 'listWorkflows':{ 'type':'Http', 'inputs':{ 'method':'GET', 'uri':'someUri', 'authentication':'@parameters(""authentication"")' }, 'conditions':[ ] } }, 'outputs':{ } }, 'parameters':{ 'parameter1':{ 'type': 'string', 'value': 'abc' }, 'parameter2':{ 'type': 'array', 'value': [1, 2, 3] } } } }"; var run = @"{ 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/runs/run87646872399558047', 'name':'run87646872399558047', 'type':'Microsoft.Logic/workflows/runs', 'properties':{ 'startTime':'2015-06-23T21:47:00.0000000Z', 'endTime':'2015-06-23T21:47:30.1300000Z', 'status':'Succeeded', 'correlationId':'a04da054-a1ae-409d-80ff-b09febefc357', 'workflow':{ 'name':'wfName/ver87717906782501130', 'id':'/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName/versions/ver87717906782501130', 'type':'Microsoft.Logic/workflows/versions' }, 'trigger':{ 'name':'6A65DA9E-CFF8-4D3E-B5FB-691739C7AD61' }, 'outputs':{ } } }"; var workflowListFormat = @"{{ 'value':[ {0} ], 'nextLink': 'http://workflowlist1nextlink' }}"; this.Workflow = new StringContent(workflow); this.WorkflowRun = new StringContent(run); this.WorkflowList = new StringContent(string.Format(workflowListFormat, workflow)); } #endregion #region Workflows_ListBySubscription [Fact] public void Workflows_ListBySubscription_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<CloudException>(() => client.Workflows.ListBySubscription()); } public void Workflows_ListBySubscription_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroup("rgName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListBySubscriptionNext [Fact] public void Workflows_ListBySubscriptionNext_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListBySubscriptionNext(null)); Assert.Throws<CloudException>(() => client.Workflows.ListBySubscriptionNext("http://management.azure.com/nextLink")); } public void Workflows_ListBySubscriptionNext_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListBySubscriptionNext("http://management.azure.com/nextLink"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListByResourceGroup [Fact] public void Workflows_ListByResourceGroup_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListByResourceGroup(null)); Assert.Throws<CloudException>(() => client.Workflows.ListByResourceGroup("rgName")); } [Fact] public void Workflows_ListByResourceGroup_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroup("rgName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_ListByResourceGroupNext [Fact] public void Workflows_ListByResourceGroupNext_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.ListByResourceGroupNext(null)); Assert.Throws<CloudException>(() => client.Workflows.ListByResourceGroupNext("http://management.azure.com/nextLink")); } public void Workflows_ListByResourceGroupNext_Success() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.WorkflowList }; var result = client.Workflows.ListByResourceGroupNext("http://management.azure.com/nextLink"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflowList1(result); } #endregion #region Workflows_CreateOrUpdate [Fact] public void Workflows_CreateOrUpdate_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate(null, "wfName", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate("rgName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.CreateOrUpdate("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow())); } [Fact] public void Workflows_CreateOrUpdate_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var workflow = client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow()); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Put); // Validates result. this.ValidateWorkflow1(workflow); } [Fact] public void Workflows_CreateOrUpdate_Created() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created, Content = this.Workflow }; var workflow = client.Workflows.CreateOrUpdate("rgName", "wfName", new Workflow()); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Put); // Validates result. this.ValidateWorkflow1(workflow); } #endregion #region Workflows_Delete [Fact] public void Workflows_Delete_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound }; Assert.Throws<ValidationException>(() => client.Workflows.Delete(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Delete("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Delete("rgName", "wfName")); } [Fact] public void Workflows_Delete_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Delete("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Delete); } [Fact] public void Workflows_Delete_NoContent() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent }; client.Workflows.Delete("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Delete); } #endregion #region Workflows_Get [Fact] public void Workflows_Get_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.Get(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Get("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Get("rgName", "wfName")); } [Fact] public void Workflows_Get_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var result = client.Workflows.Get("rgName", "wfName"); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(HttpMethod.Get); // Validates result. this.ValidateWorkflow1(result); } #endregion #region Workflows_Update [Fact] public void Workflows_Update_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.Update(null, "wfName", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Update("rgName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Update("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.Update("rgName", "wfName", new Workflow())); } [Fact] public void Workflows_Update_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; var workflow = new Workflow() { Tags = new Dictionary<string, string>() }; workflow.Tags.Add("abc", "def"); workflow = client.Workflows.Update("rgName", "wfName", workflow); // Validates request. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateMethod(new HttpMethod("PATCH")); // Validates result. this.ValidateWorkflow1(workflow); } #endregion #region Workflows_Disable [Fact] public void Workflows_Disable_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Disable(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Disable("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Disable("rgName", "wfName")); } [Fact] public void Workflows_Disable_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Disable("rgName", "wfName"); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("disable"); } #endregion #region Workflows_Enable [Fact] public void Workflows_Enable_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Enable(null, "wfName")); Assert.Throws<ValidationException>(() => client.Workflows.Enable("rgName", null)); Assert.Throws<CloudException>(() => client.Workflows.Enable("rgName", "wfName")); } [Fact] public void Workflows_Enable_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Enable("rgName", "wfName"); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("enable"); } #endregion #region Workflows_Validate [Fact] public void Workflows_Validate_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; Assert.Throws<ValidationException>(() => client.Workflows.Validate(null, "wfName", "westus", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", null, "westus", new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", "wfName", null, new Workflow())); Assert.Throws<ValidationException>(() => client.Workflows.Validate("rgName", "wfName", "westus", null)); Assert.Throws<CloudException>(() => client.Workflows.Validate("rgName", "wfName", "westus", new Workflow())); } [Fact] public void Workflows_Validate_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; client.Workflows.Validate("rgName", "wfName", "westus", new Workflow()); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("validate"); } #endregion #region Workflows_GenerateUpgradedDefinition [Fact] public void Workflows_GenerateUpgradedDefinition_Exception() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(string.Empty) }; Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition(null, "wfName", new GenerateUpgradedDefinitionParameters("2016-04-01-preview"))); Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", null, new GenerateUpgradedDefinitionParameters("2016-04-01-preview"))); // The Assert is disabled due to the following bug: https://github.com/Azure/autorest/issues/1288. // Assert.Throws<ValidationException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", null)); Assert.Throws<CloudException>(() => client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", new GenerateUpgradedDefinitionParameters("2016-04-01-preview"))); } [Fact] public void Workflows_GenerateUpgradedDefinition_OK() { var handler = new RecordedDelegatingHandler(); var client = this.CreateWorkflowClient(handler); handler.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = this.Workflow }; client.Workflows.GenerateUpgradedDefinition("rgName", "wfName", new GenerateUpgradedDefinitionParameters("2016-04-01-preview")); // Validates requests. handler.Request.ValidateAuthorizationHeader(); handler.Request.ValidateAction("generateUpgradedDefinition"); } #endregion #region Validation private void ValidateWorkflow1(Workflow workflow) { Assert.True(this.ValidateIdFormat(id: workflow.Id, entityTypeName: "workflows")); Assert.Equal("wfName", workflow.Name); Assert.Equal("Microsoft.Logic/workflows", workflow.Type); Assert.Equal("westus", workflow.Location); // 2015-06-23T21:47:00.0000001Z Assert.Equal(2015, workflow.CreatedTime.Value.Year); Assert.Equal(06, workflow.CreatedTime.Value.Month); Assert.Equal(23, workflow.CreatedTime.Value.Day); Assert.Equal(21, workflow.CreatedTime.Value.Hour); Assert.Equal(47, workflow.CreatedTime.Value.Minute); Assert.Equal(00, workflow.CreatedTime.Value.Second); Assert.Equal(DateTimeKind.Utc, workflow.CreatedTime.Value.Kind); // 2015-06-23T21:47:30.0000002Z Assert.Equal(2015, workflow.ChangedTime.Value.Year); Assert.Equal(06, workflow.ChangedTime.Value.Month); Assert.Equal(23, workflow.ChangedTime.Value.Day); Assert.Equal(21, workflow.ChangedTime.Value.Hour); Assert.Equal(47, workflow.ChangedTime.Value.Minute); Assert.Equal(30, workflow.ChangedTime.Value.Second); Assert.Equal(DateTimeKind.Utc, workflow.ChangedTime.Value.Kind); Assert.Equal(WorkflowState.Enabled, workflow.State); Assert.Equal("08587717906782501130", workflow.Version); Assert.Equal("https://westus.logic.azure.com/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Logic/workflows/wfName", workflow.AccessEndpoint); Assert.Equal(SkuName.Premium, workflow.Sku.Name); Assert.Equal("/subscriptions/66666666-6666-6666-6666-666666666666/resourceGroups/rgName/providers/Microsoft.Web/serverFarms/planName", workflow.Sku.Plan.Id); Assert.Equal("Microsoft.Web/serverFarms", workflow.Sku.Plan.Type); Assert.Equal("planName", workflow.Sku.Plan.Name); Assert.NotEmpty(workflow.Definition.ToString()); Assert.Equal(2, workflow.Parameters.Count); Assert.Equal(ParameterType.String, workflow.Parameters["parameter1"].Type); Assert.Equal(ParameterType.Array, workflow.Parameters["parameter2"].Type); } private void ValidateWorkflowList1(IPage<Workflow> result) { Assert.Equal(1, result.Count()); this.ValidateWorkflow1(result.First()); Assert.Equal("http://workflowlist1nextlink", result.NextPageLink); } #endregion } }
using UnityEngine; using System; using System.Linq; using System.Collections.Generic; public enum AnimationMode { Loop, OneShot } public abstract class AnimationSystemBase<T> : MonoBehaviour { #region Variables / Properties public bool DebugMode = false; public float AnimationRate = 0.1f; public AnimationMode AnimationMode; public List<AnimationBase<T>> Animations; public AnimationBase<T> CurrentAnimation; public AnimationBase<T> PreviousAnimation; protected bool _autoPlay = true; protected bool _isLocked = false; protected float _nextFrame; #endregion Variables / Properties #region Engine Hooks public virtual void Start() { if(Animations == null || Animations.Count == 0 || Animations[0] == null) return; CurrentAnimation = Animations[0]; } public virtual void Update () { if(! _autoPlay) return; AdvanceCurrentAnimationOne(); } #endregion Engine Hooks #region Methods public bool AnimationIsComplete() { if(DebugMode) Debug.Log("(" + gameObject.name + ") Animation " + CurrentAnimation.Name + " is " + (CurrentAnimation.IsAnimationCycleDone ? "" : "not") + " done."); return CurrentAnimation.IsAnimationCycleDone; } protected abstract void AdvanceAnimation(); protected virtual void EvaluateAnimationMode() { switch(AnimationMode) { case AnimationMode.OneShot: if(CurrentAnimation.Current == (CurrentAnimation.Frames.Count - 1)) { SetAnimation(PreviousAnimation.Name); AnimationMode = AnimationMode.Loop; } break; // Default assumes 'loop', as that is anticipated to be the most heavily used mode. default: break; } } protected virtual void AdvanceCurrentAnimationOne() { if(Time.time < _nextFrame) return; if(CurrentAnimation == null) return; AdvanceAnimation(); _nextFrame = Time.time + AnimationRate; EvaluateAnimationMode(); // if the animation is complete, release the animation lock. if(CurrentAnimation.IsAnimationCycleDone) _isLocked = false; } public virtual void SetAnimation(string animation) { if(string.IsNullOrEmpty(animation)) throw new ArgumentNullException("animation"); AnimationBase<T> newAnimation = Animations.FirstOrDefault(a => a.Name == animation); if(newAnimation == default(AnimationBase<T>)) return; CurrentAnimation = newAnimation; CurrentAnimation.Current = 0; } public virtual void Play(string animation, AnimationMode mode = AnimationMode.Loop) { _autoPlay = true; if(CurrentAnimation == null || CurrentAnimation.Frames.Count == 0) { if(DebugMode) Debug.LogWarning("There is no current animation to play, test, advance against!"); return; } if(string.IsNullOrEmpty(animation)) animation = CurrentAnimation.Name; if(animation == CurrentAnimation.Name) return; AnimationMode = mode; PreviousAnimation = CurrentAnimation; AdvanceCurrentAnimationOne(); } public virtual void PlaySingleFrame(string animation, bool lockAnimation = false, AnimationMode mode = AnimationMode.Loop) { _autoPlay = false; if(CurrentAnimation == null || CurrentAnimation.Frames.Count == 0) { if(DebugMode) Debug.LogWarning("There is no current animation to play, test, advance against!"); return; } if(string.IsNullOrEmpty(animation)) animation = CurrentAnimation.Name; // If the new animation does not match the current animation, // and there is no lock asserted, change animations. if(animation != CurrentAnimation.Name && ! _isLocked) { if(DebugMode) Debug.Log("No lock; setting lock and animation state."); _isLocked = lockAnimation; AnimationMode = mode; PreviousAnimation = CurrentAnimation; SetAnimation(animation); } if(DebugMode) Debug.Log(String.Format("Advancing animation {0} to frame {1}...", CurrentAnimation.Name, CurrentAnimation.Current)); AdvanceCurrentAnimationOne(); } #endregion Methods } [Serializable] public class AnimationBase<T> { #region Variables / Properties public string Name; public int Current; public List<T> Frames; public bool IsAnimationCycleDone { get { return Current >= Frames.Count - 1; } } public T CurrentFrame { get { if(Current > Frames.Count) Current = 0; if(Frames == null || Frames.Count == 0 || Frames[Current] == null) throw new NullReferenceException("Animations need at least one frame to animate."); return Frames[Current]; } } #endregion Variables / Properties #region Methods public virtual void UseCurrentFrame() { } public void SwitchToNextFrame() { Current = (Current + 1) % Frames.Count; } #endregion Methods }
// 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. #define CONTRACTS_FULL using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.ClousotRegression; using System.Diagnostics.Contracts; namespace IteratorAnalysis { class ClousotRegressionTestAttribute : Attribute { } class LinkedList { public string Value=null; public LinkedList Next=null; public int Random =0; [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=206,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=169,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=103,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=213,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=112,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=117,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=141,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=146,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=151,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=158,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=178,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=183,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=188,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=195,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=52,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=60,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=65,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=72,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=77,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=82,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=89,MethodILOffset=0)] IEnumerable<string> AllValues1() { LinkedList cursor = this; yield return cursor.Value; while (cursor != null) { if (cursor.Value == "") yield return cursor.Value; else yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=135,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=142,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=147,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=152,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=159,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'cursor'",PrimaryILOffset=164,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=169,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=176,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=187,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=97,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=194,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=107,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=112,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=117,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=124,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=49,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=57,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=62,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=69,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=74,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=79,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=86,MethodILOffset=0)] IEnumerable<string> AllValues2() { LinkedList cursor = this; yield return cursor.Value; while (cursor != null) { yield return cursor.Value; cursor = cursor.Next; yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=126,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=133,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=138,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'cursor.Next'",PrimaryILOffset=143,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=148,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=88,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=155,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=98,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=103,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=108,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=115,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=40,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=48,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=53,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=60,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=65,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=70,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=77,MethodILOffset=0)] IEnumerable<string> AllValues3() { LinkedList cursor = this; yield return cursor.Value; while (cursor != null) { yield return cursor.Value; cursor = cursor.Next.Next; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=135,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=142,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=147,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=152,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=159,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=170,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=97,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=177,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=107,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=112,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=117,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=124,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=49,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=57,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=62,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=69,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=74,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=79,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=86,MethodILOffset=0)] IEnumerable<string> AllValues4() { LinkedList cursor = this; yield return cursor.Value; while (cursor != null) { yield return cursor.Value; yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=123,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=85,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=130,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=95,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=100,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=105,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=112,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=37,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=45,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=50,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=57,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=62,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=67,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=74,MethodILOffset=0)] IEnumerable<string> AllValues5() { LinkedList cursor = this; yield return cursor.Value; while (cursor != null) { yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=104,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=31,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=39,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=44,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=111,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=54,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'cursor.Next'",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=69,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=76,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'cursor'",PrimaryILOffset=81,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=86,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=93,MethodILOffset=0)] IEnumerable<string> AllValues6() { LinkedList cursor = this; while (cursor != null) { cursor = cursor.Next.Next; yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=99,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=31,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=39,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=44,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=106,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=54,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=71,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=81,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=88,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly accessing a field on a null reference 'cursor'", PrimaryILOffset = 76, MethodILOffset = 0)] IEnumerable<string> AllValues7() { LinkedList cursor = this; while (cursor != null) { cursor = cursor.Next; yield return cursor.Value; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=82,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=89,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=94,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=99,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=105,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=31,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=39,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=44,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=54,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=71,MethodILOffset=0)] IEnumerable<string> AllValues8() { LinkedList cursor = this; while (true) { yield return cursor.Value; cursor = cursor.Next; if (cursor == null) break; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=82,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=89,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=94,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=99,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=31,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=39,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=44,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=106,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=54,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=71,MethodILOffset=0)] IEnumerable<string> AllValues9() { LinkedList cursor = this; while (cursor != null) { yield return cursor.Value; cursor = cursor.Next; } } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=1,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=88,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=95,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=100,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=105,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=112,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=123,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=37,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=45,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=50,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=130,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=60,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=65,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=70,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as field receiver)",PrimaryILOffset=77,MethodILOffset=0)] IEnumerable<string> AllValues10() { LinkedList cursor = this; while (cursor != null) { yield return cursor.Value; yield return cursor.Value; } } } class Test2 { public IEnumerable<string> Test1a(string s) { Contract.Requires(s != null); //if (s.Length < 0) throw new Exception(""); Contract.Ensures(Contract.Result<IEnumerable<string>>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), (string s1) => s1 != null)); int[] x = { 1, 2 }; x.First(((int y) => y > 0)); yield return s; } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as receiver)",PrimaryILOffset=20,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as receiver)",PrimaryILOffset=28,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=55,MethodILOffset=20)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=55,MethodILOffset=28)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="assert is valid",PrimaryILOffset=41,MethodILOffset=0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: s != null", PrimaryILOffset = 55, MethodILOffset = 49)] public string Test2a(string s) { Contract.Requires(s != null); // Contract.Ensures(Contract.Result<string>() != null); var strs = Test1a("hello"); strs = Test1a(s); Contract.Assert(strs != null); strs = Test1a(null); return s; } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: s != null", PrimaryILOffset = 63, MethodILOffset = 3)] public void Test2b(string s) { Test1b(null); } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: s != null", PrimaryILOffset = 22, MethodILOffset = 3)] public void Test2c(string s) { Test1c(null); } [ClousotRegressionTestAttribute] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as receiver)",PrimaryILOffset=16,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=59,MethodILOffset=16)] #if NETFRAMEWORK_4_0 [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=39,MethodILOffset=54)] #else [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=44,MethodILOffset=54)] #endif [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 59, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: input != null", PrimaryILOffset = 59, MethodILOffset = 70)] #if !NETFRAMEWORK_4_0 [RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven",PrimaryILOffset=22,MethodILOffset=54)] #else [RegressionOutcome(Outcome=ProofOutcome.Top,Message="requires unproven: collection != null (collection)",PrimaryILOffset=17,MethodILOffset=54)] #endif public void Test2d(IEnumerable<string> s) { Contract.Requires(s != null); IEnumerable<string> resultEnum = Test1d(s); Contract.Assert(Contract.ForAll(resultEnum, (string s1) => s1 != null)); s = null; Test1d(s); } public IEnumerable<string> Test1b(string s) { if (s == null) throw new Exception(""); Contract.EndContractBlock(); yield return s; } public void Test1c(string s) { if (s == null) throw new Exception(""); Contract.EndContractBlock(); } //public string s1; //[ContractInvariantMethod] //protected void ObjectInvariant() { // Contract.Invariant(s1 != null); //} // iteartor methods with type parameters public IEnumerable<T> Test1d<T>(IEnumerable<T> input) { Contract.Requires(input != null); Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<T>>(), (T s1) => s1 != null)); foreach (T t in input) yield return t; } public void Test1e<T>(IEnumerable<T> input) { Contract.Requires(Contract.ForAll(input, (T s) => s != null)); } } }